var type = $("#hfType").val();
var msg = $("#hfMsg").val();
var isDemo = $("#hfIsDemo").val() === "1";
var isCloud = $("#hfIsCloud").val() === "1";
var loginHelpText = $("#hfLoginHelpText").val();
var lang = $("#hfLang").val();
var serverPerfixGheyas = $("#hfServerPerfixGheyas").val();
$(document).ready(function () {
    initial();
    if (loginHelpText) {
        var loginHelpLink = $("#hfLoginHelpLink").val();
        var resolveUrl = $("#hfResolveUrl").val();
        var helpLink = loginHelpLink ? "<br><a style=\"float:left;direction:ltr;line-height:34px;\" href=\"" + loginHelpLink + "\" target=\"blank\">" + loginHelpLink + "</a>" : "";
        var innerHtml = "<img src=\"" + resolveUrl + "\" style=\"width:24px;margin-left:5px;\" />" + loginHelpText + helpLink;
        $("#pnlHelp").html(innerHtml);
        $("#pnlHelp").show();
    }

    if (msg) {
        msgLower = msg.toLowerCase();
        if (msgLower.includes("sessiontimeouttimer"))
            $("#lblError").text(window.top.sessionTimeoutTimer);
        else if (msgLower.includes("sessiontimeout"))
            $("#lblError").text(window.top.sessionTimeout);
        else if (msgLower.includes("gheyassessionexpired"))
            $("#lblError").text(window.top.gheyasSessionExpired);
        else if (msgLower.includes("moreuser"))
            $("#lblError").text(window.top.moreUser);
        else
            $("#lblError").text(msg);
    }

    $("#lblVer").text("Build: ver " + $("#hfversionInfo").val());

    if (isCloud) {
        $("#pnlPurchase").show();
        $('#serverBox').hide();
    }
    else
        $("#pnlPurchase").hide();


    $('.cookie-accept').click(function () {
        //setCookie('accept', '1');
        //$('#activeCookie').remove();
    });

    $(".div-rectangle").click(function () {
        $('.div-rectangle .div-cricle').removeClass("selected-lang");
        $(this).find('.div-cricle').addClass("selected-lang");
    });

    //if (getCookie('enable') === '1') {
    //    if (getCookie('accept') !== '1')
    //        $('#activeCookie').show();
    //} else {
    //    $('#deactiveCookie').show();
    //}

    $('#txtChangePass').keypress(function (e) {
        if (e.keyCode === 13) {
            $('#txtChangePassConfirm').focus();
            return false;
        }
        return true;
    });
    $('#txtChangePassConfirm').keypress(function (e) {
        if (e.keyCode === 13) {
            $('#btnChangePass').trigger('click');
            return false;
        }
        return true;
    });
    $('#txtUserNameLogin').keypress(function (e) {
        if (e.keyCode === 13) {
            $('#txtPasswordLogin').focus();
            return false;
        }
        return true;
    });
    $('#txtPasswordLogin').keypress(function (e) {
        if (e.keyCode === 13) {
            $('#btnLogin').trigger('click');
            return false;
        }
        return true;
    });
    $('#txtCaptcha').keypress(function (e) {
        if (e.keyCode === 13) {
            $('#btnLogin').trigger('click');
            return false;
        }
        return true;
    });
    $('#txtNewPass').keypress(function (e) {
        if (e.keyCode === 13) {
            $('#txtNewPassConfirm').focus();
            return false;
        }
        return true;
    });
    $('#txtNewPassConfirm').keypress(function (e) {
        if (e.keyCode === 13) {
            $('#btnConfirm').trigger('click');
            return false;
        }
        return true;
    });

});
async function initial() {
    await initServers();
    var serverSelectedLength = $("#cboServers option").length;
    if (isDemo) {
        setTimeout(function () {
            $("#txtPasswordLogin").val("demo");
            $("#txtUserNameLogin").val("demo");
        }, 100);
        $("#serverNames").hide();

        if (type && serverSelectedLength > 0)
            $("#cboServers option[name='" + type + "']").prop("selected", true);
    } else if (serverPerfixGheyas && serverSelectedLength > 0)
        $("#cboServers").val(serverPerfixGheyas);

    var languageList = eval($("#hfLoadLanguage").val());
    if (languageList.length > 0) {
        setLanguageContainer(languageList);
        if (lang) {
            if (lang.toLowerCase() !== "fa")
                $("#lblLang").text(languageList.filter(x => x.Name.toLowerCase() == lang.toLowerCase())[0].FullName);
            $(".radio-control[name='lang'][data-id='" + lang + "']").prop("checked", true);
        }
    }
}
async function initServers() {
    if (isCloud)
        return;
    await ajax({
        url: "GeneralApi/InitServers",
        success: function (result) {
            $("#cboServers").empty();
            if (result.length > 0) {
                result.forEach(function (item, index) {
                    $("#cboServers").append("<option " + (index === 0 ? "selected='selected'" : "") + " value='" + item.Code + "' name='" + item.Name + "'>" + item.Name + "</option>");
                });
            }
            if (result.length > 1)
                $("#serverNames").show();
            else
                $("#serverNames").hide();
        }
    });
}
function setLanguageContainer(languageList) {
    languageList.forEach(function (item) {
        var $div = $(".template-language-group").clone();
        $div.removeClass("template-language-group").removeAttr("hidden");
        $div.addClass("col-xs-12 center-vertical");
        $div.attr("onclick", "$(this).find('.radio-control').prop('checked',true);")
        $div.find("[name='lang']").attr("data-id", item.Name.toLowerCase());
        $div.find("label").text(item.FullName);
        $("#divLanguageContainer").append($div);
    });
}
function getCookie(cName) {
    var name = cName + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1);
        if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
    }
    return "";
}
function setCookie(cName, cValue, cHours) {
    if (!cHours)
        cHours = 8760;//365 days
    var date = new Date();
    date.setHours(date.getHours() + cHours);
    var expires = "expires=" + date.toUTCString();
    document.cookie = cName + "=" + cValue + "; " + expires + ";path=/";
}
function showPassword(main) {
    if ($('#txtPasswordLogin').attr('type') === 'text') {
        $('#txtPasswordLogin').attr('type', 'password');
        $(main).attr('src', 'img/pages/general/show.svg');
    }
    else {
        $('#txtPasswordLogin').attr('type', 'text');
        $(main).attr('src', 'img/pages/general/hide.svg');
    }
}
function validatePass(value) {
    //return /^(?=.*\d)[A-Za-z\W\d]{6,}$/.test(value);
    return value.length > 3;
}
function login() {
    $('#lblError').text('');
    if ($('#txtUserNameLogin').val().trim() === '' || $('#txtPasswordLogin').val().trim() === '') {
        $('#lblError').text(window.top.enterUsername);
        return false;
    }
    var browserInfo = getBrowserInfo();
    var registrationSystem = { DeviceName: browserInfo.browserName, DeviceVersion: browserInfo.browserVersion, DeviceType: 1 };

    ajax({
        loading: true,
        url: "GeneralApi/LoginUser",
        data: {
            registrationSystem: registrationSystem,
            width: $(window).width(),
            height: $(window).height(),
            server: isCloud ? "0" : $('#cboServers').val(),
            lang: $(".radio-control[name='lang']:checked").attr("data-id"),
            userName: $('#txtUserNameLogin').val().trim(),
            password: $('#txtPasswordLogin').val().trim(),
            captcha: $('#txtCaptcha').val(),
            captchaId: getQuery('id', $("#captcha").attr("src")),
        },
        success: function (result) {
            resultLogin(result);
        },
        error: function (result) {
            closeLoading();
            reloadCaptcha();
            var error = "";
            if (result.responseJSON && result.responseJSON.Message)
                error = result.responseJSON.Message;
            else
                error = result.responseText;

            if (error.startsWith("captcha"))
                $('#divCaptcha').show();
            switch (error) {
                case "ForceChangePass":
                    $('#loginBox').hide();
                    $('#mainChangePassForm').show();
                    $('#txtChangePass').focus();
                    break;
                default:
                    $('#lblError').text(error.replace('captcha', ''));
                    $('#txtPasswordLogin').val('');
                    break;
            }
        }
        , complete: function () { }
    });
}
function loginUserBySerial(serial, isExpiredDate) {
    $('#lblErrorSerial').text('');
    if (!serial) {
        $('#lblErrorSerial').text(window.top.companyName);
        return;
    }
    if (isExpiredDate) {
        var form = document.createElement("form");
        form.setAttribute("method", "POST");
        form.setAttribute("action", 'https://www.gheyas.com/cloud/extendsetting');
        form.setAttribute("target", "_blank");
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("name", "LockSerial");
        hiddenField.setAttribute("value", serial);
        form.appendChild(hiddenField);
        document.body.appendChild(form);
        form.submit();
        document.body.removeChild(form);
    }
    else {
        ajax({
            loading: true,
            url: 'GeneralApi/LoginUserBySerial',
            data: { lockSerial: serial },
            success: function (result) {
                $('#serialBox').hide();
                resultLogin(result);
            },
            error: function (result) {
                closeLoading();
                var error = '';
                if (result.responseJSON && result.responseJSON.Message)
                    error = result.responseJSON.Message;
                else
                    error = result.responseText;

                switch (error) {
                    case "ForceChangePass":
                        $('#serialBox').hide();
                        $('#loginBox').hide();
                        $('#mainChangePassForm').show();
                        $('#txtChangePass').focus();
                        break;
                    default:
                        $('#lblErrorSerial').text(error);
                        break;
                }
            },
            complete: function () { }
        });
    }
}
function resultLogin(result) {
    if (result.ErrorMessage === '0') {
        closeLoading();
        $('#loginBox').hide();
        $('#mainChangePassForm').show();
        $('#txtChangePass').focus();
    }
    else if (result.ErrorMessage === '1') {
        var serverIndex = isCloud ? 0 : $('#cboServers').val();
        var token = result.SessionId + ":" + serverIndex;
        redirectUrl(baseUrl, null, token);
    }
    else if (result.ErrorMessage === '2') {
        var serverIndex = isCloud ? 0 : $('#cboServers').val();
        var token = result.SessionId + ":" + serverIndex;
        redirectUrl(baseUrl + "Home/Setup", null, token);
    }
    else if (result.ErrorMessage === '4') {
        $('#lblError').text(window.top.subscriptionExpire);
        $('#lblErrorSerial').text(window.top.subscriptionExpire);
    }
    else if (result.ErrorMessage === '5') {
        $('#lblError').text(window.top.moreUser);
        $('#lblErrorSerial').text(window.top.moreUser);
    }
    else if (result.ErrorMessage === '6') {
        openOnlineUserModal();
    }
    else {
        $('#divMultiSerial').empty();
        var serials = result.MultiSerial;
        for (var i = 0; i < serials.length; i++) {
            $('#divMultiSerial').append(
                '<div class="multi-serial">' +
                '<div class="col-xs-9 center-vertical" style="height:100%;">' +
                '<div class="col-xs-12 no-padding text-ellipsis" style="margin-bottom: 6px;font-weight: 700;">' + serials[i].AccountName + '</div>' +
                '<div class="col-xs-12 no-padding">' + (serials[i].IsExpiredDate ? serials[i].ExpireDate : '') + '</div>' +
                '</div>' +
                '<div class= "col-xs-3 center-vertical" style="height: 100%;"><input type="button" class="btn btn-default" value="' + (serials[i].IsExpiredDate ? window.top.extended : window.top._login) + '"  style="' + (serials[i].IsExpiredDate ? 'background-color: #f57c00!important;' : 'background-color: #007890!important;') + '" onclick="loginUserBySerial(\'' + serials[i].Serial + '\',' + serials[i].IsExpiredDate + ');"></div>' +
                '</div>');
            // '<div class="float-right">' + json.Serial + '</div>' +            
        }
        closeLoading();
        $('#loginBox').hide();
        $('#serialBox').show();
    }
}
function changePassword() {
    $('#lblErrorChangePass').text('');
    if (!validatePass($('#txtChangePass').val())) {
        $('#lblErrorChangePass').text(window.top.passwordLeast4);
        return false;
    }

    if ($('#txtChangePass').val().trim() === '' || $('#txtChangePassConfirm').val().trim() === '') {
        $('#lblErrorChangePass').text(window.top.passwordReplies);
        return false;
    }
    if ($('#txtChangePass').val().trim() !== $('#txtChangePassConfirm').val().trim()) {
        $('#lblErrorChangePass').text(window.top.passwordNotSame);
        return false;
    }

    ajax({
        loading: true,
        url: 'GeneralApi/ChangeUserPassword',
        data: {
            currentPassword: $('#txtPasswordLogin').val().trim(),
            newPassword: $('#txtChangePass').val().trim(),
            confirmNewPassword: $('#txtChangePass').val().trim(),
            server: isCloud ? "0" : $('#cboServers').val()
        },
        success: function () {
            window.location.reload();
        },
        error: function (err) {
            if (err.responseJSON)
                $('#lblErrorChangePass').text(err.responseJSON.Message);
            else
                $('#lblErrorChangePass').text(err.responseText);
        }
    });
}
function closeConfirm() {
    $('#mainChangePassForm').hide();
    $('#loginBox').show();
}
function loginConfirm() {
    $('#lblErrorConfirm').text('');
    if (!validatePass($('#txtNewPass').val())) {
        $('#lblErrorConfirm').text(window.top.passwordLeast4);
        return false;
    }

    if ($('#txtNewPass').val().trim() === '' || $('#txtNewPassConfirm').val().trim() === '') {
        $('#lblErrorConfirm').text(window.top.passwordReplies);
        return false;
    }
    if ($('#txtNewPass').val().trim() !== $('#txtNewPassConfirm').val().trim()) {
        $('#lblErrorConfirm').text(window.top.passwordNotSame);
        return false;
    }

    ajax({
        loading: true,
        url: 'GeneralApi/ChangeForgetPassword',
        data: {
            password: $('#txtNewPass').val().trim(),
            server: isCloud ? "0" : $('#cboServers').val()
        },
        success: function () {
            window.location.reload();
        },
        error: function (err) {
            if (err.responseJSON)
                $('#lblErrorConfirm').text(err.responseJSON.Message);
            else
                $('#lblErrorConfirm').text(err.responseText);
        }
    });

}
function enterValidSms() {
    $('#lblErrorSms').text('');
    if ($('#txtSmsCode').val().trim() === '') {
        $('#lblErrorSms').text(window.top.receivedCode);
        return false;
    }
    ajax({
        loading: true,
        url: 'GeneralApi/IsValidSms',
        data: { smsCode: $('#txtSmsCode').val().trim() },
        success: function () {
            confirmForm();
        },
        error: function (err) {
            if (err.responseJSON)
                $('#lblErrorSms').text(err.responseJSON.Message);
            else
                $('#lblErrorSms').text(err.responseText);
        }
    });
}
function onChangeUserName() {
    var userName = $('#drpUserNames').val();
    var mobile = $($('#drpUserNames option[value="' + userName + '"]')[0]).attr('mobile');

    $('#lblUserName').text(userName);
    $('#lblUserName').attr('value', $("#drpUserNames")[0].selectedIndex);
    $('#lblConfirmUserName').text(userName);
    var mobileNo = mobile !== '' ? mobile : window.top.notSaveMobile;
    $('#lblMobileTemp').text(mobileNo);
    $('#phoneLbl').text(mobileNo);

}
function enterMobileNumber() {
    if (($('#txtMobileNumber').val().trim() === '')) {
        $('#lblErrorNotDefined').text(window.top.mobileRequired);
        return;
    }
    ajax({
        loading: true,
        url: 'GeneralApi/SearchUserAccountInfo',
        data: {
            isUserName: false,
            search: $('#txtMobileNumber').val(),
            server: isCloud ? "0" : $('#cboServers').val()
        },
        success: function (result) {
            if (result.length > 1) {
                $('#drpUserNames').empty();
                for (var i = 0; i < result.length; i++) {
                    var listArray = result[i].split(",");
                    $('#drpUserNames').append('<option value="' + listArray[3] + '" mobile="' + listArray[5] + '">' + listArray[3] + '</option>');
                }
                $('#drpUserNames').show();
                $('#selectUserName').show();
                $('#lblUserName').hide();
            }
            else {
                $('#lblUserName').show();
                $('#drpUserNames').hide();
                $('#selectUserName').hide();
            }
            $('#lblUserName').text(result[0].split(",")[3]);
            $('#lblUserName').attr('value', 0);
            $('#lblConfirmUserName').text(result[0].split(",")[3]);

            var mobileNo = result[0].split(",")[5] !== "" ? result[0].split(",")[5] : window.top.notSaveMobile;
            $('#lblMobileTemp').text(mobileNo);
            $('#phoneLbl').text(mobileNo);

            $('.part1').hide();
            $('.part2').show();
            $('.part3').hide();
        },
        error: function (err) {
            if (err.responseJSON)
                $('#lblErrorNotDefined').text(err.responseJSON.Message);
            else
                $('#lblErrorNotDefined').text(err.responseText);

        }
    });
}
function confirmForm() {
    $('.part3').hide();
    $('.part4').show();
}
function trySendingPass() {
    sendPassUsingSms();
}
function sendPassUsingSms() {
    $('#lblResendSms').hide();
    ajax({
        loading: true,
        url: 'GeneralApi/SendPassUsingSms',
        data: { value: $('#lblUserName').attr('value') },
        success: function () {
            $('#spTime').text(sec);
            $('#divTimer').show();
            myTimer();
            $('.part1').hide();
            $('.part2').hide();
            $('.part3').show();
        },
        error: function (err) {
            if (err.responseJSON)
                $('#lblErrorNotDefined').text(err.responseJSON.Message);
            else
                $('#lblErrorNotDefined').text(err.responseText);
        }
    });
}
var sec = 60;
function myTimer() {
    var timer = setInterval(function () {
        $('#spTime').text(sec--);
        if (sec === -1) {
            sec = 60;
            clearInterval(timer);
            $('#lblResendSms').show();
            $('#divTimer').hide();
        }
    }, 1000);
}
function showloginBox() {
    $('#lblErrorNotDefined').text('');
    $('#loginBox').show();
    $('.part1').hide();
    $('.part2').hide();
    $('.part3').hide();
}
function ForgetPassword() {
    $('#loginBox').hide();
    $('.part1').show();
    $('.part2').hide();
    $('.part3').hide();
}
function showHelp() {
    $('#loginBox').hide();
    $('.part1').hide();
    $('#divHelp').show();
}
function backHelpToLogin() {
    $('#divHelp').hide();
    $('#loginBox').show();
}
function showLanguage() {
    $('#loginBox').hide();
    $('#divLanguage').show();
}
function backLanguageToLogin() {
    $('#divLanguage').hide();
    $('#loginBox').show();
}
function selectServer() {
    $('#loginBox').hide();
    $('#serverBox').show();
}
function backServerToLogin() {
    $('#serverBox').hide();
    $('#loginBox').show();
}
function backSerialToLogin() {
    $('#serialBox').hide();
    $('#loginBox').show();
}
function changeLanguage() {
    ajax({
        loading: true,
        url: "GeneralApi/ChangeLanguage",
        data: { language: $(".radio-control[name='lang']:checked").attr("data-id") },
        success: function () {
            window.location.reload();
        }
    });
}
$(".help-item").click(function () {
    if ($(this).next().is(":hidden")) {
        $(this).next().show();
        $(this).css('border-bottom', 'none');
        $(this).find('.help-item-img').css('transform', 'rotate(180deg)');
    }
    else {
        $(this).next().hide();
        $(this).css('border-bottom', '1px solid #ccc');
        $(this).find('.help-item-img').css('transform', 'rotate(0deg)');
    };

});

