(function($, undefined) {
    // initialize the library with the API key
    FB.init({
        apiKey: settings.FACEBOOK_APP_ID,
        status: true,
        cookie: true,
        xfbml: false
    });
    
    // fetch the status on load
    function goto_next($oButton) {
        var sGoToNext = "";
        var $oGoToNext = $oButton.parents("form").find("[name=goto_next]");
        if ($oGoToNext.length) {
            sGoToNext = $oGoToNext.val();
        }
        return sGoToNext
    }
    
    var bLoggedIn = false;
    
    $('.facebook_login').live('click', function() {
        var sGoToNext = goto_next($(this));
        if (bLoggedIn) {
            if (sGoToNext) {
                location.href = "/facebook/link/?goto_next=" + sGoToNext;
            } else {
                location.href = "/facebook/link/" + location.search;
            }
        } else {
            FB.login(handleSessionResponseAndGoTo(sGoToNext), {
                perms: settings.FACEBOOK_APP_REQUIRED_PERMISSIONS
            });
        }
        return false;
    });
    
    function loginStatusReady(response) {
        bLoggedIn = !!response.session;
    }
    
    // handle a session response from any of the auth related calls
    function handleSessionResponseAndGoTo(sGoToNext) {
        return (function handleSessionResponse(response) {
            // if we dont have a session, just hide the user info
            if (!response.session) {
                return;
            }
            if (sGoToNext) {
                location.href = "/facebook/link/?goto_next=" + sGoToNext;
            } else {
                location.href = "/facebook/link/" + location.search;
            }
        });
    }
    
    FB.getLoginStatus(loginStatusReady);
    FB.Event.subscribe('auth.statusChange', loginStatusReady);
    
}(jQuery));

