
function fb_login() {
    FB.login(function (response) {
        if (response.session) {
            if (response.perms) {
                // user is logged in and granted some permissions.
                // perms is a comma separated list of granted permissions
                // A user has logged in, and a new cookie has been saved
                var user_cookie = readCookie("User");
                var user_subcookie = user_cookie.split('&');
                var current_guid = user_subcookie[0].split('=')[1];

                var fbs_cookie = readCookie("fbs_238723076545");
                fbs_cookie = fbs_cookie.replace(/"/g, '');
                var fbs_subcookie = fbs_cookie.split('&');
                var access_key = fbs_subcookie[0].split('=')[1];

                process_fblogin(current_guid, access_key);

            } else {
                // user is logged in, but did not grant any permissions
                // A user has logged in, and a new cookie has been saved
                var user_cookie = readCookie("User");
                var user_subcookie = user_cookie.split('&');
                var current_guid = user_subcookie[0].split('=')[1];

                var fbs_cookie = readCookie("fbs_238723076545");
                fbs_cookie = fbs_cookie.replace(/"/g, '');
                var fbs_subcookie = fbs_cookie.split('&');
                var access_key = fbs_subcookie[0].split('=')[1];

                process_fblogin(current_guid, access_key);
            }
        } else {
            // user is not logged in
            // The user has logged out, and the cookie has been cleared
            eraseCookie('User', '.buygb.co.uk');
            window.location = '/Handlers/Logout/DoLogout_Remote.aspx';
        }
    }, { perms: 'email,publish_stream,user_hometown,user_checkins,friends_checkins' });
}

function process_fblogin(current_guid, access_key) {

    var xmlHttp = null;
    var xmlDoc = null;

    // Create xmlHttp Object
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        try {
            // Internet Explorer
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }

    // Event Handler - EventListener
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4) // 4: The Request is complete
        {
            xmlDoc = xmlHttp.responseXML; // Response

            try {
                var FB_GUID = xmlDoc.getElementsByTagName("GUID")[0].childNodes[0].nodeValue;
                var FB_AuthKey = xmlDoc.getElementsByTagName("AuthKey")[0].childNodes[0].nodeValue;

                //write new GUID to cookie and restart session
                if (FB_GUID != current_guid) {
                    createCookie('User', 'GUID=' + FB_GUID + '&AuthKey=' + FB_AuthKey, 365, '.buygb.co.uk');
                    //alert('User:' + 'GUID=' + FB_GUID + '&AuthKey=' + FB_AuthKey);

                    window.location = '/Handlers/Logout/DoLogout_Remote.aspx';
                }
            }
            catch (e) {
                alert("An error has occured with your Facebook Login.");
            }

            xmlDoc = null;
            xmlHttp = null;
        }
    }

    // Request
    var myRand = parseInt(Math.random() * 999999);
    xmlHttp.open("GET", "/ws-internal/BuyGBAuth.asmx/MemberUpdateWithFacebook?Rand=" + myRand + "&GUID=" + current_guid + "&FBAccessKey=" + access_key + "&SessionGUID=", true);
    xmlHttp.send(null);
}

function createCookie(name, value, days, domain) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";

    if (domain != '') {
        document.cookie = name + "=" + value + expires + "; path=/; domain=" + domain;
    }
    else {
        document.cookie = name + "=" + value + expires + "; path=/";
    }
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name, domain) {
    createCookie(name, "", -1, domain);
}


