// initialize the library with the API key
FB.init({ appId: '163448827020860', status: true, cookie: true, xfbml: true});

// fetch the status on load
FB.getLoginStatus(handleSessionResponse);


$('#facebook_login_link').bind('click', function () {
    FB.login(handleSessionResponse, {scope: 'offline_access,user_interests,email,friends_interests'});
});

$('#facebook_logout_link').bind('click', function () {
    FB.logout(handleSessionResponse);
});

$('#disconnect').bind('click', function () {
    FB.api({ method: 'Auth.revokeAuthorization' }, function (response) {
        clearDisplay();
    });
});

// no user, clear display
function clearDisplay() {
    $('#user_info').hide('fast');
}

// handle a session response from any of the auth related calls
function handleSessionResponse(response) {
    // if we dont have a session, just hide the user info
    if (!response.authResponse) {
        clearDisplay();
        $('#facebook_logout_link').hide();
        return;
    }

    $.post(sys_url + '/front/call/user_aleria/facebook_connect/', response.authResponse);

    $('#facebook_login_link').hide();
    $('#facebook_logout_link').show();

    FB.api('/me', function (response) {
        $('#user_info').html('<img src="http://graph.facebook.com/' + response.username + '/picture">').show('fast');
        //$('#user_name').html(response.name);
    });
}
