﻿/// <reference path="../API/Agility.js" />
/// <reference path="../API/Agility.UGC.API.js" />
/// <reference path="../External/jquery-1.3.2-vsdoc2.js" />
/// <reference path="../External/jquery-jtemplates-vsdoc.js" />
/// <reference path="../Plugins/jquery.cookie.js" />
/// <reference path="../AgilityData.js" />
/// <reference path="../ContextUtil.js" />

Agility.RegisterNamespace("Subaru.Controls.Login");

(function(SCL) {

    var LoginDialog = null;
    var CreateProfileDialog = null;
    var MyProfileDialog = null;
    var ForgotPasswordDialog = null;

    var LoginBarSections = null;
    var _randomQueryString = null;
    var _authCookieName = null;

    var _loginCallbackFunction = null;

    $(function() {
        //bind handlers

        //button handlers
        var _hoverTimeout = -1;

        $("#lnkForgotPassword").click(_doForgotPassword);

        $("#lnkSignupForAccount").click(function() {
            LoginDialog.dialog("close");
            SCL.OnPopupCreateProfile(null);
        });

        $("#lnkLoginWithFacebook").click(function() {
            _loginWithFacebook();
        });

        $("#lnkMyProfileAccountInfo").click(function() {
            $("#pnlMyProfileHover").hide();
            _EditMyProfile(0);

        });
        $("#lnkMyProfileFavourites").click(function() {
            $("#pnlMyProfileHover").hide();
            _EditMyProfile(1);
        });

        $("#pnlLoginArea").hover(
			function() {

			    if (_hoverTimeout == -1) {
			        _hoverTimeout = setTimeout(function() {
			            _hoverTimeout = -1;
			            //over
			            var pos = $("#pnlLoginArea").offset();
			            var x = pos.left - 7;
			            var y = pos.top - 5;

			            $("#pnlMyProfileHover").css("top", y + "px");
			            $("#pnlMyProfileHover").css("left", x + "px");
			            $("#pnlMyProfileHover").show();
			        }, 100);
			    }

			},
			function() {
			    //out
			    clearTimeout(_hoverTimeout);
			    _hoverTimeout = -1;
			}
		);


        $("#pnlMyProfileHover").hover(
			function() {
			    //over
			},
			function() {
			    //out
			    $("#pnlMyProfileHover").hide();
			}
		);

        setTimeout(Subaru.Controls.Login.SetLoginStatus, 50);

    });

    SCL.SetLoginStatus = function() {
        //login status poller...
        _checkSubaruLoginStatus();

    }


    SCL.OnInit = function(pnlLoginID, loginTitle, createTitle, myProfileTitle, isAuthenticated, authCookieName) {

        var d = new Date();
        _randomQueryString = d.getFullYear() + d.getMonth() + d.getDate() + d.getHours() + d.getMinutes() + d.getSeconds();

        _authCookieName = authCookieName;

        LoginDialog = $("#" + pnlLoginID).dialog({
            autoOpen: false,
            modal: true,
            closeText: 'hide',
            dialogClass: 'LoginDialog',
            title: loginTitle,
            resizable: false,
            close: function() {
                if (Subaru.Contest.ContestOpen()) {
                    Subaru.Contest.ShowInfoDialog();
                }
            }
        });

        ForgotPasswordDialog = $("#pnlForgotPassword").dialog({
            autoOpen: false,
            modal: true,
            closeText: 'hide',
            dialogClass: 'ForgotPasswordDialog',
            title: "",
            resizable: false
        });


        CreateProfileDialog = $("#pnlCreateProfile").dialog({
            autoOpen: false,
            modal: true,
            closeText: 'hide',
            dialogClass: 'CreateProfileDialog',
            title: createTitle,
            resizable: false,
            close: function() {
                if (Subaru.Contest.ContestOpen()) {
                    Subaru.Contest.ShowInfoDialog();
                }
            }
        });

        MyProfileDialog = $("#pnlMyProfile").dialog({
            autoOpen: false,
            modal: true,
            closeText: 'hide',
            dialogClass: 'MyProfileDialog',
            title: myProfileTitle,
            resizable: false
        });

        LoginBarSections = $("div.Login > div");
        if (isAuthenticated) {
            LoginBarSections.eq(1).show();
        }
        else {
            LoginBarSections.eq(0).show();
        }
    };

    SCL.CreateProfileLogin = function() {
        Subaru.Controls.Login.OnPopupLogin(null, null);
        CreateProfileDialog.dialog("close");
    }

    SCL.OnLogin = function(sender) {
        var button = $(sender);
        var inputs = $("div.Registered input", button.parent());
        var user = inputs.eq(0).val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        var pass = inputs.eq(1).val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');

        if (user.length > 0 && pass.length > 0) {
            _doLogin(user, pass);
        }
    };

    SCL.OnPopupLogin = function(sender, loginCallbackFunction) {
        if (LoginDialog != null) {
            if (loginCallbackFunction != undefined && $.isFunction(loginCallbackFunction)) {
                _loginCallbackFunction = loginCallbackFunction;
            }
            LoginDialog.dialog("open");

            var inputs = $("div.Registered input", LoginDialog);
            inputs.val("");
            inputs.eq(0).focus();
        }
    };

    SCL.OnPopupCreateProfile = function(sender) {

        //show the dialog
        $("#pnlCreateProfile").html('<div class="Spinner"></div>');

        CreateProfileDialog.dialog("open");

        //load the dialog content...
        var url = Agility.ResolveUrl("~/Dialogs/CreateProfile.aspx?r=" + _randomQueryString);
        $("#pnlCreateProfile").load(url, function() {
            $("#txtCreateProfileUsername").focus();

            $("#pnlCreateProfile div.btnCancel").html(Subaru.AgilityData.GetGlobalLanguageResource("lblCancel"));


            jQuery("#pnlCreateProfile .CreateProfile").keydown(function(event) {
                if (event.keyCode == 13) {
                    _doRegister();
                    return false;
                }
            });

            $("#pnlCreateProfile .btnCancel").click(function() {
                CreateProfileDialog.dialog("close");
            });

            $("#pnlCreateProfile .btnRegister").click(function() {
                _doRegister();
            });

        });

    };

    function _doRegister() {

        //show progress...
        jQuery("#pnlCreateProfile").append('<div class="Spinner"></div>');

        var msgAry = new Array();

        var username = jQuery.trim($("#txtCreateProfileUsername").val());
        var email = jQuery.trim($("#txtCreateProfileEmail").val());
        var emailVerify = jQuery.trim($("#txtCreateProfileReenterEmail").val());
        var password = jQuery.trim($("#txtCreateProfilePassword").val());
        var passwordVerify = jQuery.trim($("#txtCreateProfileReenterPassword").val());

        if (username == "") {
            msgAry[msgAry.length] = $("#pnlUsernameRequiredMessage").html();
            $("#pnlCreateProfile label[for='txtCreateProfileUsername']").parent("div").attr("className", "RequiredLabel");
        }
        if (email == "") {
            msgAry[msgAry.length] = $("#pnlEmailRequiredMessage").html();
            $("#pnlCreateProfile label[for='txtCreateProfileEmail']").parent("div").attr("className", "RequiredLabel");
        }
        if (email.toLowerCase() != emailVerify.toLowerCase()) {
            msgAry[msgAry.length] = $("#pnlEmailsDoNotMatchMessage").html();
            $("#pnlCreateProfile label[for='txtCreateProfileReenterEmail']").parent("div").attr("className", "RequiredLabel");
        }
        if (password == "" || (password.length < 4 || password.length > 10)) {
            msgAry[msgAry.length] = $("#pnlPasswordRequiredMessage").html();
            $("#pnlCreateProfile label[for='txtCreateProfilePassword']").parent("div").attr("className", "RequiredLabel");
        }

        if (password != passwordVerify) {
            msgAry[msgAry.length] = $("#pnlPasswordDoNotMatchMessage").html();
            $("#pnlCreateProfile label[for='txtCreateProfileReenterPassword']").parent("div").attr("className", "RequiredLabel");
        }

        //check if the username is taken...
        var userCheck = jQuery.ajax({
            url: Agility.ResolveUrl("~/HTTPHandlers/CheckUser.ashx"),
            async: false,
            data: { "username": username },
            dataType: "text"
        }).responseText;

        if (userCheck + "" == "1") {
            msgAry[msgAry.length] = $("#pnlUserAlreadyExistsMessage").html();
        }

        if (msgAry.length > 0) {
            $("#pnlCreateProfile .Spinner").remove();
            alert(msgAry.join("\n"));
            return;
        }

        //create the user
        jQuery.ajax({
            url: Agility.ResolveUrl("~/HTTPHandlers/Register.ashx"),
            cache: false,
            data: {
                "username": username,
                "email": email,
                "password": password,
                "referenceName": $("#pnlCreateProfileModuleReferenceName").html()
            },
            dataType: "text",
            success: function(userIDStr) {
                $("#pnlCreateProfile .Spinner").remove();
                var userID = parseInt(userIDStr);
                if (isNaN(userID) || userID < 1) {
                    //an error
                    alert($("#pnlCreateProfileGeneralError").html());
                    return;
                } else {
                    //success
                    jQuery("#pnlCreateProfile .CreateProfile").html($("#pnlCreateProfileThanks").html());

                    LoginBarSections.eq(0).hide();
                    $("#pnlMyProfileHover .Username").html(username);
                    $("#pnlLoginArea .Username").html(username);

                    LoginBarSections.eq(1).show();

                    if (LoginDialog.dialog('isOpen')) {
                        LoginDialog.dialog('close');
                    }
                }
            },
            error: function() {
                //an error
                $("#pnlCreateProfile .Spinner").remove();
                alert($("#pnlCreateProfileGeneralError").html());
                return;
            }
        })




    }

    function _doLogin(username, password) {
        var arg = {
            u: username,
            p: password
        };

        $.ajax({
            type: "POST",
            url: AgilityData_WebserviceUrl + '/AuthenticateUser',
            data: JSON.encode(arg),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(result) {
                if (result.d != undefined && result.d != null && result.d != "") {
                    LoginBarSections.eq(0).hide();

                    $("#pnlMyProfileHover .Username").html(result.d);
                    $("#pnlLoginArea .Username").html(result.d);


                    LoginBarSections.eq(1).show();

                    LoginDialog.dialog('close');

                    if (_loginCallbackFunction != undefined && $.isFunction(_loginCallbackFunction)) {
                        _loginCallbackFunction();
                        _loginCallbackFunction = null;
                    }
                }
                else {
                    alert("Username/password not found.");

                    var inputs = $("div.Registered input", LoginDialog);
                    inputs.eq(0).focus();
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                //alert(XMLHttpRequest.status + ' ' + textStatus);
                //alert(XMLHttpRequest.responseText);
            }
        });
    };

    SCL.OnLogout = function(sender, cookieName) {
        $.ajax({
            type: "POST",
            url: AgilityData_WebserviceUrl + '/SignOut',
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(result) {
                if (result.d != undefined && result.d != null) {

                    //Clear authentication cookie, again?
                    $.cookie(cookieName, null);
                    Subaru.ContextUtil.CurrentUserID = -1
                    LoginBarSections.eq(1).hide();
                    $("#pnlMyProfileHover .Username").html("");
                    $("#pnlLoginArea .Username").html("");
                    LoginBarSections.eq(0).show();

                    //if they are logged in to facebook, logout from that too..
                    if (FB.Connect && FB.Connect.get_loggedInUser) {
                        var facebookConnectID = FB.Connect.get_loggedInUser();
                        if (facebookConnectID != null) {
                            FB.Connect.logout();
                        }
                    }
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                //alert(XMLHttpRequest.status + ' ' + textStatus);
                //alert(XMLHttpRequest.responseText);
            }
        });
    };

    function _EditMyProfile(tabIndex) {


        //show the dialog
        $("#pnlMyProfile").html('<div class="Spinner"></div>');
        MyProfileDialog.dialog("open");
        $("#pnlMyProfileTabs-2").data("favesLoaded", false);

        //load the dialog content...
        var url = Agility.ResolveUrl("~/Dialogs/MyProfile.aspx?r=" + _randomQueryString);
        $("#pnlMyProfile").load(url, function() {

            $("#pnlMyProfileTabs .ProfileTabHeader li a").click(function() {
                //tab switch function
                $("#pnlMyProfileTabs .ProfileTabHeader li").each(function() {
                    $(this).removeClass("Selected");
                })

                $("#pnlMyProfileTabs .ProfileTab").each(function() {
                    $(this).hide();
                });

                var id = $(this).attr("href");
                id = id.substring(id.indexOf("#"));

                $(this).parent("li").addClass("Selected")
                $(id).show();

                //special case for the first time we click on faves...
                if (id == "#pnlMyProfileTabs-2" && $(id).data("favesLoaded") != true) {
                    _loadFaves();
                }

                return false;

            });

            //check if the user is on facebook - if so - show the facebook message
            var facebookConnectID = FB.Connect.get_loggedInUser();
            if (facebookConnectID != null) {
                $("#pnlMyProfileTabs-Facebook").show();
            } else {
                $("#pnlMyProfileTabs-NonFacebook").show();
            }

            //call the click event of the tab to load...			 
            if (tabIndex == 1) {
                $("a", $("#pnlMyProfileTabs ul.ProfileTabHeader li").get(1)).click();
            }


            //bind other events...
            jQuery("#pnlMyProfile .MyProfile").keydown(function(event) {
                if (event.keyCode == 13) {
                    _doSaveMyProfile();
                    return false;
                }
            });

            $("#pnlMyProfile .btnCancel").click(function() {
                //reset the form...
                _EditMyProfile();
                return false;
            });

            $("#pnlMyProfile .btnSaveChanges").click(function() {
                //save...

                _doSaveMyProfile();
                return false;
            });

            $("#pnlMyProfile .btnDeleteProfile").click(function() {
                //delete
                var msg = $("#pnlMyAccountDeleteConfirmationMessage").html();
                if (confirm(msg)) {

                    //show progress...
                    jQuery("#pnlMyProfile").append('<div class="Spinner"></div>');

                    $.ajax({
                        type: "POST",
                        url: AgilityData_WebserviceUrl + '/DeleteProfile',
                        data: "{}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(result) {
                            $("#pnlMyProfile .Spinner").remove();
                            MyProfileDialog.dialog("close");

                            LoginBarSections.eq(1).hide();
                            $("#pnlMyProfileHover .Username").html("");
                            $("#pnlLoginArea .Username").html("");
                            LoginBarSections.eq(0).show();

                            //Clear authentication cookie, again?
                            $.cookie(_authCookieName, null);

                        },
                        error: function() {
                            $("#pnlMyProfile .Spinner").remove();
                            alert("An error occurred.  Please refresh the page and try again.");

                        }
                    });
                }

                return false;
            });

        });
    }

    function _doSaveMyProfile() {


        //show progress
        jQuery("#pnlMyProfile").append('<div class="Spinner"></div>');

        var email = $("#txtMyAccountEmail").val();
        var password = $("#txtMyAccountPassword").val();
        var passwordVerify = $("#txtMyAccountConfirmPassword").val();

        var msgAry = new Array();

        if (email == "") {
            msgAry[msgAry.length] = $("#pnlMyAccountEmailRequiredLabel").html();
            $("#pnlMyProfile label[for='txtMyAccountEmail']").parent("div").attr("className", "RequiredLabel");
        }

        if (password != passwordVerify || (password.lenght < 4 && password.length > 10)) {
            msgAry[msgAry.length] = $("#pnlMyAccountPasswordsDontMatch").html();
            $("#pnlMyProfile label[for='txtMyAccountConfirmPassword']").parent("div").attr("className", "RequiredLabel");
        }

        if (msgAry.length > 0) {
            $("#pnlMyProfile .Spinner").remove();
            return;
        }


        //create the user
        jQuery.ajax({
            url: Agility.ResolveUrl("~/HTTPHandlers/UpdateMyProfile.ashx"),
            cache: false,
            data: {
                "email": email,
                "password": password
            },
            dataType: "text",
            success: function(userIDStr) {
                $("#pnlMyProfile .Spinner").remove();
                var userID = parseInt(userIDStr);
                if (isNaN(userID) || userID < 1) {
                    //an error
                    alert("An error occurred while saving.  Please refresh the page and try again.");
                    return;
                } else {
                    //success					
                    MyProfileDialog.dialog('close');
                }
            },
            error: function() {
                //an error
                $("#pnlMyProfile .Spinner").remove();
                alert("An error occurred while saving.  Please refresh the page and try again.");
                return;
            }
        })
    }

    function _loadFaves(pageIndex, sortColumn, sortDir, favesAry) {
        //show progress
        $("#pnlMyProfile").append('<div class="Spinner"></div>');
        $("#pnlMyProfileTabs-2").html("");

        if (pageIndex == undefined) {
            pageIndex = 0;
        }

        if (favesAry == undefined || favesAry == null) {
            favesAry = new Array();
        }

        if (sortColumn == undefined || sortColumn == null) {
            sortColumn == "CreatedOn";
        }

        if (sortDir == undefined || sortDir == null) {
            sortDir == "DESC";
        }


        //load the data for this person
        var userID = Subaru.ContextUtil.GetCurrentUserID();
        var searchArg = {
            RecordTypeName: "ProfileFavouriteActivities",
            PageSize: 2,
            RecordOffset: favesAry.length,
            SortedField: "ID",
            SortDirection: Agility.UGC.API.SortDirection.DESC,
            Search: "ProfileID = " + userID
        }


        Agility.UGC.API.SearchRecords(searchArg, function(data) {

            if (data.ResponseType != Agility.UGC.API.ResponseType.OK) {
                $("#pnlMyProfile .Spinner").remove();
                $("#pnlMyProfileTabs-2").html("An error occurred: " + data.Message);
            } else {
                //success.
                $("#pnlMyProfileTabs-2").data("favesLoaded", true);

                var myFaveCount = data.ResponseData.TotalRecords

                if (myFaveCount == 0) {
                    $("#pnlMyProfile .Spinner").remove();
                } else {
                    var faves = data.ResponseData.Records;
                    //add the activity title to these records...
                    var activityIDs = new Array();
                    for (var i = 0; i < faves.length; i++) {
                        activityIDs[activityIDs.length] = faves[i].ActivityID;
                    }

                    var actSearchArg = {
                        RecordTypeName: "Activity",
                        PageSize: 100,
                        RecordOffset: 0,
                        Search: "RecordID = " + activityIDs.join(" || RecordID = ")
                    }

                    //get the activities...
                    Agility.UGC.API.SearchRecords(actSearchArg, function(actData) {
                        $("#pnlMyProfile .Spinner").remove();

                        if (actData.ResponseType != Agility.UGC.API.ResponseType.OK) {
                            $("#pnlMyProfileTabs-2").html("An error occurred: " + actData.Message);
                        } else {

                            var actRecords = actData.ResponseData.Records;

                            for (var i = 0; i < faves.length; i++) {
                                faves[i].ActivityTitle = "Unknown";
                                for (var p = 0; p < actRecords.length; p++) {
                                    if (faves[i].ActivityID == actRecords[p].ID) {
                                        faves[i].ActivityTitle = actRecords[p].Title;
                                        faves[i].LikeCount = actRecords[p].LikeCount;
                                    }
                                }

                                favesAry[favesAry.length] = faves[i];
                            }



                            //if we still have more to load, than do that...
                            if (favesAry.length < myFaveCount) {

                                _loadFaves(pageIndex, sortColumn, sortDir, favesAry);

                            } else {
                                _loadFaves2(pageIndex, sortColumn, sortDir, favesAry)
                            }

                        }
                    });
                }
            }
        });
    }


    function _loadFaves2(pageIndex, sortColumn, sortDir, favesAry) {
        var pageSize = 6;

        //sort the array
        favesAry.sort(function(elemA, elemB) {
            var val1 = elemA[sortColumn];
            var val2 = elemB[sortColumn];

            var ret = 0;
            if (val1 < val2) ret = -1;
            if (val1 > val2) ret = 1;

            if (sortDir == "DESC") ret = ret * -1;

            return ret;
        });

        //grab the section of the faves that we want...
        var offset = pageSize * pageIndex;
        var array2 = favesAry.slice(offset, offset + pageSize);


        //load the grid															
        var template = $("#pnlFavesTableTemplate").val();

        $("#pnlMyProfileTabs-2").setTemplate(template);
        $("#pnlMyProfileTabs-2").setParam("toDateString", _toDateString);
        $("#pnlMyProfileTabs-2").processTemplate(array2);

        //bind the links...
        $("#pnlMyProfileTabs-2 a.lnkShowActivity").click(function() {
            var actID = $(this).attr("activityID");
            MyProfileDialog.dialog('close');
            Subaru.ActivityDetails.LoadActivity(actID);
        });

        //setup the pager...
        var pagesCount = Math.ceil(favesAry.length / pageSize);
        $("#pnlMyProfileTabs-2 .PagerContent").html((pageIndex + 1) + " of " + pagesCount);

        $("#pnlMyProfileTabs-2 .PagerLeft").click(function() {
            //previous
            if (pageIndex > 0) _loadFaves2(pageIndex - 1, sortColumn, sortDir, favesAry);
            return false;
        });

        $("#pnlMyProfileTabs-2 .PagerRight").click(function() {
            //next
            if (pageIndex < pagesCount - 1) _loadFaves2(pageIndex + 1, sortColumn, sortDir, favesAry);
            return false;
        });

        $("#pnlMyProfileTabs-2 .FavesTable th").click(function() {
            //sort

            var newSort = $(this).attr("fieldName");
            if (newSort == sortColumn) {
                if (sortDir == "ASC") {
                    sortDir = "DESC";
                } else {
                    sortDir = "ASC";
                }
            } else {
                sortColumn = newSort;
                sortDir = "ASC";
            }
            _loadFaves2(0, sortColumn, sortDir, favesAry);
            return false;
        });

        //set the css on the sort column
        $("#pnlMyProfileTabs-2 .FavesTable th").removeClass("ASC").removeClass("DESC");
        if (sortDir == "ASC") {
            $("#pnlMyProfileTabs-2 .FavesTable th[fieldName=" + sortColumn + "]").addClass("ASC");
        } else {
            $("#pnlMyProfileTabs-2 .FavesTable th[fieldName=" + sortColumn + "]").addClass("DESC");
        }

    }

    function _doForgotPassword() {


        //show the dialog
        $("#pnlForgotPassword").html('<div class="Spinner"></div>');

        LoginDialog.dialog("close");
        ForgotPasswordDialog.dialog("open");

        //load the dialog content...
        var url = Agility.ResolveUrl("~/Dialogs/ForgotPassword.aspx?r=" + _randomQueryString);
        $("#pnlForgotPassword").load(url, function() {
            $("#txtForgotPasswordEmail").focus();

            $("#pnlForgotPassword div.btnCancel").html(Subaru.AgilityData.GetGlobalLanguageResource("lblCancel"));


            jQuery("#pnlForgotPassword .ForgotPassword").keydown(function(event) {
                if (event.keyCode == 13) {
                    _recoverPassword();
                    return false;
                }
            });

            $("#pnlForgotPassword .btnCancel").click(function() {
                ForgotPasswordDialog.dialog("close");
            });

            $("#pnlForgotPassword .btnSubmit").click(function() {
                _recoverPassword();
            });
        });

    }

    function _recoverPassword() {

        var email = $("#txtForgotPasswordEmail").val();

        $("#pnlForgotPasswordEmail").attr("className", "Label");
        if (email == "") {
            $("#pnlForgotPasswordEmail").attr("className", "RequiredLabel");
            return;
        }

        $.ajax({
            type: "POST",
            url: AgilityData_WebserviceUrl + '/RecoverPassword',
            data: JSON.encode({ emailAddress: email, moduleContentName: $("#pnlForgotPasswordReferenceName").html() }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(result) {

                if (result.d != undefined && result.d != null && result.d == true) {
                    alert($("#pnlForgotPasswordSuccessMessage").html());
                    ForgotPasswordDialog.dialog("close");

                } else {
                    alert($("#pnlForgotPasswordErrorMessage").html());
                }
            },
            error: function() {
                alert($("#pnlForgotPasswordErrorMessage").html());
            }
        });

    }


    function _checkSubaruLoginStatus() {

        //initialize the username panels
        //only check for facebook connect if they have newly logged in
        ///?session=%7B%22session_key%22%3A%223.nKzyp4n7gxON_PsOKj1H0w__.86400.1259942400-667306275%22%2C%22uid%22%3A%22667306275%22%2C%22expires%22%3A1259942400%2C%22secret%22%3A%22PFHDt9MS5yWbWteyQrFF1w__%22%2C%22base_domain%22%3A%22subaru.staging.edentity.ca%22%2C%22sig%22%3A%227b749e8976315e336ce013b892aee33b%22%7D
        if (location.href.indexOf("session=")) {
            if (FB.Connect && FB.Connect.get_loggedInUser) {
                var facebookConnectID = FB.Connect.get_loggedInUser();
                if (facebookConnectID != null) {
                    _facebook_onlogin();
                    return;
                }
            }
        }

        var userID = Subaru.ContextUtil.GetCurrentUserID();

        if (userID > 0) {
            $.ajax({
                type: "POST",
                url: AgilityData_WebserviceUrl + '/GetCurrentUserName',
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(result) {
                    if (result.d != undefined && result.d != null && result.d != "") {
                        LoginBarSections.eq(0).hide();

                        $("#pnlMyProfileHover .Username").html(result.d);
                        $("#pnlLoginArea .Username").html(result.d);

                        LoginBarSections.eq(1).show();

                        LoginDialog.dialog('close');
                        MyProfileDialog.dialog('close');
                    }
                }
            });
        }

    }

    SCL.FacebookLogin = function() {
        _facebook_onlogin();
    }

    function _facebook_onlogin() {

        var facebookConnectID = FB.Connect.get_loggedInUser();

        if (facebookConnectID != null) {

            //get the user info from facebook
            FB.Facebook.apiClient.users_getInfo([facebookConnectID], ["username", "name", "proxied_email"], function(result, exception) {
                if (result == undefined || result == null || !$.isArray(result) || result.length < 1) {
                    return;
                }

                var userName = result[0].username;
                if (userName == undefined || userName == null) {
                    userName = result[0].name;
                }

                var emailAddress = result[0].proxied_email;

                //SignInViaFacebook(string facebookConnectID, string userName, string emailAddress)
                if (userName == undefined || userName == null) return;

                var arg = {
                    facebookConnectID: facebookConnectID,
                    userName: userName,
                    emailAddress: emailAddress
                };

                $.ajax({
                    type: "POST",
                    url: AgilityData_WebserviceUrl + '/SignInViaFacebook',
                    data: JSON.encode(arg),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(result) {
                        if (result.d != undefined && result.d != null && result.d != "") {
                            LoginBarSections.eq(0).hide();

                            $("#pnlMyProfileHover .Username").html(result.d);
                            $("#pnlLoginArea .Username").html(result.d);
                            LoginBarSections.eq(1).show();

                            LoginDialog.dialog('close');
                            MyProfileDialog.dialog('close');
                            CreateProfileDialog.dialog('close');


                            if (_loginCallbackFunction != undefined && $.isFunction(_loginCallbackFunction)) {
                                _loginCallbackFunction();
                                _loginCallbackFunction = null;
                            }
                        }
                    }
                });
            });


        }
    }

    function _toDateString(date) {
        return Date.parse(date).toString("MMM d, yyyy");
    }

})(Subaru.Controls.Login);
