        // Initialize the facebook SDK async and set the call back functions

        var 	ThisPage                                    =       location.href;
        var     FirstPageLoad                           =       true;
        var     DoneConfirmAssociation          =       false;
        var     ShowLogout                                      =       false;
        var     FBUserAccount                           =       "";
        var     RequestEmailCount                       =       0;
        var     EmailKnown                                      =       false;
        var     UserSession = "";

        window.fbAsyncInit = function() {
                FB.init({
                        appId      : 171984049027, // App ID
                        channelURL : '//braindash.com/channel.php', // Channel File
                        status     : true, // check login status
                        cookie     : true, // enable cookies to allow the server to access the session
                        oauth      : true, // enable OAuth 2.0
                        xfbml      : true  // parse XFBML
                });

                FB.getLoginStatus(function(response) {
                        if (response.status === 'connected') {
                          var uid = response.authResponse.userID;
                          var accessToken = response.authResponse.accessToken;
                          SwitchLoginButton(1);
                        } else if (response.status === 'not_authorized') {
                           SwitchLoginButton(0);
                        } else {
                           SwitchLoginButton(0);
                        }
                  });

                FB.Event.subscribe('edge.create',
                        function(response) {
                        AddBonusMoney(120);
                        }
                );
        };

        (function() {
                var e = document.createElement('script'); e.async = true;
                e.src = document.location.protocol +
                  '//connect.facebook.net/en_US/all.js';
                document.getElementById('fb-root').appendChild(e);
        }());

        function SwitchLoginButton(Login)
        {
           // alert('Testing 123');
                if (PHP_NewUser == undefined) {
                        var PHP_NewUser = 0;
                }

                if (PHP_NewUser == 1) {
                        DoneConfirmAssociation = true;
                }

                if (Login == 1) {

                        if (DoneConfirmAssociation) {
                                ProcUserLogin();
                        }
                        else {
                                DoneConfirmAssociation  =       true;
                                //      This logic tries to establish if we know this ThirdParty account already in our
                                //      Database and if so - does it belong to the same person (UniqueID)
                                //      If it's OK we execute ProcUserLogin

                                FB.api('/me', function(response) {
                                        var     JSONRequest             =       "";
                                        if ((response.id == undefined) || (response.id.length == 0)) {
                                                ProcUserLogin();
                                                return;
                                        }

                                        FacebookAccount =       response.id;
                                        JSONRequest                     +=      "AccountID="            + response.id + "&ThirdPartyID=1&AffiliateID=" + escape(PHP_AffiliateID) + "&" ;
                                        // if (PHP_Staging == 1)                                JSONRequest             +=      "Debug=UpdateUserInfo&";

                                        BrainDashApiCall        ("user/UserServer.php","user.find_third_party_account",JSONRequest,function(json_data){
                                                var     Status          =       json_data['Status'];
                                                if (Status == "ERROR") {
                                                        ProcUserLogin();
                                                        return;
                                                }
                                                var     BrainDashUniqueID       =       json_data['UniqueID'];          //      The one we currently know about in the database
                                                var     BrainDashUserID         =       json_data['UserID']                     //      The user ID we thing you should be
                                                var     SiteUniqueID            =       readCookie("BDUniq");           //      The one stored in the cookie
                                                var     MaxBrainCells           =       parseInt(json_data['MaxBrainCells']);   // If you haven't any, you're new and we don't really care what you do


                                                if ((SiteUniqueID != BrainDashUniqueID) && (MaxBrainCells > 0)) {

                                                        if ((response.name == undefined) || (response.name.length == 0)) {
                                                                ProcUserLogin();
                                                                return;
                                                        }

                                                        //      There is still something wrong with this logic. Fix on staging first.

                                                        var     DebugMessage    =       "";
                                                        if (PHP_Staging == 0) {
                                                                // ProcUserLogin();
                                                                // return;
                                                        }
                                                        else {
                                                                DebugMessage    =       "\nBrowserUniqueID: " + SiteUniqueID + "\n" +
                                                                                                        "DatabaseUniqueID: " + BrainDashUniqueID + "\n" +
                                                                                                        "DatabaseUserID: " + BrainDashUserID + "\n";
                                                        }

                                                        var     FacebookName            =       response.name;
                                                        DoneConfirmAssociation  =       true;
                                                        var answer = confirm ("Are you sure that you want to associated this game account " +
                                                                                                  "with the Facebook account for " + FacebookName + "?" + DebugMessage );
                                                        if (answer) {
                                                                ProcUserLogin();
                                                                return;
                                                        }
                                                        else {
                                                                // FacebookLogout();
                                                                alert ("Please log out from Facebook and this website");
                                                                return;
                                                        }
                                                }
                                                else {
                                                        ProcUserLogin();
                                                }
                                        });
                                });
                        }       // Not DoneConfirmAssociation
                }
                else {
                        $(".fb_button").show();
                        $(".fb_login_container").show();
                        $(".fb_logout_button").hide();
                        ShowLogout = false;
                }
        }

        function        ProcUserLogin()
        {
                if (FirstPageLoad) {
                //      CheckRequestEmail();
                }

                $(".fb_button").hide();
                $(".fb_login_container").hide();
                $(".fb_logout_button").show();
                ShowLogout = true;
                UpdateUserInfo();
                FirstPageLoad   =       false;
        }
        function        CheckRequestEmail()
        {
                RequestEmailCount       =       readCookie("AskForEmailCount");

                if ((RequestEmailCount == undefined) || (RequestEmailCount == "")) {
                        RequestEmailCount       =       3;
                        setCookie("AskForEmailCount",3);
                }

                if (PHP_Staging == 1) {
                        // RequestEmailCount    =       1;
                }
                if (RequestEmailCount > 0) {
                        var     TimeOut =       5000;
                        if (PHP_Staging == 1) {
                                TimeOut =       1000;
                        }
                        setTimeout('RequestEmailPermision()', TimeOut); //      There's loads of page refreshing going on in
                                                                                                                        //      FBC so if you do it straight away it looks pretty bad
                }

        }
        function        RequestEmailPermision()
        {

                RequestEmailCount               =       parseInt(readCookie("AskForEmailCount"));

                if (PHP_Staging == 1) {
                        // RequestEmailCount            =       1;
                }

                if (EmailKnown) {
                        return;
                }

                if (RequestEmailCount > 0) {
                        RequestEmailCount--;
                        setCookie("AskForEmailCount",RequestEmailCount);
                        FacebookLogin('email');

                }
                return;
        }



        //      Function used to add functions to a JSON string

        function        BuildAPIString(ReplyArray,FieldName,APIParameter)
        {
                if (ReplyArray[FieldName] == undefined) {
                        return  "";
                }

                if (ReplyArray[FieldName].length == 0) {
                        return "";
                }

                return APIParameter + "=" + escape(ReplyArray[FieldName]) + "&";

        }

        function        PublishFacebookFeed(Text,StreamText,ImageURL,TargetURL,Caption,TargetFacebookID)
        {

                var publish = {
                        method: 'stream.publish',
                        message: Text,
                        user_prompt_message: Caption
                };

                $.facebox.close();

                var     AddAttachment   =       0;
                if ((TargetURL != undefined) &&
                        (ImageURL != undefined) &&
                        (ImageURL.length > 0) &&
                        (TargetURL.length > 0) )        {

                                var     Media   = [{
                                        'type': 'image',
                                        'src': ImageURL,
                                        'href': TargetURL}];

                                var     Attachment = {
                                                        description: ( StreamText ),
                                                        href: TargetURL,
                                                        media: Media
                                };

                                publish['attachment']   =       Attachment;
                }

                FB.ui(publish, function(response) {
                        if (response && response.post_id) {
                                TrackGoogleEvent("Facebook","Publish Stream",Caption,0);
                                // alert('Post was published.');
                        } else {
                                // alert('Post was not published.');
                        }
                });
        }

        //      When user is logged in - update their profile on BD

        function        UpdateUserInfo()
        {

                FB.api('/me', function(response) {
                        var     JSONRequest             =       "";
                        var     FacebookAccount =       "";

                        JSONRequest                     +=      "ThirdPartyID=1&";
                        JSONRequest                     +=      "AffiliateID="                  + escape(PHP_AffiliateID) + "&";
                        JSONRequest                     +=      "CreateIfRequired="             + "1&";
                        JSONRequest                     +=      "UpdateSession="                + "1&";

                        if ((response.id != undefined) && (response.id.length > 0)) {
                                FacebookAccount =       response.id;
                                FBUserAccount   =       response.id;
                                var AvatarURL           =       "https://graph.facebook.com/" + FacebookAccount + "/picture";
                                JSONRequest                     +=      "AvatarURL="            + escape(AvatarURL) + "&";
                        }

                        JSONRequest                     +=      BuildAPIString(response,"id",                                                   "AccountID");
                        JSONRequest                     +=      BuildAPIString(response,"first_name",                                   "FirstName");
                        JSONRequest                     +=      BuildAPIString(response,"last_name",                                    "LastName");
                        JSONRequest                     +=      BuildAPIString(response,"name",                                                 "DisplayName");
                        JSONRequest                     +=      BuildAPIString(response,"timezone",                                             "TimeZoneName");

                        if ((response.email != undefined) && (response.email.length > 0)) {
                                var     EmailAddress    =       response.email;
                                RequestEmailCount       =       0;
                                EmailKnown                      =       true;
                                if (EmailAddress.indexOf("proxy") <= 0) {
                                        JSONRequest                     +=      "EmailAddress="         + escape(EmailAddress) + "&";
                                }
                        }

                        // JSONRequest                  +=      BuildAPIString(response,"proxied_email",                                "proxied_email");
                        // JSONRequest                  +=      BuildAPIString(response,"email",                                                "EmailAddress");
                        JSONRequest                     +=      BuildAPIString(response,"locale",                                               "CountryISACode");
                        JSONRequest                     +=      BuildAPIString(response,"link",                                                 "ProfileURL");

                        if (PHP_ClientUniqueID.length > 0) {
                                JSONRequest             +=      "UserUniqueID="                 +       PHP_ClientUniqueID              + "&";
                        }


                        if (response.birthday   != undefined)   {
                                birthday_date                   = response.birthday;
                                if (birthday_date.length==10) {
                                        var     ReformatDate            =       "";
                                        ReformatDate                    +=      birthday_date.substring(6,10);
                                        ReformatDate                    +=      birthday_date.substring(0,2);
                                        ReformatDate                    +=      birthday_date.substring(3,5);
                                        birthday_date                   =       ReformatDate;
                                        JSONRequest                             +=      "DateOfBirth="                  +       escape(birthday_date)           + "&";
                                }
                        }

                        if (response.sex != undefined) {
                                sex                                             = response.sex;
                                if (sex.length > 0) {
                                        sex                                     =       sex.toUpperCase().substr(0,1);
                                        JSONRequest                             +=      "Gender="                       +       escape(sex)             + "&";
                                }
                        }


                        var     FriendString    =       "";
                        FB.api('/me/friends',function(response) {

                                for ( var i=0, len=response.data.length; i<len; ++i ){
                                        var     ThisFriend              =       response.data[i];
                                        var     ThisFriendID    =       ThisFriend.id;
                                        if (FriendString.length > 0) {
                                                FriendString    +=      ",";
                                        }
                                        FriendString            +=      ThisFriendID;
                                        if (FriendString.length > 4900) {
                                                break;
                                        }
                                }
                                if (FriendString.length > 0) {
                                        JSONRequest                     +=      "Friends="                      + escape(FriendString) + "&";
                                }

                                // if (PHP_Staging == 1)                                JSONRequest             +=      "Debug=UpdateUserInf2o&";

                                BrainDashApiCall                ("user/UserServer.php","user.find_third_party_account",JSONRequest,function(json_data){

                                        Status          =       json_data['Status'];
                                        if (Status == "ERROR") {
                                                return;
                                        }

                                        //      We have correctly updated their details. Are they logged in to BD already?

                                        BrainDashUserID                         =       parseInt(json_data['UserID']);
                                        NewUser                                         =       parseInt(json_data['NewUser']);
                                        UserSessionID                           =       json_data['UserSessionID'];
                                        UniqueID                                        =       json_data['UniqueID'];
                                        var     UserWarning                             =       json_data['UserWarning'];

                                        // alert("NewUser: " + NewUser);

                                        if (NewUser == 1) {
                                                TrackGoogleEvent("Register Player","Register with Facebook Connect -  " + PHP_AffiliateName);
                                        }

                                        if (UserWarning.length > 0) {
                                                // alert(UserWarning);
                                        }

                                        // AffiliateID                                  =       json_data['AffiliateID'];

                                        //      ShowFooterComment("Update User OK: " + FBUserAccount,true);

                                        var     LogoutPos = ThisPage.toLowerCase().indexOf("logout=y");
                                        if (LogoutPos < 0) {
                                                LogoutPos = ThisPage.toLowerCase().indexOf("logout.php");
                                        }

                                        if (LogoutPos >= 0) {
                                                ThisPage="/index.php";
                                        }										
										//if((json_data['DrupalThirdPartyAccountID'] != '')){
										//	DrupalSetCookie('DFBAID', json_data['DrupalThirdPartyAccountID'], 1, json_data['DrupalCookieDomain'], json_data['DrupalCookiePath']);						
										//}
                                        JSLogin(UniqueID,UserSessionID,PHP_AffiliateID,ThisPage);
                                        $(".fb_button").hide();

                                });
                        });
                });

        }


        //      Call any BD call
        function BrainDashApiCall(WebServer,WebService,ParamString,CallBack)
        {
                var     TheURL          =       PHP_BrainDashJSONWrapper;
                TheURL                  +=      "WebService="   + WebService + "&";
                TheURL                  +=      "WebServer="    + WebServer + "&";
                TheURL                  +=      ParamString;

                TheURL          =       TheURL + "jsoncallback=?";
                // if (PHP_Staging == 1) alert("BrainDashApiCall " + TheURL );

                $.getJSON(TheURL, CallBack);
        }

        function        CheckFacebookAssociation()
        {
                if (OnLogoutPage()) {   //      See trivia.js
                        return true;
                }

                FB.api('/me', function(response) {
                        var     JSONRequest             =       "";
                        if ((response.id == undefined) || (response.id.length == 0)) {
                                return true;
                        }

                        FacebookAccount =       response.id;
                        JSONRequest                     +=      "AccountID="            + response.id + "&ThirdPartyID=1&AffiliateID=" + escape(PHP_AffiliateID) + "&" ;
                        // if (PHP_Staging == 1)                JSONRequest             +=      "Debug=CheckFacebookAssociation&";

                        BrainDashApiCall        ("user/UserServer.php","user.find_third_party_account",JSONRequest,function(json_data){
                                var     Status          =       json_data['Status'];
                                if (Status == "ERROR") {
                                        return true;
                                }
                                var     BrainDashUniqueID       =       json_data['UniqueID'];          //      The one we currently know about in the database
                                var     SiteUniqueID            =       readCookie("BDUniq");           //      The one stored in the cookie

                                if (SiteUniqueID != BrainDashUniqueID) {
                                        if ((response.name == undefined) || (response.name.length == 0)) {
                                                return true;
                                        }
                                        var     FacebookName    =       response.name;
                                        var answer = confirm ("Are you sure that you want to associated this game account with the Facebook account for " + FacebookName + "?");
                                        if (answer) {
                                                return true;
                                        }
                                        else {
                                                FacebookLogout();
                                                alert ("Please log out from Facefook and this website");
                                                return false;
                                        }
                                }
                        });
                });

        }

        function        FacebookLogin(Permissions, Redirect)
        {

                RequestEmailCount       =       parseInt(readCookie("AskForEmailCount"));
                if (RequestEmailCount <= 0) {
                        TrackGoogleEvent("Facebook","Request " + Permissions,"Reset permission " + Permissions,0);
                        Permissions     =       Permissions.replace("email","");
                }

                if ((Permissions != undefined) && (Permissions.length > 0)) {
                        TrackGoogleEvent("Facebook","Request " + Permissions,"Request permission " + Permissions,0);
                        if (RequestEmailCount > 0) {
                                 FB.login(function(response) {
                                 if (response.authResponse) {
                                        var accessToken = response.authResponse.accessToken;
                                        if (accessToken) {
                                                TrackGoogleEvent("Facebook","Request " + Permissions,"Granted permission " + Permissions,0);
                                                SwitchLoginButton(1);
                                                setTimeout(function(){
													window.location = Redirect;
												}, 4000);
                                        } else {
                                                TrackGoogleEvent("Facebook","Request " + Permissions,"Declined permission " + Permissions,0);
                                        }
                                  }
                 }, {scope:Permissions});


                                // FB.login(function(response) {}, {perms:Permissions});
                        }
                }
                else {
                        if (!ShowLogout) {      //      No point doing this if you are logged in
                                FB.login(function(response) {});
                        }
                }
        }

        function FBPostWall (title, message, description, link, picture , callback, gaGoal){

                if (typeof gaGoal == 'undefined' ) {
                         gaGoal = '/FacebookShare';
                }

                 // If there is no logo, just use the BrainDash one.
                 if(!picture){
                         picture = "http://profile.ak.fbcdn.net/hprofile-ak-snc4/41596_115811851772596_4201_n.jpg"
                 }

                 // If there is no link, just go to the BrainDash Homepage.
                 if(!link){
                         link = "http://www.braindash.com"
                 }

                 // If there is no description, use the one from Facebook.
                 if(!description){
                         description = "BrainDash is a fast growing online community jam packed full of trivia quiz, puzzle and brain games. Play free or in tournaments for cash prizes. Games include well known brands Who Wants To Be A Millionaire, Catchphrase, Bullseye, Word Wrap and Springo Bingo."
                 }


                 FB.ui(
                   {
                         method: 'feed',
                         name: title,
                         link: link,
                         picture: picture,
                         caption: 'Play Games For Real Cash',
                         description: description,
                         message: message
                   },
                   function(response) {
                           if (response.post_id){
                                        ForceAnalyticsPage(gaGoal);
                                        TrackGoogleEvent("Facebook","Wall Post",title,0);

                           }
                   }
                 );
         }

         function FBFriendsInvite (message, key, challenge){

                if (!message){
                        message = "Join me on BrainDash!"
                }

                if (!key){
                        key = null;
                }

                var     EventType       =       "Challenge Friends";
                if(!challenge){
                        challenge = 0;
                        EventType       =       "Invite Friends";
                }

                FB.ui({
                        method: 'apprequests',
                        message: message,
                        data:key
                },
                   function(response) {
                     if (response) {
                            var idsLength = response.request_ids.length;
                                                        TrackGoogleEvent(       "Facebook",EventType,"Friend Count",idsLength);
                            for (var i = 0; i < idsLength; i++){
                               AddChallengeUser(null, null, 1);
                            }
                     } else {
                       //alert('Post was not published.');
                     }
               });
         }

        function FacebookLogout()
        {
                FB.logout(function(response) {
                        JSLogout(PHP_LogoutPage);
                });
                // JSLogout(PHP_LogoutPage);

                // FB.Connect.logoutAndRedirect('/');
        }

        function AddBonusMoney(BonusMoneyID)
        {
                var     ParamString                     =       "";
                ParamString                             +=      "UserSessionID="                +       UserSessionID           + "&";
                ParamString                             +=      "BonusMoneyID="                 +       BonusMoneyID + "&";
                ParamString                             +=      "ForceIt=1&";   //      This is ignored on the live site
                BrainDashApiCall("user/UserServer.php","user.give_bonus_money",ParamString,function(json_data){
                                Status          =       json_data['Status'];
                                if (Status == "ERROR") {
                                        // alert ("Error");
                                        return;
                                }
                                else {
                                        var     Done    =       1;
                                }
                });
        }

