﻿/// <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 _invalidLoginMessage = null;

    var _loginCallbackFunction = null;
    var _contestIsClosed = false;

    $(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, invalidLoginMessage) {

        var d = new Date();
        _randomQueryString = d.getFullYear() + d.getMonth() + d.getDate() + d.getHours() + d.getMinutes() + d.getSeconds();

        _authCookieName = authCookieName;
        _invalidLoginMessage = invalidLoginMessage;

        LoginDialog = $("#" + pnlLoginID).dialog({
            autoOpen: false,
            modal: true,
            closeText: 'hide',
            dialogClass: 'LoginDialog',
            title: loginTitle,
            resizable: false,
            close: function() {
                if (!Subaru.ContextUtil.IsAuthenticated()) {
                    _loginCallbackFunction = null;
                }
                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,
            width: 603,
            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, user) {
        if (LoginDialog != null) {
            if (loginCallbackFunction != undefined && $.isFunction(loginCallbackFunction)) {
                _loginCallbackFunction = loginCallbackFunction;
            }
            LoginDialog.dialog("open");

            var inputs = $("div.Registered input", LoginDialog);
            if (user != null) {
                if (user == 'facebook') {

                    setTimeout("$('#RES_ID_fb_login')[0].click()", 2000);
                } else {
                    inputs.eq(0).val(user);
                    inputs.eq(1).focus();
                }
            } else {

                inputs.val("");
                inputs.eq(0).focus();
            }

        }
    };

    SCL.OnPopupCreateProfile = function(sender) {

        //show the dialog
        $("#pnlCreateProfile").html('<div class="CreateProfileLeft"></div><div class="CreateProfileMiddle"><div class="Spinner"></div></div><div class="CreateProfileRight"></div>');

        CreateProfileDialog.dialog("open");

        //load the dialog content...
        var url = Agility.ResolveUrl("~/Dialogs/CreateProfile.aspx?r=" + _randomQueryString);
        $("#pnlCreateProfile").load(url, function() {
            Subaru.AgilityData.LoadContentItem("EnterContestForm", SCL.PopulateContestFormContent);

            $("#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();
            });

        });

    };

    SCL.ToggleContestEntryForm = function() {

        var submittingAs = $("#ddlCreateProfileSubmittingAs").val();
        var group = $("#SubmittingAsGroup");
        var individual = $("#SubmittingAsIndividual");

        switch (submittingAs) {
            case "1":
                group.show();
                individual.hide();
                break;
            case "2":
                group.hide();
                individual.show();
                break;
            default:
                group.hide();
                individual.hide();
        }
    }

    SCL.PopulateContestFormContent = function(data) {

        _contestIsClosed = Subaru.AgilityData.FindContentItemProperty(data, "ContestIsClosed").toLowerCase() == "true";

        if (!_contestIsClosed) {

            $("#EnterContest").show();

            $("label[for=txtCreateProfileFirstName]").text(Subaru.AgilityData.FindContentItemProperty(data, "FirstNameLabel"));
            $("label[for=txtCreateProfileLastName]").text(Subaru.AgilityData.FindContentItemProperty(data, "LastNameLabel"));
            $("label[for=ddlCreateProfileDobMonth]").text(Subaru.AgilityData.FindContentItemProperty(data, "DateOfBirthLabel"));
            $("label[for=txtCreateProfileAddress]").text(Subaru.AgilityData.FindContentItemProperty(data, "AddressLabel"));
            $("label[for=txtCreateProfileCity]").text(Subaru.AgilityData.FindContentItemProperty(data, "CityLabel"));
            $("label[for=ddlCreateProfileProvince]").text(Subaru.AgilityData.FindContentItemProperty(data, "ProvinceLabel"));
            $("label[for=txtCreateProfilePostalCode]").text(Subaru.AgilityData.FindContentItemProperty(data, "PostalCodeLabel"));
            $("label[for=txtCreateProfilePhoneNumber]").text(Subaru.AgilityData.FindContentItemProperty(data, "PhoneNumberLabel"));
            $("label[for=chkCreateProfileContestTerms]").text(Subaru.AgilityData.FindContentItemProperty(data, "ContestRulesLabel"));
            $("#aCreateProfileContestTerms").text(Subaru.AgilityData.FindContentItemProperty(data, "ContestRulesLink"));
            $("#aCreateProfileContestTerms").attr("href", Subaru.AgilityData.FindContentItemProperty(data, "ContestRulesHref"));

            var submittingAsVisible = (Subaru.AgilityData.FindContentItemProperty(data, "ShowGroupAndIndividualOptions").toLowerCase() == "true");
            $("#hdnSubmittingAs").val(submittingAsVisible);

            if (submittingAsVisible) {
                $("label[for=ddlCreateProfileSubmittingAs]").text(Subaru.AgilityData.FindContentItemProperty(data, "SubmittingAsLabel"));
                $("#oSelectOne").text(Subaru.AgilityData.FindContentItemProperty(data, "SelectOneLabel"));
                $("#oGroup").text(Subaru.AgilityData.FindContentItemProperty(data, "GroupLabel"));
                $("#oIndividual").text(Subaru.AgilityData.FindContentItemProperty(data, "IndividualLabel"));
                $("label[for=txtCreateProfileOrganizationName]").text(Subaru.AgilityData.FindContentItemProperty(data, "OrganizationNameLabel"));
                $("label[for=txtCreateProfileWebsiteUrl]").text(Subaru.AgilityData.FindContentItemProperty(data, "WebsiteUrlLabel"));
                $("#SubmittingAsIndividual span").html(Subaru.AgilityData.FindContentItemProperty(data, "SelectPrizeLabel"));
                $("label[for=rbPrize1]").text(Subaru.AgilityData.FindContentItemProperty(data, "Prize1Label"));
                $("label[for=rbPrize2]").text(Subaru.AgilityData.FindContentItemProperty(data, "Prize2Label"));

                $("#SubmittingAs").show();
            }

            Subaru.Common.PopulateDateOfBirthControls("ddlCreateProfileDobMonth", "ddlCreateProfileDobDay", "ddlCreateProfileDobYear");

            var contestEntryCheckedByDefault = Subaru.AgilityData.FindContentItemProperty(data, "ContestEntryCheckedByDefault").toLowerCase() == "true";
            
            if (contestEntryCheckedByDefault) {
                
                $("#chkEnterContest").attr("checked", true);
                Subaru.Controls.Login.ToggleProfileWidth();
            }
        }
    }

    function _doRegister() {

        //show progress...
        jQuery("#pnlCreateProfile .CreateProfileMiddle").append('<div class="Spinner"></div>');

        var msgAry = new Array();
        var valid = true;

        var username = Subaru.AgilityData.HTMLFilter(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());

        var firstName = jQuery.trim($("#txtCreateProfileFirstName").val());
        var lastName = jQuery.trim($("#txtCreateProfileLastName").val());
        var dateOfBirth = Subaru.Common.GetDateString("ddlCreateProfileDobMonth", "ddlCreateProfileDobDay", "ddlCreateProfileDobYear");
        var address = jQuery.trim($("#txtCreateProfileAddress").val());
        var city = jQuery.trim($("#txtCreateProfileCity").val());
        var province = $("#ddlCreateProfileProvince :selected").text();
        var postalCode = jQuery.trim($("#txtCreateProfilePostalCode").val());
        var telephoneNumber = jQuery.trim($("#txtCreateProfilePhoneNumber").val());
        var receiveUpdates = $("#chkReceiveUpdates").is(":checked");
        var submitAsEnabled = $("#hdnSubmittingAs").val().toLowerCase() == "true";
        var submittingAsGroup = ($("#ddlCreateProfileSubmittingAs").val() == "1");
        var submittingAsIndividual = ($("#ddlCreateProfileSubmittingAs").val() == "2");
        var organizationName = $("#txtCreateProfileOrganizationName").val();
        var websiteUrl = $("#txtCreateProfileWebsiteUrl").val();
        var prize1 = $("#rbPrize1").is(":checked");
        var prize2 = $("#rbPrize2").is(":checked");

        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");
        }

        if ($("#chkEnterContest").is(":checked")) {
            if (firstName.length < 1) {
                valid = false;
                $("label[for='txtCreateProfileFirstName']").parent("div").addClass("RequiredLabel");
            }
            else {
                $("label[for='txtCreateProfileFirstName']").parent("div").removeClass("RequiredLabel");
            }

            if (lastName.length < 1) {
                valid = false;
                $("label[for='txtCreateProfileLastName']").parent("div").addClass("RequiredLabel");
            }
            else {
                $("label[for='txtCreateProfileLastName']").parent("div").removeClass("RequiredLabel");
            }

            if (!Subaru.Common.DateIsValid("ddlCreateProfileDobMonth", "ddlCreateProfileDobDay", "ddlCreateProfileDobYear")) {
                valid = false;
                $("label[for='ddlCreateProfileDobMonth']").parent("div").addClass("RequiredLabel");
            }
            else {
                $("label[for='ddlCreateProfileDobMonth']").parent("div").removeClass("RequiredLabel");
            }

            if (address.length < 1) {
                valid = false;
                $("label[for='txtCreateProfileAddress']").parent("div").addClass("RequiredLabel");
            }
            else {
                $("label[for='txtCreateProfileAddress']").parent("div").removeClass("RequiredLabel");
            }

            if (city.length < 1) {
                valid = false;
                $("label[for='txtCreateProfileCity']").parent("div").addClass("RequiredLabel");
            }
            else {
                $("label[for='txtCreateProfileCity']").parent("div").removeClass("RequiredLabel");
            }

            if (province.length < 1) {
                valid = false;
                $("label[for='ddlCreateProfileProvince']").parent("div").addClass("RequiredLabel");
            }
            else {
                $("label[for='ddlCreateProfileProvince']").parent("div").removeClass("RequiredLabel");
            }

            var rePostalCode = /^[a-ceghj-npr-tvxy]\d[a-ceghj-npr-tv-z]\s*\d[a-ceghj-npr-tv-z]\d$/i;
            if ((postalCode.length > 0) && (!rePostalCode.test(postalCode))) {
                valid = false;
                $("label[for='txtCreateProfilePostalCode']").parent("div").addClass("RequiredLabel");
            }
            else {
                $("label[for='txtCreateProfilePostalCode']").parent("div").removeClass("RequiredLabel");
            }

            if (telephoneNumber.length < 1) {
                valid = false;
                $("label[for='txtCreateProfilePhoneNumber']").parent("div").addClass("RequiredLabel");
            }
            else {
                $("label[for='txtCreateProfilePhoneNumber']").parent("div").removeClass("RequiredLabel");
            }

            if (submitAsEnabled) {
                $("label[for='ddlCreateProfileSubmittingAs']").parent("div").removeClass("RequiredLabel");
                if (submittingAsGroup) {
                    if (organizationName.length < 1) {
                        valid = false;
                        $("label[for='txtCreateProfileOrganizationName']").parent("div").addClass("RequiredLabel");
                    }
                    else {
                        $("label[for='txtCreateProfileOrganizationName']").parent("div").removeClass("RequiredLabel");
                    }
                } else if (submittingAsIndividual) {
                    if ((!prize1) && (!prize2)) {
                        $("#SubmittingAsIndividual span").addClass("RequiredLabel")
                        valid = false;
                    } else {
                        $("#SubmittingAsIndividual span").removeClass("RequiredLabel")
                    }
                } else {
                    $("label[for='ddlCreateProfileSubmittingAs']").parent("div").addClass("RequiredLabel");
                    valid = false;
                }
            }

            if ($("#chkCreateProfileContestTerms").is(":checked")) {
                $("label[for='chkCreateProfileContestTerms']").parent("div").removeClass("RequiredLabel");
            }
            else {
                valid = false;
                $("label[for='chkCreateProfileContestTerms']").parent("div").addClass("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 .CreateProfileMiddle .Spinner").remove();
            alert(msgAry.join("\n"));
            return;
        }
        else if (!valid) {
            $("#pnlCreateProfile .CreateProfileMiddle .Spinner").remove();
            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 .CreateProfileMiddle .Spinner").remove();
                var userID = parseInt(userIDStr);
                if (isNaN(userID) || userID < 1) {
                    //an error
                    alert($("#pnlCreateProfileGeneralError").html());
                    return;
                } else {
                    //success
                    if ($("#chkEnterContest").is(":checked")) {
                        Subaru.Contest.SubmitEntry(firstName, lastName, dateOfBirth, address, city, province, postalCode, telephoneNumber, email, submittingAsGroup, organizationName, websiteUrl, prize1, prize2, receiveUpdates);
                    }

                    if (receiveUpdates) {
                        Subaru.NewsletterSignup.Subscribe(email, userID);
                    }

                    jQuery("#pnlCreateProfile .CreateProfile").html($("#pnlCreateProfileThanks").html());
                    jQuery("#pnlCreateProfile #EnterContestPanel").html("");

                    LoginBarSections.eq(0).hide();
                    $("#pnlMyProfileHover .Username").html(username);
                    $("#pnlLoginArea .Username").html(username);

                    LoginBarSections.eq(1).show();

                    if (LoginDialog.dialog('isOpen')) {
                        LoginDialog.dialog('close');
                    }

                    _sendWelcomeEmail(username, email, password, $("#chkEnterContest").is(":checked"));
                }
            },
            error: function() {
                //an error
                $("#pnlCreateProfile .CreateProfileMiddle .Spinner").remove();
                alert($("#pnlCreateProfileGeneralError").html());
                return;
            }
        })




    }

    _sendWelcomeEmail = function(username, email, password, isContestEntered) {

        jQuery.ajax({
            url: Agility.ResolveUrl("~/HTTPHandlers/WelcomeEmail.ashx"),
            cache: false,
            data: {
                "UserName": username,
                "EmailAddress": email,
                "Password": password,
                "IsContestEntered": (isContestEntered || _contestIsClosed)
            }
        })
    }

    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(_invalidLoginMessage);

                    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');

                            var enterContest = $("#chkEnterContest").is(":checked");

                            if (!enterContest) {
                                CreateProfileDialog.dialog('close');
                            }

                            if (_loginCallbackFunction != undefined && $.isFunction(_loginCallbackFunction)) {
                                _loginCallbackFunction();
                                _loginCallbackFunction = null;
                            }
                        }
                    }
                });
            });
        }
    }

    function _toDateString(date) {
        return Date.parse(date).toString("MMM d, yyyy");
    }

    SCL.ToggleProfileWidth = function() {

        $("#chkEnterContest").attr("disabled", "disabled");

        var extraWidth = 270;
        var isChecked = $("#chkEnterContest").is(":checked");
        var div = $(".CreateProfileDialog");

        if (isChecked) {
            div.animate({ width: "+=" + extraWidth, left: "-=" + (extraWidth / 2) }, 300, false, function() {
                $("#EnterContestPanel").fadeIn("fast");
                $("#chkEnterContest").removeAttr("disabled");
            });
        }
        else {
            $("#EnterContestPanel").fadeOut("fast", function() {
                div.animate({ width: "-=" + extraWidth, left: "+=" + (extraWidth / 2) }, 300, false);
                $("#chkEnterContest").removeAttr("disabled");
            });
        }
    }

})(Subaru.Controls.Login);

function Register() {
    Subaru.Controls.Login.OnPopupCreateProfile(null);
}
