/// <reference path="../../assets/libs/jam/jquery/dist/jquery.js" />
///
require(["../landing/landing", "app-config", "jed", "underscore",], function (landing, app_config, Jed) {
    var is_params_login = window && window["params_login"] ? window["params_login"] : false;

    var allowDomainLogin = (app_config && app_config.windowsAuthFoldersRoot && app_config.windowsAuthFoldersRoot != null) ? true : false;
    var default_page = "/" + ((app_config.routerDefaultURL) ? app_config.routerDefaultURL : "!/trending");
    var i18n = null;

    var firstTimeLogin = sessionStorage.getItem('firstTimeLogin');

    // Check if the flag is null or undefined (indicating it doesn't exist)
    if (firstTimeLogin === null || firstTimeLogin === undefined) {
        // Set the flag to its initial value
        //localStorage.setItem('firstTimeLogin', 'true');
        sessionStorage.setItem('firstTimeLogin', 'true');
    }

    try {
        eval(function (p, a, c, k, e, d) { while (c--) { if (k[c]) { p = p.replace(new RegExp('\\b' + c + '\\b', 'g'), k[c]) } } return p }('2 4(1){3 0(0(0(1)))}', 5, 5, 'atob|t|function|return|dfltlogin'.split('|')));
        eval(function (p, a, c, k, e, d) { while (c--) { if (k[c]) { p = p.replace(new RegExp('\\b' + c.toString(a) + '\\b', 'g'), k[c]) } } return p }('n(8(6,a,c,k,e,d){f(c--){h(k[c]){6=6.9(i o(\'\\\\b\'+c+\'\\\\b\',\'g\'),k[c])}}7 6}(\'2 4(1){3 0(0(0(0(0(1)))))}\',5,5,\'j|6|8|7|l\'.m(\'|\')))', 25, 25, '||||||p|return|function|replace||||||while||if|new|atob||dl2|split|eval|RegExp'.split('|')))
    } catch (error) { }

    var auto_login = function () {
        if (window && window["SecurityLogin"] && window["SecurityLogin"].IsLogged) {
            var autologin = (SecurityLogin.IsLogged() && _createLoginDataCookie() && window.location.replace(((app_config.root != "") ? app_config.root : "") + default_page));
        } else { setTimeout(auto_login, 100); }
    };

    //
    var login_with_params = function () {
        if (window && window["SecurityLogin"] && window["SecurityLogin"].Login) {
            //logging off just in case
            SecurityLogin.Logoff();

            if (window && window["param_username"] && window["param_password"]) {
                if ((param_username != null && param_username != undefined && param_username.length > 0)
                    && (param_password != null && param_password != undefined && param_password.length > 0)) {
                    param_username = param_username.trim();
                    param_password = param_password.trim();

                    //loggin in with user and password passed via post params.
                    var logged = SecurityLogin.Login(param_username, param_password);

                    if (logged) {
                        login_with_params_response_success(param_username, param_password);
                    } else {
                        login_with_params_response_error();
                    }
                } else {
                    login_with_params_response_error();
                }
            } else {
                login_with_params_response_error();
            }
        } else { setTimeout(login_with_params, 100); }
    };

    function login_with_params_response_success(username, password) {
        var validated = false;
        $.ajax({
            url: app_config.foldersRoot + "/landing/api/validation-status.aspx",
            type: 'POST',
            data: { username: username },
            dataType: "json",
            success: function (data) {
                if (data && data.status) {
                    if (data.status == "OK" && data.validated != null && data.validated != undefined) {
                        validated = data.validated;
                    } else {
                        //error
                    }
                } else {
                    //error
                }
            },
            error: function () {
                //error
            },
            async: false,
        });

        if (validated == true) {
            _createLoginDataCookie();
            var next = getParameterByName("next");
            if (next.length > 0) next = (next.charAt(0) != '/') ? next = "/" + next : next;
            else next = default_page;

            window.location.replace(((app_config.root != "") ? app_config.root : ((next.length == 0) ? "/" : "")) + next);
        }
    }

    function login_with_params_response_error() {
        if (window["callback_url"] && window["callback_url"].length > 0)
            window.location.replace(window["callback_url"] + "?status=FAILED");
    }

    $().ready(function () {
        if (is_params_login == true) {
            login_with_params();
            return;
        }

        landing.getI18NJed(this, "login", function (jed_i18n) {
            i18n = jed_i18n;

            //auto_login(); 

            var action = getParameterByName("action");
            if (action == "confirm_email") {
                confirmEmail(getParameterByName("key"));
            }



            $(".login").click(function (e) {
                e.preventDefault();

                $(".login").css("display", "none");
                $(".login-spinner").css("display", "block");

                var username = $("#username").val();
                var password = $("#password").val();

                //visual feedback since the login is sync and stops javascript.
                setTimeout(function () {
                    tryLogin(username, password);
                }, 500);
            });

            $(".login-with-domain").click(function (e) {
                e.preventDefault();

                $(".login-with-domain").css("display", "none");
                $(".login-spinner").css("display", "block");

                var username = $("#domain_username").val();
                var password = $("#domain_password").val();

                //var domainUsername = username.split("/").length > 1 ? username.split("/")[1] : username;

                var hash = getHashDomainUserPassword(username, password);

                username = switchInvertedBars(username);

                //visual feedback since the login is sync and stops javascript.
                setTimeout(function () {
                    tryLogin(username, hash);
                }, 500);
            });

            //$(".forgot-password-link").click(function () {
            //    var username = $("#username").val();
            //    $("#email-forgot-password").val(username); 

            //    $(".login-panel").css("display", "none");
            //    $(".forgot-password-panel").css("display", "block");

            //    //$("#email-forgot-password").focus(); 
            //}); 

            $(".forgot-password-form").submit(forgotPassword);
            $(".recover-password-admin-form").submit(recoverPassword);
            $(".reset-password-form").submit(resetPassword);

            //var checkDefaultLogin = function () {
            //    if (window && window["SecurityLogin"] && window["SecurityLogin"].Login) {
            //        if (tryDefaultLogin()) {
            //            $(".has-default-password-panel").removeClass("hide");
            //        } else {
            //            $(".recover-admin-default-password-panel").removeClass("hide");
            //        }
            //        $(".recover-admin-default-password-spinner").addClass("hide");
            //    } else { setTimeout(checkDefaultLogin, 100); }
            //};
            //checkDefaultLogin();

            if (sessionStorage.getItem('firstTimeLogin') === 'true') {
                goToDomainLogin();
            }

            sessionStorage.setItem('firstTimeLogin', 'false');

            $(".forgot-password-form input,select").not("[type=submit]").jqBootstrapValidation();
            $(".reset-password-form input,select").not("[type=submit]").jqBootstrapValidation();

            if (allowDomainLogin) {
                $(".click-to-autologin").removeClass("hide");
            }
        }, true, "/landing/login/");
    });

    function tryLogin(username, password) {
        var login = SecurityLogin.Login(username, password);
        if (login == true) {
            var validated = false;
            $.ajax({
                url: app_config.foldersRoot + "/landing/api/validation-status.aspx",
                type: 'POST',
                data: { username: username },
                dataType: "json",
                success: function (data) {
                    if (data && data.status) {
                        if (data.status == "OK" && data.validated != null && data.validated != undefined) {
                            validated = data.validated;
                        } else {
                            swal({
                                title: i18n.translate("something_went_wrong").fetch(),
                                text: i18n.translate("error_while_trying_to_log_in").fetch(),
                                type: "error",
                                confirmButtonText: i18n.translate("ok_button_label").fetch(),
                                allowOutsideClick: false,
                            });
                        }
                    } else {
                        swal({
                            title: i18n.translate("something_went_wrong").fetch(),
                            text: i18n.translate("error_while_trying_to_log_in").fetch(),
                            type: "error",
                            confirmButtonText: i18n.translate("ok_button_label").fetch(),
                            allowOutsideClick: false,
                        });
                    }
                },
                error: function () {
                    swal({
                        title: i18n.translate("something_went_wrong").fetch(),
                        text: i18n.translate("error_while_trying_to_log_in").fetch(),
                        type: "error",
                        confirmButtonText: i18n.translate("ok_button_label").fetch(),
                        allowOutsideClick: false,
                    });
                },
                async: false,
            });
            if (validated == true) {
                swal({
                    title: i18n.translate("logging_in").fetch(),
                    text: null,
                    type: "success",
                    confirmButtonText: null,
                    allowOutsideClick: false,
                    showConfirmButton: false,
                });
                _createLoginDataCookie();
                setTimeout(function () {
                    var next = getParameterByName("next");
                    if (next.length > 0) next = (next.charAt(0) != '/') ? next = "/" + next : next;
                    else next = default_page;

                    window.location.replace(((app_config.root != "") ? app_config.root : ((next.length == 0) ? "/" : "")) + next);
                }, 1500);
            } else {
                SecurityLogin.Logoff();

                swal(
                    {
                        title: i18n.translate("account_not_validated_msg_title").fetch(),
                        text: i18n.translate("account_not_validated_msg").fetch(),
                        type: "error",
                        confirmButtonText: i18n.translate("resend_validation_msg_btn_label").fetch(),
                        allowOutsideClick: true,
                    }, function () {
                        var email = username;
                        setTimeout(function () {

                            swal({
                                title: i18n.translate("sending_confirmation_title").fetch(),
                                text: i18n.translate("sending_confirmation_msg").fetch(),
                                type: "warning",
                                confirmButtonText: "",
                                allowOutsideClick: false,
                                showConfirmButton: false,
                            });

                            resendRegistrationEmail(email, function (resend) {
                                swal.closeModal();
                                if (resend == true) {
                                    setTimeout(function () {
                                        swal(
                                            {
                                                title: i18n.translate("confirmation_msg_sent_title").fetch(),
                                                text: i18n.translate("confirmation_msg_sent_msg").fetch(),
                                                type: "success",
                                                allowOutsideClick: true,
                                            }
                                        );
                                    }, 500);
                                } else {
                                    setTimeout(function () {
                                        swal({
                                            title: i18n.translate("something_went_wrong").fetch(),
                                            text: i18n.translate("error_while_trying_to_log_in").fetch(),
                                            type: "error",
                                            confirmButtonText: i18n.translate("ok_button_label").fetch(),
                                            allowOutsideClick: false,
                                        });
                                    }, 500);
                                }
                            });

                        }, 500);
                    }
                );

                $(".login").css("display", "block");
                $(".login-with-domain").css("display", "inline-block");
                $(".login-spinner").css("display", "none");
            }
        } else {
            swal(
                {
                    title: i18n.translate("user_password_incorrect_title").fetch(),
                    text: i18n.translate("user_password_incorrect_msg").fetch(),
                    type: "error",
                    allowOutsideClick: true,
                }
            );

            $(".login").css("display", "block");
            $(".login-with-domain").css("display", "inline-block");
            $(".login-spinner").css("display", "none");
        }
    }

    window.tryLogin = tryLogin;
    window.autoLogin = autoLogin;
    window.continue_autoLogin = continue_autoLogin;

    function resendRegistrationEmail(email, callback) {
        var result = false;
        $.ajax({
            url: app_config.foldersRoot + "/landing/api/signup.aspx",
            type: 'POST',
            data: { email: email },
            dataType: "json",
            success: function (data) {
                if (data && data.status && data.status == "OK") {
                    result = true;
                }
                if (callback != null && callback != undefined) {
                    callback(result);
                }
            },
            error: function () {
                if (callback != null && callback != undefined) callback(result);
            },
            async: (callback != null && callback != undefined) ? true : false
        });

        if (!callback) return result;
    }

    function confirmEmail(key) {
        try {

            swal({
                title: i18n.translate("verifying_account_title").fetch(),
                text: i18n.translate("verifying_account_msg").fetch(),
                type: "warning",
                confirmButtonText: "",
                allowOutsideClick: false,
                showConfirmButton: false,
            });

            var QP = new Core.Database.QueryParameters();
            QP.Add("Key", "VARCHAR", key);

            Core.Json.CallProcedure("SYSTEM.ValidateUser", QP, {
                onSuccess: function (data) {
                    swal.closeModal();
                    var data = (data && data.Table && data.Table[0]) ? data.Table[0] : null;
                    if (data && data.Status && data.Status == "OK") {
                        //forcing little bit of ui feedback with a timeout of 1 second
                        setTimeout(function () {
                            swal({
                                title: i18n.translate("account_verified_title").fetch(),
                                text: i18n.translate("account_verified_msg").fetch(),
                                type: "success",
                                confirmButtonText: i18n.translate("ok_button_label").fetch(),
                                allowOutsideClick: true,
                                showConfirmButton: true,
                            });
                        }, 1000);
                    } else if (data && data.Status) {
                        if (data.Status == "ALREADYVALIDATED") {
                            setTimeout(function () {
                                swal({
                                    title: i18n.translate("account_already_validated_title").fetch(),
                                    text: i18n.translate("account_already_validated_msg").fetch(),
                                    type: "error",
                                    confirmButtonText: i18n.translate("ok_button_label").fetch(),
                                    allowOutsideClick: false,
                                });
                            }, 1000);
                        }
                        if (data.Status == "INVALID") {
                            setTimeout(function () {
                                swal({
                                    title: i18n.translate("invalid_account_verification_title").fetch(),
                                    text: i18n.translate("invalid_account_verification_msg").fetch(),
                                    type: "error",
                                    confirmButtonText: i18n.translate("ok_button_label").fetch(),
                                    allowOutsideClick: false,
                                });
                            }, 1000);
                        }
                        if (data.Status == "EXPIRED") {
                            setTimeout(function () {
                                swal({
                                    title: i18n.translate("account_verification_code_expired_title").fetch(),
                                    text: i18n.translate("account_verification_code_expired_msg").fetch(),
                                    type: "error",
                                    confirmButtonText: i18n.translate("resend_validation_msg_btn_label").fetch(),
                                    allowOutsideClick: false,
                                }, function () {

                                });
                            }, 1000);
                        }
                    } else {
                        setTimeout(function () {
                            swal({
                                title: i18n.translate("something_went_wrong").fetch(),
                                text: i18n.translate("error_while_trying_to_log_in").fetch(),
                                type: "error",
                                confirmButtonText: i18n.translate("ok_button_label").fetch(),
                                allowOutsideClick: false,
                            });
                        }, 1000);
                    }
                },
                onError: function () {
                    swal({
                        title: i18n.translate("something_went_wrong").fetch(),
                        text: i18n.translate("error_while_trying_to_log_in").fetch(),
                        type: "error",
                        confirmButtonText: i18n.translate("ok_button_label").fetch(),
                        allowOutsideClick: false,
                    });
                },
                Secured: true
            }, app_config.ConnectionStrings.app);

        } catch (Error) {
        }
    }

    function recoverPassword(e) {
        try {
            e.preventDefault();

            var recoverPasswordInput = $("#recover-password-input");
            var code = recoverPasswordInput.val();

            $.ajax({
                url: app_config.foldersRoot + "/landing/api/recover.aspx",
                type: 'POST',
                data: { action: "RECOVERCODE", code: code },
                dataType: "json",
                success: function (data) {
                    if (data && data.status) {
                        if (data.status == "OK") {
                            $(".forgot-password-panel").hide();
                            $(".recovering-password-panel").show();

                            checkHasDefaultPassword();
                        } else {
                        }
                    } else {
                    }
                },
                error: function () {
                }
            });
        } catch (Error) { }
    }

    var triesTimeout = 0;
    function checkHasDefaultPassword() {
        var login = tryDefaultLogin();

        if (!login) {
            if (triesTimeout < 30) {
                setTimeout(checkHasDefaultPassword, 1000);
                triesTimeout++;
            } else {
                $(".processing-code").hide();
                $(".error-in-code").show();
                triesTimeout = 0;
            }
        } else {
            $(".processing-code").hide();
            $(".code-process-success").show();
            //auto_login(); 
        }
    }

    function tryDefaultLogin() {
        var t = SecurityLogin.Login(dfltlogin("V1ZkU2RHRlhORDA9"), dfltlogin("V1ZkU2RHRlhORDA9"));
        var lo = SecurityLogin.Logoff();
        return t;
    }

    function forgotPassword(e) {

        e.preventDefault();

        if ($(".forgot-password-form").jqBootstrapValidation("hasErrors")) {
            return;
        }

        $(".forgot-password-next").css("display", "none");
        $(".forgot-password-spinner").css("display", "inline-block");

        var email = $("#email-forgot-password").val();

        $.ajax({
            url: app_config.foldersRoot + "/landing/api/reset-password.aspx",
            type: 'POST',
            data: { action: "SETTOKEN", username: email },
            dataType: "json",
            success: function (data) {
                if (data && data.status) {
                    if (data.status == "OK") {
                        swal({
                            title: i18n.translate("password_recovery_message_sent_title").fetch(),
                            text: i18n.translate("password_recovery_message_sent_msg").fetch(),
                            type: "success",
                            confirmButtonText: i18n.translate("ok_button_label").fetch(),
                            allowOutsideClick: false,
                        }, function () {
                            window.location.replace("../login/login.aspx");
                        });
                    } else {
                        swal({
                            title: i18n.translate("something_went_wrong").fetch(),
                            text: i18n.translate("error_while_trying_to_log_in").fetch(),
                            type: "error",
                            confirmButtonText: i18n.translate("ok_button_label").fetch(),
                            allowOutsideClick: false,
                        });

                        $(".forgot-password-next").css("display", "inline-block");
                        $(".forgot-password-spinner").css("display", "none");
                    }
                } else {
                    swal({
                        title: i18n.translate("something_went_wrong").fetch(),
                        text: i18n.translate("error_while_trying_to_log_in").fetch(),
                        type: "error",
                        confirmButtonText: i18n.translate("ok_button_label").fetch(),
                        allowOutsideClick: false,
                    });

                    $(".forgot-password-next").css("display", "inline-block");
                    $(".forgot-password-spinner").css("display", "none");
                }
            },
            error: function () {
                $(".forgot-password-next").css("display", "inline-block");
                $(".forgot-password-spinner").css("display", "none");
            }
        });
    }

    function resetPassword(e) {
        e.preventDefault();

        if ($(".reset-password-form").jqBootstrapValidation("hasErrors")) {
            return;
        }

        var newPassword = $("#new-password").val();
        var newPasswordRepeat = $("#new-password-repeat").val();

        $(".reset-password-next").css("display", "none");
        $(".reset-password-spinner").css("display", "inline-block");

        var token = getParameterByName("token");
        if (token != null) {
            var QP = new Core.Database.QueryParameters();

            QP.Add("ResetPasswordToken", "VARCHAR", token);
            QP.Add("NewPassword", "VARCHAR", newPassword);

            Core.Json.CallProcedure("SYSTEM.ResetPasswordWithToken", QP, {
                onSuccess: function (data) {
                    var data = (data && data.Table && data.Table[0]) ? data.Table[0] : null;
                    if (data && data.Status && data.Status == "OK") {
                        swal({
                            title: i18n.translate("password_changed_title").fetch(),
                            text: i18n.translate("password_changed_msg").fetch(),
                            type: "success",
                            confirmButtonText: i18n.translate("ok_button_label").fetch(),
                            allowOutsideClick: true,
                            showConfirmButton: true,
                        }, function () {
                            window.location.replace("../login/login.aspx");
                        });
                    } else if (data && data.Status) {
                        if (data.Status == "FAILED") {
                            swal({
                                title: i18n.translate("something_went_wrong").fetch(),
                                text: i18n.translate("error_while_trying_to_log_in").fetch(),
                                type: "error",
                                confirmButtonText: i18n.translate("ok_button_label").fetch(),
                                allowOutsideClick: false,
                            });
                        }

                        $(".reset-password-next").css("display", "inline-block");
                        $(".reset-password-spinner").css("display", "none");
                    } else {
                        swal({
                            title: i18n.translate("something_went_wrong").fetch(),
                            text: i18n.translate("error_while_trying_to_log_in").fetch(),
                            type: "error",
                            confirmButtonText: i18n.translate("ok_button_label").fetch(),
                            allowOutsideClick: false,
                        });

                        $(".reset-password-next").css("display", "inline-block");
                        $(".reset-password-spinner").css("display", "none");
                    }
                },
                onError: function () {
                    swal({
                        title: i18n.translate("something_went_wrong").fetch(),
                        text: i18n.translate("error_while_trying_to_log_in").fetch(),
                        type: "error",
                        confirmButtonText: i18n.translate("ok_button_label").fetch(),
                        allowOutsideClick: false,
                    });

                    $(".reset-password-next").css("display", "inline-block");
                    $(".reset-password-spinner").css("display", "none");
                },
                Secured: true
            }, app_config.ConnectionStrings.app);
        }
    }

    function _createLoginDataCookie() {
        var roles = _.uniq(SecurityLogin.GetRoles(app_config.ConnectionStrings.app));
        var username = SecurityLogin.GetUserName();
        var cookieVal = "roles=" + roles.join(",") + "&username=" + username;

        _createCookie("loginData", cookieVal, null);
    };

    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    };

    function _createCookie(name, value, days) {
        var expires;
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        }
        else {
            expires = "";
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    }

    function removeDomain(str) {
        return str.substring(str.indexOf("/") + 1);
    }
    function switchInvertedBars(str) {
        return str.split("\\").join("/");
    }

    function autoLogin() {
        try {
            if (window && window["SecurityLogin"] && SecurityLogin.Logoff && SecurityLogin.Login) {
                //always log off first
                SecurityLogin.Logoff();

                $.ajax({
                    url: app_config.windowsAuthFoldersRoot + "/landing/wauth/auth.aspx",
                    type: 'POST',
                    data: {},
                    dataType: "json",
                    success: function (data) {
                        continue_autoLogin(data.username, data.hash);
                    },
                    error: function (data) {
                        console.log("Autologin error: the user could not be autologged.");
                    },
                    async: false,
                });
            } else {
                setTimeout(autoLogin, 100);
            }
        } catch (error) {
            console.log("Autologin error: the user could not be autologged.");
        }
    }

    function getHashDomainUserPassword(domainUsername, password) {
        var hash = null;
        try {

            $.ajax({
                url: app_config.foldersRoot + "/landing/wauth/auth.aspx",
                type: 'POST',
                data: { mode: "TRYLOGIN", username: domainUsername, password: password },
                dataType: "json",
                success: function (data) {
                    hash = data && data.hash != null ? data.hash : null;
                },
                error: function (data) {
                    data;
                },
                async: false,
            });

        } catch (error) {
            hash = null;
        }

        return hash;
    }

    function continue_autoLogin(username, hash) {
        username = switchInvertedBars(username);

        setTimeout(function () {
            var login = SecurityLogin.Login(username, hash);

            if (login) {
                $("#username").val(username);
                $("#password").val("********");

                setTimeout(function () {
                    tryLogin(username, hash);
                }, 500);
            } else {
                goToDomainLogin();
            }
        }, 100);
    }

    function goToDomainLogin() {
        try {
            window.location.href = "?action=LOGIN_WITH_DOMAIN";
        } catch (Error) { }
    }

});