function getBrowserInfo() {
    var navUserAgent = window.navigator.userAgent;
    var browserName = window.navigator.appName;
    var browserVersion = '' + parseFloat(window.navigator.appVersion);
    var majorVersion = parseInt(window.navigator.appVersion, 10);
    var tempNameOffset, tempVersionOffset, tempVersion;


    if ((tempVersionOffset = navUserAgent.indexOf("Opera")) != -1) {
        browserName = "Opera";
        browserVersion = navUserAgent.substring(tempVersionOffset + 6);
        if ((tempVersionOffset = navUserAgent.indexOf("Version")) != -1)
            browserVersion = navUserAgent.substring(tempVersionOffset + 8);
    } else if ((tempVersionOffset = navUserAgent.indexOf("MSIE")) != -1) {
        browserName = "Microsoft Internet Explorer";
        browserVersion = navUserAgent.substring(tempVersionOffset + 5);
    } else if ((tempVersionOffset = navUserAgent.indexOf("Chrome")) != -1) {
        browserName = "Chrome";
        browserVersion = navUserAgent.substring(tempVersionOffset + 7);
    } else if ((tempVersionOffset = navUserAgent.indexOf("Safari")) != -1) {
        browserName = "Safari";
        browserVersion = navUserAgent.substring(tempVersionOffset + 7);
        if ((tempVersionOffset = navUserAgent.indexOf("Version")) != -1)
            browserVersion = navUserAgent.substring(tempVersionOffset + 8);
    } else if ((tempVersionOffset = navUserAgent.indexOf("Firefox")) != -1) {
        browserName = "Firefox";
        browserVersion = navUserAgent.substring(tempVersionOffset + 8);
    } else if ((tempNameOffset = navUserAgent.lastIndexOf(' ') + 1) < (tempVersionOffset = navUserAgent.lastIndexOf('/'))) {
        browserName = navUserAgent.substring(tempNameOffset, tempVersionOffset);
        browserVersion = navUserAgent.substring(tempVersionOffset + 1);
        if (browserName.toLowerCase() === browserName.toUpperCase()) {
            browserName = navigator.appName;
        }
    }

    if ((tempVersion = browserVersion.indexOf(";")) != -1)
        browserVersion = browserVersion.substring(0, tempVersion);
    if ((tempVersion = browserVersion.indexOf(" ")) != -1)
        browserVersion = browserVersion.substring(0, tempVersion);

    return { browserName: browserName, browserVersion: browserVersion };


}

function openOnlineUserModal() {
    closeLoading();
    var serverIndex = isCloud ? 0 : $('#cboServers').val();
    redirectUrl("General/OnlineUsers?islogin=1&serverindex=" + serverIndex, "iframeOnlineUser",)
    $("#onlineUserModal").modal();
}

function reloadCaptcha() {
    var src = $('#captcha').attr('src');
    var v = getQuery("v", src);
    src = v ? src.substring(0, src.length - (v.length + 3)) + "&v=" + (Number(v) + 1) : src + "&v=1";
    $('#captcha').attr('src', src);
}


