(function () {
    /**
   * @module Facebook
   * Facebook Connect functionality
   */
    var F = Facebook = {
        initialize: function(api_key) {
            FB_RequireFeatures(["XFBML"], function() {
                FB.init(api_key,'/xd_receiver.html', {xfbml  : true});
            });
        },

        logout: function() {
            FB.ensureInit(function() {
                FB.Connect.logoutAndRedirect('/main/do_logout');
            });
        },


        has_connected: function() {
            FB.ensureInit(function() {
                FB.Connect.ifUserConnected(
                    function(){
                        
                    },
                    function(){
                        window.location.replace("/main/do_logout");
                    })
            });
        },

        // Determine whether the user has authorized email access
        has_email_access: function(callback_true, callback_false) {
            FB.Facebook.apiClient.fql_query(
                "select email from permissions where uid=" +
                FB.Connect.get_loggedInUser(), function(rows) {
                    if (rows[0].email == 1 && callback_true) {
                        callback_true();
                    } else if (rows[0].email == 0 && callback_false) {
                        callback_false();
                    }
                });
        },
    
        // Retrieve the user's email address
        get_email: function(callback, store_proxymail) {
            FB.Facebook.apiClient.fql_query("SELECT email FROM user WHERE uid=" +
                FB.Connect.get_loggedInUser(), function(rows) {
                    var email = rows[0].email;
                    callback(email);
                }
                );
        },
    
        // Request that the user give publish access to Allthat
        request_publish_access: function() {
            FB.ensureInit(function() {
                FB.Facebook.apiClient.fql_query(
                    "select publish_stream from permissions where uid=" +
                    FB.Connect.get_loggedInUser(), function(rows) {
                        if (rows && (rows[0].publish_stream == 0)) {
                            FB.Connect.showPermissionDialog('publish_stream', function(){});
                        }
                    });
            });
        },

        // Request that the user give email access to Allthat
        request_email_access: function() {
            FB.ensureInit(function() {
                var notice = jQuery('#expect_holder_notice');
                notice.append('Facebook initialized');
                Facebook.has_email_access(
                    function() {
                        notice.append('<br />Getting e-mail');
                        Facebook.get_email(function(email) {
                            if (email) {
                                notice.append('<br />E-mail: ' + email);
                                Facebook.store_email(email);
                            }
                        });
                    },
                    function() {
                        FB.Connect.showPermissionDialog('email,publish_stream', Facebook.save_if_email_set);
                    //                        FB.Connect.showPermissionDialog('email', Facebook.save_if_email_set);
                    });
            });
        },
    
        // Store the email if the user authorized it
        save_if_email_set : function(response) {
            if (response.indexOf('email') != -1) {
                jQuery('#expect_holder_notice').append('<br />Getting e-mail');
                Facebook.get_email(function(email) {
                    jQuery('#expect_holder_notice').append('<br />E-mail: ' + email);
                    Facebook.store_email(email);
                }, true);
            }
            else{
                jQuery.ajax({
                    type: "POST",
                    url: "/main/dont_allow_email",
                    data: "email=0",
                    beforeSend: function(){
                        jQuery('#expect_holder_notice').append('<br />not allowed');
                        jQuery('#expect_holder_notice').append('<br />switch to user typed e-mail...');
                        window.setTimeout(function(){
                            jQuery('#expect_holder_notice').hide();
                            jQuery('#expect_holder').show();
                        }, 2000);
                    },
                    success: function(msg){
                        
                    }
                });
            }
        },
    
        store_email: function(email) {
            var notice = jQuery('#expect_holder_notice');
            jQuery.ajax({
                type: "POST",
                url: "/save_email",
                data: "email=" + encodeURIComponent(email),
                beforeSend: function(){
                    notice.append('<br />saving...');
                },
                success: function(msg){
                    notice.append('<br />E-mail successfully saved');
                },
                error: function(req){
                    notice.append('<br />' + req.responseText);
                    window.location.replace("/login?email=" + email);
                }
            });
        //            new Request({
        //                url: '/save_email'
        //            }).send("email=" + encodeURIComponent(email));
        }
    };
})();