﻿/// <reference path="../ContextUtil.js" />
/// <reference path="../AgilityData.js" />

Agility.RegisterNamespace("Doritos.Controls.Login");

(function(Login) {
    var LoginDialog = null;
    var SignInOnlyDialog = null;
    var _loginCallbackFunction = null;

    $(function() {

    });


    Login.Init = function() {

        setTimeout("Doritos.Controls.Login.InitializeState()", 500);
        LoginDialog = $("#pnlLoginPopup").dialog({
            autoOpen: false,
            modal: true,
            closeText: 'hide',
            dialogClass: 'SignInDialog',
            title: "",
            resizable: false
        });

        SignInOnlyDialog = $("#pnlSignInOnly").dialog({
            autoOpen: false,
            modal: true,
            closeText: 'hide',
            dialogClass: 'SignInOnlyDialog',
            title: "",
            resizable: false
        });

        try{
            $('#txtJOTFirstName').autotab({ format: 'alpha' });
            $('#txtJOTLastName').autotab({ format: 'alpha' });
            //$('#txtJOTEmail').autotab({ format: 'text' });
        }
        catch (err) { }
    }

    Login.InitializeState = function() {
        if (Doritos.ContextUtil.IsAuthenticated()) {
            $("#pnlAccount").show();

            _checkFacebookConnect();
        }
        else {
            $("#pnlLogin").show();
        }

        $("#pnlLoginArea").show();
    }
    Login.PerformRegistration = function() {
        Login.CloseDialog();
        location.href = Agility.ResolveUrl("~/Register.aspx");
    }
    Login.OpenDialog = function() {

        $(".Captcha div").hide();

        LoginDialog.dialog("open");
        $(".JOTError").hide();

        $("#txtJOTFirstName").val("");
        $("#txtJOTLastName").val("");
        $("#txtJOTEmail").val("");
        $("#txtLoginEmail").focus();
        jQuery("#pnlLoginPopup .SignIn").keydown(function(event) {
            if (event.keyCode == 13) {
                Doritos.Controls.Login.PerformLogin();
                return false;
            }
        });
    }

    Login.OpenSignInOnlyDialog = function() {
        $("#SignInOnly").show();
        $("#ForgotPassword").hide();

        SignInOnlyDialog.dialog("open");
        jQuery("#pnlSignInOnly .MainSignIn").keydown(function(event) {
            if (event.keyCode == 13) {
                Doritos.Controls.Login.PerformSignInOnlyLogin();
                return false;
            }
        });

    }
    Login.CloseSignInOnlyDialog = function() {

        SignInOnlyDialog.dialog("close");
    }

    Login.CloseDialog = function() {

        LoginDialog.dialog("close");
    }

    Login.PerformLogin = function(sender) {

        var button = $(sender);

        var email = $("#txtLoginEmail").val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        var pass = $("#txtLoginPassword").val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');

        if (email.length > 0 && pass.length > 0) {
            $("#emailRequired").hide();
            $("#passwordRequired").hide();

            _doLogin(email, pass);
        }
        else {
            $("#emailRequired").hide();
            $("#passwordRequired").hide();
            if (email.length == 0) {
                $("#emailRequired").show();

            }

            if (pass.length == 0) {
                $("#passwordRequired").show();

            }


        }

    }

    Login.PerformForgotPassword = function() {
        $("#SignInOnly").hide();
        $("#ForgotPassword").show();

        $("#txtForgotPasswordEmail").val("");
        $("#TitleForgotPassword").show();
        $("#ForgotPasswordForm").show();
        $("#TitleThanks").hide();
        $("#ThankYou").hide();

    }

    Login.ForgotPasswordSubmit = function() {

        var email = $("#txtForgotPasswordEmail").val();
        $.ajax({
            type: "POST",
            url: AgilityData_WebserviceUrl + '/ForgotPasswordSubmit',
            data: "{'email': '" + email + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function(result) {
                if (result.d != undefined && result.d != null) {
                    $("#TitleForgotPassword").hide();
                    $("#ForgotPasswordForm").hide();
                    $("#TitleThanks").show();
                    $("#ThankYou").show();
                    $("#txtForgotPasswordEmail").val("");
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                //alert(XMLHttpRequest.status + ' ' + textStatus);
                //alert(XMLHttpRequest.responseText);
            }
        });


    }

    Login.PerformSignInOnlyLogin = function(sender, loginCallbackFunction) {
        var button = $(sender);

        var email = $("#txtSignInOnlyEmail").val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        var pass = $("#txtSignInOnlyPassword").val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');

        if (email.length > 0 && pass.length > 0) {
            $("#signInOnlyEmailRequired").hide();
            $("#signInOnlyPasswordRequired").hide();

            _doLogin(email, pass);
            if (loginCallbackFunction != undefined && $.isFunction(loginCallbackFunction)) {
                _loginCallbackFunction = loginCallbackFunction;
            }
        }
        else {
            $("#signInOnlyEmailRequired").hide();
            $("#signInOnlyPasswordRequired").hide();
            if (email.length == 0) {
                $("#signInOnlyEmailRequired").show();

            }

            if (pass.length == 0) {
                $("#signInOnlyPasswordRequired").show();

            }


        }

    }

    //    Login.PerformLogin = function(sender, loginCallbackFunction) {
    //        if (LoginDialog != null) {
    //            if (loginCallbackFunction != undefined && $.isFunction(loginCallbackFunction)) {
    //                _loginCallbackFunction = loginCallbackFunction;
    //            }
    //            var button = $(sender);

    //            var email = $("#txtLoginEmail").val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    //            var pass = $("#txtLoginPassword").val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');

    //            if (email.length > 0 && pass.length > 0) {
    //                _doLogin(email, pass);
    //            }
    //        }
    //    };
    Login.OnLogout = function(sender) {

        $.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(Doritos.ContextUtil.AuthCookieName, null);
                    Doritos.ContextUtil.CurrentUserID = -1


                    //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();
                        }
                    }

                    var url = location.href.toString().toLowerCase();

                    if (url.indexOf("accountsettings.aspx") > 0 || url.indexOf("submit.aspx") > 0) {
                        location.href = Agility.ResolveUrl("~/Home.aspx");
                    }

                    $("#pnlAccount").hide();
                    $("#pnlLogin").show();
                    _reinitializeUgcApi();
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                //alert(XMLHttpRequest.status + ' ' + textStatus);
                //alert(XMLHttpRequest.responseText);
            }
        });
    };



    function _doLogin(email, password) {
        var arg = {
            e: email,
            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 != "") {


                    //$("#pnlAccount .Username").html(result.d);
                    //$("#pnlLoginArea .Username").html(result.d);
                    $("#pnlLogin").hide();
                    $("#pnlAccount").show();
                    $("#txtLoginEmail").val("");
                    $("#txtLoginPassword").val("");
                    $("#txtSignInOnlyEmail").val("");
                    $("#txtSignInOnlyPassword").val("")
                    Login.CloseDialog();
                    Login.CloseSignInOnlyDialog();
                    _reinitializeUgcApi();

                    //won't be a just one time user anymore if they were logged in as one
                    Doritos.ContextUtil.ClearJustOneTimeUser();

                    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) {

            }
        });
    };



    function _checkFacebookConnect() {

        $("#btnFacebookLogout").hide();
        $("#btnFacebookLogout").hide();
        $("#pnlAccount .Avatar").hide();
        $("#btnFacebookConnect").show();

        FB.Connect.get_status().waitUntilReady(function(status) {

            if (status == FB.ConnectState.connected) {

                $("#btnFacebookLogout").show();
                $("#btnFacebookLogout").show();
                $("#pnlAccount .Avatar").show();
                $("#btnFacebookConnect").hide();
            }
        });

    }

    Login.ValidateEmail = function(email) {
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if (reg.test(email) == false) {
            return false;
        }

        return true;
    }

    Login.JustThisOneTimeLogin = function() {
        $(".JOTError").hide();
        var firstname = $("#txtJOTFirstName").val().replace("/[^a-zA-Z 0-9]+/g", '');
        var lastname = $("#txtJOTLastName").val().replace("/[^a-zA-Z 0-9]+/g", '');
        var email = $("#txtJOTEmail").val();
        var characters = $("#txtCaptchaCode").val();

        

        var isEmailValid = true;
        if (firstname.length == 0) {
            $("#ErrorJOTFirstName").show();
        }
        if (lastname.length == 0) {
            $("#ErrorJOTLastName").show();
        }
        if (email.length == 0 || !Login.ValidateEmail(email)) {
            isEmailValid = false;
            $("#ErrorJOTEmail").show();
        }


        

        var code = $(".Captcha input").val();


        var result = Doritos.AgilityData.VerifyCaptcha(code, characters);

        if (result == "True") {


            if (firstname.length > 0 && lastname.length > 0 && isEmailValid) {

                Doritos.ContextUtil.SetJustOneTimeUser(firstname, lastname, email);

                Login.CloseDialog();
            }
        }
        else {
            $("#ErrorJOTCaptcha").show();
        }

    }

    Login.FacebookLogin = function() {

        var facebookConnectID = FB.Connect.get_loggedInUser();

        if (facebookConnectID != null) {

            //get the user info from facebook
            FB.Facebook.apiClient.users_getInfo([facebookConnectID], ["username", "name", "first_name", "last_name", "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 firstName = result[0].first_name;
                var lastName = result[0].last_name;
                var emailAddress = result[0].email;

                //SignInViaFacebook(string facebookConnectID, string userName, string emailAddress)
                if (userName == undefined || userName == null) return;

                var arg = {
                    facebookID: facebookConnectID,
                    firstName: firstName,
                    lastName: lastName,
                    userName: userName,
                    facebookEmail: emailAddress
                };

                $.ajax({
                    type: "POST",
                    url: AgilityData_WebserviceUrl + '/AuthenticateUserViaFacebook',
                    data: JSON.encode(arg),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(result) {
                        if (result.d != undefined && result.d != null && result.d != "") {
                            $("#pnlLogin").hide();
                            $("#pnlAccount").show();
                            Login.CloseDialog();
                            Login.CloseSignInOnlyDialog();
                            _checkFacebookConnect();
                            _reinitializeUgcApi();


                        }
                    },
                    error: function() {
                        alert("The sign in process was not successful.  Please try again.");
                    }
                });

            });
        }
        
    }

    function _reinitializeUgcApi() {
        var d = new Date();
        var url = Agility.ResolveUrl("~/Scripts/UGCAPIInit.ashx/api.js?dt=" + d.toString("yyyyMMddhhmmss"));
        var html = "<scr" + "ipt type='text/javascript' src='" + url + "'></scri" + "pt>";
        $(html).appendTo($(document.body));
    }



   



})(Doritos.Controls.Login);
