﻿$(document).ready(function () {
    FB.init({
        appId: '180586111962956',
        status: true, // check login status
        cookie: true, // enable cookies to allow the server to access the session
        xfbml: true  // parse XFBML
    });
    FB.getLoginStatus(function (response) {
        onStatus(response); // once on page load
        FB.Event.subscribe('auth.statusChange', onStatus); // every status change
    });
});
var LoginUrl;
var LogoutUrl;

function Login() {
    FB.login(function (response) {
        
        if (response.authResponse) {
            LoginToWebsite(response.authResponse);
        }
        else {
            alert('fail');
        }
    });
}
function LoginToWebsite(authResponse) {
    if (!authResponse) {
        authResponse = FB.getAuthResponse();
    }
    $.post(LoginUrl, { userId: authResponse.userID, accessToken: authResponse.accessToken },
                    function (data) {
                        var obj = $.parseJSON(data);
                        location.href = obj.Url;
                    });
}
function Logout() {
    FB.logout();
    $.post(LogoutUrl, null, function (data) {
        var obj = $.parseJSON(data);
        location.href = obj.Url;
    });
    
}

/**
* This assumes the user is logged in and renders their profile picture,
* name and a logout link.
*/
function showAccountInfo() {
    FB.api(
        {
            method: 'fql.query',
            query: 'SELECT name, pic_square FROM user WHERE uid=' + FB.getAuthResponse().userID
        },
        function (response) {
            $("#FBaccount-info").html(
            '<img src="' + response[0].pic_square + '"> ' +
            response[0].name +
            ' <img onclick="Logout()" style="cursor: pointer;"' +
            'src="https://s-static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">');
            if (Authenticated == false) {
                LoginToWebsite();
            }
        }
        );
        
}

/**
* This assumes the user is logged out, and renders a login button.
*/
function showLoginButton() {
    $("#FBaccount-info").html(
    '<img onclick="Login();" style="cursor: pointer;"' +
         'src="https://s-static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">');
}

/**
* This will be called once on page load, and every time the status changes.
*/
function onStatus(response) {
    if (response.authResponse) {
        showAccountInfo();
    } else {
        showLoginButton();
    }
}

