/* Js for , Version=1775205246 */
 if(typeof(v) != "object") v = {};v.mobileLoginAgreement = "\u8bf7\u540c\u610f\u4ee5\u4e0a\u534f\u8bae";;v.mobileWrongMessage = "\u624b\u673a\u53f7\u8f93\u5165\u9519\u8bef\u8bf7\u91cd\u65b0\u8f93\u5165";;v.codeWrongMessage = "\u8bf7\u8f93\u51656\u4f4d\u6570\u5b57\u7684\u9a8c\u8bc1\u7801";;v.inputNewPasswordTip = "\u8bf7\u8f93\u5165\u60a8\u7684\u65b0\u5bc6\u7801";;v.confirmNewPasswordTip = "\u8bf7\u786e\u8ba4\u60a8\u7684\u65b0\u5bc6\u7801";;v.passwordFormatTip = "\u5bc6\u7801\u8bf7\u5305\u542b\u6570\u5b57\u548c\u5b57\u6bcd\uff0c\u516d\u4f4d\u4ee5\u4e0a";;v.passwordNotSame = "\u5bc6\u7801\u4e0e\u786e\u8ba4\u5bc6\u7801\u4e0d\u4e00\u81f4";;v.sendMobileSMS = "\u53d1\u9001\u9a8c\u8bc1\u7801";;v.isUserLoginPage = 0;;v.getCertifyCodeLang = "\u83b7\u53d6\u9a8c\u8bc1\u7801";;v.confirmSkipBindAccount = "\u8df3\u8fc7\u6b64\u6b65\u9aa4\u5c06\u4f1a\u7ed9\u60a8\u521b\u5efa\u65b0\u7684\u8d26\u53f7\uff0c\u786e\u8ba4\u4e0d\u7ed1\u5b9a\u8001\u8d26\u53f7\uff1f";;v.login = "\u767b\u5f55";;v.bind = "\u7ed1\u5b9a";;v.getCertifyCodeLang = "\u83b7\u53d6\u9a8c\u8bc1\u7801";;v.referer = "";;v.captchaEmptyMessage = "\u8bf7\u8f93\u5165\u9a8c\u8bc1\u7801";;v.reSend = "\u91cd\u65b0\u83b7\u53d6";;v.codeTip = "\u77ed\u4fe1\u9a8c\u8bc1\u7801\u5df2\u53d1\u9001\u81f3 %s";;var initcountdown   = 60;
var smscountdown      = 60;
var retrievecountdown = 60;
var countTimer;
var disableQrCodeTimer;
window.qrCodeTimer = null;
var loginSendSMS =
    {
        elementID   : "captcha",
        mobileID    : "mobile",
        senderID    : "smsLoginSender",
        senderTimer : 0,
        captchaIns  :{},
    };
/** common block */
$(function ()
{
    $('#loginModal form').append("<input type='hidden' id='fingerprint' name='fingerprint' value='" + getFingerprint() + "'>");
    $('#mobileTab input[name="isBindAccount"], #checkMobile input[name="isBindAccount"]').change(function()
    {
        if($(this).prop('checked'))
        {
            $(this).parents('form').find('#submit').val(v.bind);
        }
        else
        {
            $(this).parents('form').find('#submit').val(v.login);
        }
    });

    $('#mobile').tab('show');
    var type = $.cookie('lastLoginMethod');
    $('.nav .tab-li').removeClass('active');
    $('#loginCommon .tab-content .tab-pane').removeClass('active');
    if(!location.href.includes('type=recover')) getQrCode();

    showWechat();
    if(type)
    {
        if(type != 'mobile')
        {
            $('.tab-li.account').insertBefore('.tab-li.mobile');
            $('.tab-li.account a').click();
        }
        else
        {
            $('#mobileTab, .tab-li.mobile').addClass('active');
        }
    }
    else
    {
        $('#mobileTab, .tab-li.mobile').addClass('active');
    }

    $(".modal-dialog>.modal-content>.modal-header>.close").html("&lti class='icon icon-close-circle'>".replace('&lt', '<'));

    $('.refresh').click(function(){getQrCode();});
    $('#loginCommon #expired').click(function(){getQrCode();});

    $('.close').click(function ()
    {
        clearInterval(loginSendSMS.senderTimer);
        if(window.qrCodeTimer) clearInterval(window.qrCodeTimer);
    });
});

/* checkmobileuser */
$(document).ready(function()
{
    var countdown = 60;
    var smsSenderTimer;

    function setSmsSenderTime()
    {
        $('.mobile-captcha-wrapper .re-send').html(countdown + 's').addClass('reciprocal');
        smsSenderTimer = setInterval(function(){
            countdown -= 1;
            if(countdown > 0)
            {
                $('.mobile-captcha-wrapper .re-send').html(countdown + 's').addClass('reciprocal');
            }else{
                window.clearInterval(smsSenderTimer);
                $('.mobile-captcha-wrapper .re-send').html(v.reSend).removeClass('reciprocal');
            }
        },1000);
    }

    $('#checkMobileSender').click(function(e)
    {
        e.preventDefault();
        $('#captchaMobileError').html('');
        $.post("/sms-sendcode.html",{mobile:$('#checkMobile #mobile').val(), captchaContent: $('#checkMobile #captchaContent').val(), token:$('#token').val()},function(response)
        {
            if(response.result == 'success')
            {
                countdown = 60;
                setSmsSenderTime();
                $('#captchaBox, .sendSMS').addClass('hide');
                $('.mobile-captcha-wrapper, .submit-btn').removeClass('hide');
            }
            else
            {
                $('#captchaMobileError').html(response.message);
                if(response.captchaContent) $('#checkMobile #captchaBox .captcha-box .image-box').html(response.captchaContent);
            }
        });
    });


    $('#checkMobile .captcha-box .btn-sure').click(function()
    {
        var mobile         = $('#checkMobile #mobile').val();
        var token          = $('#checkMobile #token').val();
        var captchaContent = $('#checkMobile .reSend-captcha-wrapper input').val();
        if(!captchaContent)
        {
            $('#checkMobile .captcha-box .empty-tip').html(v.captchaEmptyMessage);
            return;
        }
        $.post("/sms-sendcode.html",{mobile:mobile, token:token, captchaContent: captchaContent},function(response)
        {
            if(response.result == 'success')
            {
                $('#checkMobile .reSend-captcha-wrapper').addClass('hide');
                countdown = 60;
                setSmsSenderTime();
                $('#captcha').val('');
                $('#checkMobile #captchaLabel').html('');
            }
            else
            {
                $('#checkMobile .captcha-box .empty-tip').html(response.message);
                if(response.captchaContent) $('#checkMobile .reSend-captcha-wrapper .image-box').html(response.captchaContent);
            }
        });
    });

    $('#checkMobile form').submit(function(e)
    {
        e.preventDefault();
        if(!checkUserMobile()) return false;

        var mobile   = $('#checkMobile #mobile').val();
        var captcha  = $('#checkMobile #captcha').val();
        $.post('/user-bindmobile', {mobile: mobile, captcha: captcha}, function(bindResponse)
        {
            if (bindResponse.result == 'success')
            {
                if(bindResponse.locate)
                {
                    if(checkDemoLogin(bindResponse.locate)) return;
                    window.location.href = bindResponse.locate;
                    return;
                }
                window.location.reload();
            }
            else
            {
                if (bindResponse.status == 'binded')
                {
                    $('.binded').parents('form').find('#captchaError').html(bindResponse.message);
                    $('.binded').removeClass('hide');
                    $('.submit-btn').parent('.form-group').addClass('hide');
                    $('.popover').remove();
                }
                else
                {
                    if (bindResponse.message.mobile)
                    {
                        $('#checkMobile #mobileError').html(bindResponse.message.mobile);
                        $('#checkMobile #mobileError').addClass('text-error');
                        return;
                    }
                    if (bindResponse.message.captcha)
                    {
                        $('#checkMobile #captchaError').html(bindResponse.message.captcha);
                        $('#checkMobile #captchaError').addClass('text-error');
                        return;
                    }
                }
            }
        });
    });

    $(document).on('click', '.returnToPrev', function()
    {
        $('#checkMobile #mobile').val('');
        $('#checkMobile #mobileError').removeClass('text-error').text('');
        $('#checkMobile #captcha').val('');
        $('#checkMobile #captchaError').removeClass('text-error').text('');
        $('#checkMobile #agreementError').removeClass('text-error').text('');
        $('#checkMobile').hide();
        $('#loginCommon').show().removeClass('hide');
        $('#wechatTab a').click()
    })
})

/** loginCommon block */
$(function ()
{
    $("#bindAccount form").submit(function(e)
    {
        e.preventDefault();
        $.post($("#bindAccount form").attr('action'), {account: $('#bindAccount #account').val(), password: $('#bindAccount #password').val(), referer: $('#accountTab #referer').val(), bindToAccount: 1}, function (data)
        {
            if(data.result == 'success')
            {
                if(checkDemoLogin(data.locate)) return;
                location.href = data.locate;
            }

            if(data.result == 'fail')
            {
                $('#bindAccount #formError').text('* ' + data.message);
                $('#bindAccount #formError').show();
            }
            return false;
        });
        return false;
    });

    $("#skipBindAccount").click(function(e)
    {
        bootbox.confirm(v.confirmSkipBindAccount, function(result)
        {
            if(!result) return;

            $.post($(e.target).attr('skipbindurl'), {skipBind : 1, fingerprint: getFingerprint()}, function (data)
            {
                if(data.result == 'success')
                {
                    if(checkDemoLogin(data.locate)) return;
                    location.href = data.locate;
                }

                if(data.reLogin == 1)
                {
                    $('#skipBindError').html(data.message).removeClass('hide');
                    setTimeout(function()
                    {
                        $('#bindAccount').addClass('hide').hide();
                        $('#loginCommon').removeClass('hide').show();
                        $('#skipBindError').html('').addClass('hide');
                    }, 2000);
                }
            });
        });
    });

    $("#accountTab form").submit(function(e)
    {
        e.preventDefault();
        $.post($("#accountTab form").attr('action'), {account: $('#accountTab #account').val(), password: $('#accountTab #password').val(), referer: $('#referer').val(), fingerprint: getFingerprint()}, function (data)
        {
            if(data.result == 'success')
            {
                if(checkDemoLogin(data.locate)) return;
                location.href = data.locate;
            }

            if(data.result == 'fail')
            {
                $('#formError').text('* ' + data.message);
                $('#formError').show();
            }
        });
    });

    $('#loginCommon').on('hidden.zui.modal', function()
    {
        clearTimeout(disableQrCodeTimer);
    });

    $('.reset-pass').click(() =>
    {
        if(window.location.pathname === '/user-login'){
            $('#retrieve').show();
            getCaptchaContent($('#retrieveCaptchaBox .image-box'));
            $('#retrieve #splitLine').show();
            $("#loginCommon").hide().addClass('hide');
            $("#bindAccount").hide();
            $('#emailOrMobile').val('');
            $('#login .title').hide();
            setSubmitEnable($('#retrieve .submit'), false);
            if(window.qrCodeTimer) clearInterval(window.qrCodeTimer);
        }
        else
        {
            window.open('/user-login#type=recover');
        }

        return false;
    });

    $('#mask, #expired').hover(function()
    {
        $("#expired img").attr('src', '/theme/default/default/images/main/qrcode_refresh_hover.png');
    },function()
    {
        $("#expired img").attr('src', '/theme/default/default/images/main/qrcode_refresh.png');
    });
});

/** mobileTab block */
$(function ()
{
    $('#mobileTab #account').keyup(function()
    {
        var loginAccount = $(this).val();
        if(isMobile(loginAccount))
        {
            $("#mobileTab #mobile").val(loginAccount);
            showMobileLogin();
        }
    });

    $('#mobileTab form').submit(function(e)
    {
        e.preventDefault();
        if(!checkMobileLogin()) return false;

        var isBindAccount = $("#mobileTab input[name='isBindAccount']").prop('checked') ? 1 : 0;
        var mobile        = $('#mobileTab #mobile').val();
        var captcha       = '';
        var token         = $('#token').val();
        var openID        = $('#openID').val();
        var referer       = $('#referer').val();

        $('.login-code .code-item').each(function()
        {
            captcha += $(this).val();
        });
        $.post("/user-mobileLogin.html",{mobile:mobile, captcha:captcha, token:token, openID:openID, referer:referer, isBindAccount:isBindAccount, fingerprint: getFingerprint()},function(response)
        {
            if(response.result == 'success')
            {
                if(response.isBindAccount)
                {
                    $('#loginCommon').hide().addClass('hide');
                    if(response.account) $("#bindAccount #account").val(response.account);
                    $('#bindAccount').show();
                    $('#bindTip').html(response.bindTip);
                    return;
                }

                if(response.locate)
                {
                    if(checkDemoLogin(response.locate)) return;
                    window.location.href = response.locate;
                    return;
                }

                window.location.reload();
            }
            else
            {
                if(response.message.mobile)
                {
                    $('#mobileTab #mobileError').html(response.message.mobile);
                    $('#mobileTab #mobileError').addClass('text-error');
                    return;
                }
                if(response.message.captcha)
                {
                    $('.login-code .text-error').html(response.message.captcha);
                    return;
                }
                $('.login-code .text-error').html(response.message);
            }
        });
        return false;
    });

    $('#mobileTab #mobile').bind('input propertychange', function()
    {
        if(isMobile($('#mobileTab #mobile').val())) $('#mobileTab #mobileError').removeClass('text-error').html('');
    });

    $('#mobileTab #captcha').bind('input propertychange', function()
    {
        if(/^\d{6}$/.test($('#mobileTab #captcha').val())) $('#captchaError').removeClass('text-error').html('');
    });

    $('.return-prev').click(function()
    {
        $('.login-code').addClass('hide')
        $('.rt-content').removeClass('hide');
        $('.login-code .code-tip').html(v.codeTip);
        $('#captchaBox #captchaContent').val('');
        $('#captchaError').html('');
        getCaptchaContent($('#captchaBox .image-box'));
    })
    function debounce(fn, delay = 500) {
        let timer = null;

        return function() {
            if (timer) {clearTimeout(timer)}
            timer = setTimeout(() =>
            {
                fn.apply(this, arguments);
                timer = null;
            }, delay);
        }
    }

    $('#agreementBox').click(function()
    {
        if(!!$('#agreementBox').is(':checked')) $('#agreementError').removeClass('text-error').html('');
    })

    $('#mobileTab .sendSMS a').click(debounce(function()
    {
        var mobile = $('#mobileTab #mobile').val();
        var token  = $('#token').val();
        var captchaContent = $('#captchaBox input').val();
        if(!isMobile(mobile))
        {
            $('#mobileTab #mobile').next('.errorTip').addClass('text-error').html(v.mobileWrongMessage);
            return;
        }
        if(!captchaContent)
        {
            $('#mobileTab #captchaError').html(v.captchaEmptyMessage);
            return;
        }

        $('#mobileTab #mobile').next('.errorTip').removeClass('text-error').html(' ');
        $.post("/sms-sendcode.html",{mobile:mobile, token:token, captchaContent: captchaContent},function(response)
        {
            if(response.result == 'success')
            {
                $('#mobileTab #captcha').parents('.form-group').find('.errorTip').removeClass('text-error').html('');
                var tel = mobile.substring(0, 3) + " **** " + mobile.substring(7);
                var codeTip = $('.login-code .code-tip').text();
                $('.login-code .code-tip').text(codeTip.replace('%s', tel));
                $('.login-code').removeClass('hide');
                $('.rt-content').addClass('hide');
                $('.login-code .code-item').val('');
                $('.login-code #code0').focus();
                $('.login-code .errorTip').html('');
                smscountdown = initcountdown;
                setSenderTime(loginSendSMS);
            }
            else
            {
                $('#mobileTab #captchaError').html(response.message);
                if(response.captchaContent) $('.captcha-box .image-box').html(response.captchaContent);
            }
        });
        return false;
    }));
    $('.captcha-box .image-box').click(function()
    {
        getCaptchaContent($(this));
    });

    $('.login-code .code-item').on('keydown', function(e)
    {
        e.preventDefault();
        var key = window.event ? e.keyCode : e.which;
        var keyMap = {
            48: '0',
            49: '1',
            50: '2',
            51: '3',
            52: '4',
            53: '5',
            54: '6',
            55: '7',
            56: '8',
            57: '9',
            96: '0',
            97: '1',
            98: '2',
            99: '3',
            100: '4',
            101: '5',
            102: '6',
            103: '7',
            104: '8',
            105: '9'
        }
        if((key > 47 && key < 58) || (key > 95 && key < 106))
        {
            $(this).val(keyMap[key]).addClass('no-cursor');
            if($(this).next().length > 0 && $(this).val() && !$(this).next().val()) $(this).next().focus();
        }

        if(key == 8)
        {
            if($(this).prev().length > 0 && !$(this).val()) $(this).prev().focus();
            $(this).val('').removeClass('no-cursor');
        }

        if(key == 39) $(this).next().focus();
        if(key == 37) $(this).prev().focus();
    });

    $('.login-code #submit').click(function()
    {

        $('#mobileTab form').trigger('submit');
    });

    $('.re-send').click(function(e)
    {
        e.stopPropagation();
        if($(this).hasClass('reciprocal')) return;
        $(this).next('.reSend-captcha-wrapper').toggleClass('hide');
        $('.empty-tip').html('');
        $('#captchaContent').val('');
        getCaptchaContent($('.reSend-captcha-wrapper .image-box'));
    });

    $('.reSend-captcha-wrapper').click(function(e){e.stopPropagation();});

    $('#loginModal').on('click', function()
    {
      $('.reSend-captcha-wrapper').addClass('hide');
    });

    $('.captcha-box .btn-sure').click(function()
    {
        var mobile         = $('#mobileTab #mobile').val();
        var token          = $('#token').val();
        var captchaContent = $('.reSend-captcha-wrapper input').val();
        $('.login-code .errorTip').html('');
        if(!captchaContent)
        {
            $('.login-code .empty-tip').html(v.captchaEmptyMessage);
            return;
        }
        $.post("/sms-sendcode.html",{mobile:mobile, token:token, captchaContent: captchaContent},function(response)
        {
            if(response.result == 'success')
            {
                $('.login-code .code-item').val('');
                $('.login-code #code0').focus();
                $('.reSend-captcha-wrapper').addClass('hide');
                smscountdown = initcountdown;
                setSenderTime(loginSendSMS);
            }
            else
            {
                $('.login-code .empty-tip').html(response.message);
                if(response.captchaContent) $('.reSend-captcha-wrapper .image-box').html(response.captchaContent);
            }
        });
    });
});

/** retrieve block */
$(function ()
{
    if(location.href.includes('type=recover'))
    {
        $('#loginCommon').addClass('hide');
        getCaptchaContent($('#retrieveCaptchaBox .image-box'));
        if(window.qrCodeTimer) clearInterval(window.qrCodeTimer);
    }

    $("#emailOrMobile").bind('input propertychange', function()
    {
        const inputVal = $('#emailOrMobile').val();
        setSubmitEnable($('#retrieve .submit'), isMobile(inputVal) || isEmail(inputVal));
    });

    $("#retrieve .submit").click(function(e)
    {
        const inputVal = $('#retrieve #emailOrMobile').val();
        var captcha = $('#retrieveCaptcha').val();
        if(!(inputVal && inputVal.length) || (!isEmail(inputVal) && !isMobile(inputVal))) return;

        $('#retrieve .errorTip').text('');
        verifyEmailOrMobileAndSendMsg(inputVal, captcha, function(data){
            $('#retrieve #retrieveCaptchaError').text('* ' + data.message);
            if(data.captchaContent) $('#retrieveCaptchaBox .image-box').html(data.captchaContent);
        })
    });

    $('#retrieve #back-login').click(function()
    {
        $('#retrieve').hide();
        $('#loginCommon').show().removeClass('hide');
        getQrCode();
    });

    $('#retrieveMobile .captcha-box .btn-sure').click(function()
    {
        var mobile         = $('#retrieveMobile #mobile').val();
        var token          = $('#token').val();
        var captchaContent = $('#retrieveMobile .reSend-captcha-wrapper input').val();
        if(!captchaContent)
        {
            $('#retrieveMobile .captcha-box .empty-tip').html(v.captchaEmptyMessage);
            return;
        }
        $.post("/sms-sendcode.html",{mobile:mobile, token:token, type: 'resetPassword', captchaContent: captchaContent},function(response)
        {
            if(response.result == 'success')
            {
                $('#retrieveMobile .reSend-captcha-wrapper').addClass('hide');
                $('#captcha').val('');
                mobileCountTime();
                $('#retrieveMobile .re-send').addClass('reciprocal');
                $('#retrieveMobile #captchaLabel').html('');
            }
            else
            {
                $('#retrieveMobile .captcha-box .empty-tip').html(response.message);
                if(response.captchaContent) $('#retrieveMobile .reSend-captcha-wrapper .image-box').html(response.captchaContent);
            }
        });
    });
});

/** retrieveEmail block */
$(function ()
{
    $('#retrieveEmail .submit').click(function()
    {
        var inputVal = $("#retrieveEmail #email").val();
        var captcha = $('#retrieveverifyCode').val();
        if(captcha !== '')
        {
            verifyEmailOrMobileAndSendMsg(inputVal, captcha, function(data) {
                $('#retrieveEmail #emailError').text(data.message);
                getCaptchaContent($('#retrieveEmailBox .image-box'));
            })
        }
        else
        {
            $('.verifycode').removeClass('hide');
            $('#retrieveEmailBox').removeClass('hide');
            getCaptchaContent($('#retrieveEmailBox .image-box'));
        }
    });
});

/** retrieveMobile block */
$(function ()
{
    $('#verifyCode').bind('input propertychange', function()
    {
        const codeVal = $('#verifyCode').val();
        setSubmitEnable($('#retrieveMobile .submit'), isVerifyCode(codeVal));
    });
    $('#retrieveMobile .submit').click(function(elem)
    {
        elem = $(elem);
        if(elem.hasClass('disable')) return;
        $.post('/sms-checkresetpasswordcode.html', {mobile: $("#retrieveMobile #mobile").val(), code: $('#retrieveMobile #verifyCode').val(), token: $('#token').val()}, function(response)
        {
            if(response.result == 'success')
            {
                $('#retrieveMobile').hide();
                $('#reset').show();
            }
            else
            {
                $('#retrieveMobile #verifyCode').val('');
                elem.addClass('disable');
                elem.attr('disable');
                $('#retrieveMobile #checkMobileError').text('* ' + response.message);
            }
        });
    });
});

/** reset block */
$(function ()
{
    $('#reset .submit').click(function()
    {
        var pwdVal = $('#passwordNew').val();
        var pwdConfirmVal = $('#passwordConfirm').val();
        $('#reset #error').text('');
        $('#reset #confirmError').text('');
        $('#passwordNew').removeClass('error-border');
        $('#passwordConfirm').removeClass('error-border');
        if(!(pwdVal && pwdVal.length))
        {
            $('#passwordNew').addClass('error-border');
            $('#reset #error').text('* ' + v.inputNewPasswordTip);
            return;
        }
        if(!/[a-zA-Z0-9]{6,}/.test(pwdVal))
        {
            $('#passwordNew').addClass('error-border');
            $('#reset #error').text('* ' + v.passwordFormatTip);
            return;
        }
        if(!(pwdConfirmVal && pwdConfirmVal.length))
        {
            $('#passwordConfirm').addClass('error-border');
            $('#reset #confirmError').text('* ' + v.confirmNewPasswordTip);
            return;
        }
        if(pwdVal.length !== pwdConfirmVal.length)
        {
            $('#passwordConfirm').addClass('error-border');
            $('#reset #confirmError').text('* ' + v.passwordNotSame);
            return;
        }
        $.post('/user-resetpasswordbysms.html', {password1: pwdVal, password2: pwdConfirmVal, token: $('#token').val()}, function(response)
        {
            if(response.result == 'success')
            {
                $('#resetSuccess').show();
                $('#reset').hide();
            }
            else
            {
                $('#retrieveMobile #verifyCode').val('');
                if(typeof response.message === 'string') $('#reset #confirmError').text('* ' + response.message);
                if(typeof response.message === 'object')
                {
                    for(const key in response.message) $('#reset #confirmError').text('* ' + response.message[key]);
                }
            }
        });
    });
});

/** resetSuccess block */
$(function ()
{
    $('#resetSuccess .submit').click(() =>
    {
        $('#loginCommon').show().removeClass('hide');
        $('#resetSuccess').hide();
    });
});

function showEmailRetrieve(inputVal)
{
    $("#retrieveEmail #email").val(inputVal);
    $('#retrieve').hide();
    $("#retrieveEmail").show();
    $("#retrieveMobile").hide();
}
function showMobileRetrieve(inputVal)
{
    $("#retrieveMobile #mobile").val(inputVal);
    $('#retrieve').hide();
    $("#retrieveMobile").show();
    $("#retrieveEmail").hide();
}

function verifyEmailOrMobileAndSendMsg(inputVal, captcha, callback)
{
    var token  = $('#token').val();
    $.post('/user-resetpassword.html', {account: inputVal, captchaContent: captcha, token: token}, function (data)
    {
        if(data.result === 'success')
        {
            if(isEmail(inputVal))
            {
                showEmailRetrieve(inputVal);
                emailCountTime();
                callback(data);
                return;
            }

            if(isMobile(inputVal))
            {
                showMobileRetrieve(inputVal);
                mobileCountTime();
            }
        }
        else
        {
            callback(data);
        }
    });
}

function emailCountTime()
{
    if($('#retrieveEmail .submit').hasClass('disable')) return;
    setSubmitEnable($('#retrieveEmail .submit'), false);
    countTime('Email', function()
    {
        setSubmitEnable($('#retrieveEmail .submit'), true);
    });
}

function mobileCountTime()
{
    if($("#retrieveMobile .send-again").hasClass('reciprocal')) return;
    $("#retrieveMobile .send-again").addClass('send-again-disable reciprocal');
    countTime('Mobile', function()
    {
        $("#retrieveMobile .send-again").addClass('send-again-enable');
        $("#retrieveMobile .send-again").removeClass('send-again-disable reciprocal');
    });
}

function countTime(id, callback)
{
    retrievecountdown = initcountdown;
    $('#retrieve' + id + ' .send-again .time').text('(' + retrievecountdown + 's)');
    if(countTimer) clearInterval(countTimer);
    countTimer = setInterval(function()
    {
        retrievecountdown -= 1;
        if(retrievecountdown <= 0)
        {
            if(countTimer) clearInterval(countTimer);
            $('#retrieve' + id + ' .send-again .time').text('');
            callback && callback();
            return;
        }
        $('#retrieve' + id + ' .send-again .time').text('(' + retrievecountdown + 's)');
    }, 1000);
};

function setSubmitEnable($elem, stus)
{
    if(stus)
    {
        $elem.removeClass('disable');
        $elem.removeAttr('disable');
    }
    else
    {
        $elem.addClass('disable');
        $elem.attr('disable', '');
    }
}

function showWechat()
{
    $('#loginCommon').removeClass('fade');
    $('#loginCommon').show().removeClass('hide');

}

function showMobileLogin()
{
    $('#loginCommon').hide().addClass('hide');

}

function disableQrCode()
{
    $('#loginCommon #expired').show();
    $('#loginCommon #mask').show();
    if(window.qrCodeTimer) clearInterval(window.qrCodeTimer);
}


async function getQrCode()
{
    try
    {
        $.ajax(
        {
            url: "/wechat-getLoginQrCode", success: function(response)
            {
                if (response.result === "success") {
                    $('#loginCommon #expired').hide();
                    $('#loginCommon #qrcode').css('background-image', 'url(' + response.url + ')');
                    $('#loginCommon #mask').hide();
                    clearTimeout(disableQrCodeTimer);
                    if (window.qrCodeTimer) clearInterval(window.qrCodeTimer);

                    disableQrCodeTimer = setTimeout(disableQrCode, 50000);

                    window.qrCodeTimer = setInterval(function()
                    {
                        $.get("/wechat-ajaxgetscanstatus", {'ticket': response.ticket, fingerprint: getFingerprint()}, function(response)
                        {
                            if(response.result == 'success')
                            {
                                if(window.qrCodeTimer) clearInterval(window.qrCodeTimer);
                                if(response.status == 'error')
                                {
                                    if(response.message) bootbox.alert(response.message);
                                    disableQrCode();
                                    clearTimeout(disableQrCodeTimer);
                                }
                                if(response.status == 'check')
                                {
                                    $('#checkMobile').show();
                                    getCaptchaContent($('#checkMobile #captchaBox .image-box'));
                                    $('#loginCommon').hide().addClass('hide');
                                    $('#wechatTab').removeClass('active');
                                    $('.openID').val(response.openID);
                                    return;
                                }
                                if(response.status == 'userinfo')
                                {
                                    $('.register-success-form').show();
                                    return;
                                }
                                if(response.locate != '')
                                {
                                    setTimeout(function()
                                    {
                                        if(checkDemoLogin(response.locate)) return;
                                        location.href = response.locate;
                                    }, 500);
                                }
                            }
                            else
                            {
                                $('.register-success-form').hide();
                            }
                        });
                    }, 3000);
                }
                else
                {
                    $('#scanTip').html(data.message);
                }
            }
        });
    }
    catch(error)
    {
        $('#scanTip').html('二维码加载失败，请重试');
    }
}

function isMobile(mobile)
{
    return /^1[3456789]\d{9}$/.test(mobile);
}

function isVerifyCode(code)
{
    return /^\d{6}$/.test(code);
}

function setSenderTime(sendSMS)
{
    $('.login-code .re-send').html(smscountdown + 's').addClass('reciprocal');
    var senderTimer = setInterval(function()
    {
        smscountdown -= 1;
        if(smscountdown > 0)
        {
            $('.login-code .re-send').html(smscountdown + 's');
        }
        else
        {
            clearInterval(sendSMS.senderTimer);
            $('.login-code .re-send').html(v.reSend);
            $('.login-code .re-send').removeClass('reciprocal');
            smscountdown = initcountdown;
        }
    }, 1000);
    loginSendSMS.senderTimer = senderTimer;
}

function isEmail(email)
{
    return /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(email);
}

function setSmsSenderTime(sendSMS)
{
    var senderTimer = setInterval(function()
    {
        smscountdown -= 1;
        if(smscountdown > 0)
        {
            $('#mobileTab .sendSMS a').html(smscountdown + 's').attr("disabled", true);
            $('#mobileTab .sendSMS a').addClass('reciprocal');
        }
        else
        {
            clearInterval(sendSMS.senderTimer);
            $('#mobileTab .sendSMS a').html(v.sendMobileSMS).attr("disabled", false);
            $('#mobileTab .sendSMS a').removeClass('reciprocal');
            smscountdown = initcountdown;
        }
    }, 1000);
    loginSendSMS.senderTimer = senderTimer;
}

function checkMobileLogin()
{
    var mobile = $('#mobileTab #mobile').val();
    var code   = $('#mobileTab #captcha').val();
    var result = true;

    if(!isMobile(mobile))
    {
        $('#mobileTab #mobile').next('.errorTip').addClass('text-error').html(v.mobileWrongMessage);
        result = false;
    }
    else
    {
        $('#mobileTab #mobile').next('.errorTip').removeClass('text-error').html(' ');
    }

    return result;
}

function checkUserMobile()
{
    var mobile = $('#checkMobile #mobile').val();
    var code   = $('#checkMobile #captcha').val();
    var agree  = $('#checkMobile input[name="agreement"]:checked').length > 0;
    var result = true;

    if(!isMobile(mobile))
    {
        $('#checkMobile #mobile').next('.errorTip').addClass('text-error').html(v.mobileWrongMessage);
        result = false;
    }
    else
    {
        $('#checkMobile #mobile').next('.errorTip').removeClass('text-error').html(' ');
    }

    if(!/^\d{6}$/.test(code))
    {
        result = false;
        $('#checkMobile #captcha').parents('.form-group').find('.errorTip').addClass('text-error').html(v.codeWrongMessage);
    }
    else
    {
        $('#checkMobile #captcha').parents('.form-group').find('.errorTip').removeClass('text-error').html('');
    }

    if(!agree)
    {
        result = false;
        $('#checkMobile #agreementError').addClass('text-error').html(v.mobileLoginAgreement);
    }
    return result;
}

$('.btn-new-mobile').click(function()
{
    $('.errorTip').html('');
    $('#mobile, #captcha').val('');
    $(this).parents('form').find('#captchaError').html('');
    $('.submit-btn').parent('.form-group').removeClass('hide');
    $('.binded').addClass('hide');
});

$('.btn-login-current').click(function()
{
    var url = '/user-bindmobile-' + $(this).parents('form').find('#mobile').val() + '.html';
    $.post(url, {referer: v.referer}, function(response)
    {
        if(response.result == 'success' && response.locate)
        {
            if(checkDemoLogin(response.locate)) return;
            location.href = response.locate;
        }
        if(response.result == 'fail')
        {
            $('.errorTip').html('');
            $('#checkMobile').find('#mobileError').html(response.message);
        }
    });
});

$('#agreementBox').change(function(e)
{
    if(!$(e.target).prop('checked')) $('#checkMobile #submit, .binded .btn').prop('disabled', 'disabled');
    if($(e.target).prop('checked')) $('#checkMobile #submit, .binded .btn').prop('disabled', false);
});

function getCaptchaContent($ele)
{
    $.get(createLink('guarder', 'getCaptcha'), function(response)
    {
        if(response.result == 'success') $ele.html(response.captchaContent);
    });
}
window.xuanxuan = {
    // beta 版本相关信息
    betadate: "04月24日",
    betaver: "7.2.beta",
    betadownload: "/dynamic/xuanxuan7.2.beta-104.html",

    // 设置喧喧当前版本
    version: "10.1",

    // 设置喧喧更新日期
    publishDate: "2025.04.25",

    // 首页幻灯片发布日期
    date: "7月11日",

    // 以下只能填写版本号，不可以加英文字母
    ver: "10.2",

    xxcVersion: "10.2",

    xxbVersion: "10.2",

    xxdVersion: "10.2",

    androidVersion: "10.2.0",
    
    version:"10.2.0",

    iosVersion: "10.2.0",

    owtVersion: "1.5",

    // 所有下载按钮指向的位置
    download: "/dynamic/xuanxuan9.1-111.html",

    // 设置喧喧下载地址前缀
    downloadUrl: "/dl/xuanxuan/{ver}/",
    androidDownloadUrl: "/dl/xuanxuan/{ver}/",
    owtDownloadUrl: "/dl/xuanxuan/owt/",
    jitsiDownloadUrl: "https://dl.zentao.net/xuanmeet/xuanmeet-1.0.zip",
    downloadDockerBaidu: "https://pan.baidu.com/s/1Pvz5Yz4fsvS8-VNzKLqPSQ",
    owt_docker_baidu_code: "cgna",

    // 以下内容无需更改
    downloads: {
        windows_setup: "xuanxuan.{xxcVersion}.win64.setup.exe",
        windows_setup_debug: "xuanxuan.{xxcVersion}.debug.win64.setup.exe",
        windows_setup_win32: "xuanxuan.{xxcVersion}.win32.setup.exe",
        windows_7z: "xuanxuan.{xxcVersion}.win64.7z.exe",
        windows_7z_win32: "xuanxuan.{xxcVersion}.win32.7z.exe",
        windows_zip: "xuanxuan.{xxcVersion}.win64.zip",
        windows_zip_win32: "xuanxuan.{xxcVersion}.win32.zip",
        mac_dmg: "xuanxuan.{xxcVersion}.mac.dmg",
        mac_zip: "xuanxuan.{xxcVersion}.mac.zip",
        mac_dmg_debug: "xuanxuan.{xxcVersion}.debug.mac.dmg",
        browser: "xuanxuan.{xxcVersion}.browser.zip",
        linux_deb: "xuanxuan.{xxcVersion}.linux.amd64.deb",
        linux_deb_32: "xuanxuan.{xxcVersion}.linux.i386.deb",
        linux_zip: "xuanxuan.{xxcVersion}.linux64.zip",
        linux_targz: "xuanxuan.{xxcVersion}.linux.x64.tar.gz",
        linux_targz_32: "xuanxuan.{xxcVersion}.linux.ia32.tar.gz",
        linux_rpm: "xuanxuan.{xxcVersion}.linux.x86_64.rpm",
        linux_rpm_32: "xuanxuan.{xxcVersion}.linux.i686.rpm",
        ranzhi_server: "xuanxuan.ranzhi.{xxbVersion}.zip",
        zentao_server: "xuanxuan.zentao.{xxbVersion}.zip",
        source: "xuanxuan.source.{ver}.zip",
        xxd_win32: "xxd.{xxdVersion}.win32.zip",
        xxd_win64: "xxd.{xxdVersion}.win.x64.zip",
        xxd_mac: "xxd.{xxdVersion}.mac.tar.gz",
        xxd_linux32: "xxd.{xxdVersion}.linux.ia32.tar.gz",
        xxd_linux64: "xxd.{xxdVersion}.linux.x64.tar.gz",
        xxb_source: "xxb.{xxbVersion}.zip",
        xxb_source_php53: "xxb.{xxbVersion}.php53.zip",
        xxb_source_php70: "xxb.{xxbVersion}.php70.zip",
        xxb_source_php71: "xxb.{xxbVersion}.php71.zip",
        xxb_source_php72: "xxb.{xxbVersion}.php72.zip",
        xxb_win64_zbox: "xuan.{xxbVersion}.zbox.win.x64.exe",
        xxb_win64: "xxb.{xxbVersion}.win64.exe",
        xxb_win32: "xxb.{xxbVersion}.win32.exe",
        xxb_zbox64: "xuan.{xxbVersion}.zbox.linux.x64.tar.gz",
        xxb_zbox32: "xxb.{xxbVersion}.zbox_32.tar.gz",
        xxb_linux_rpm: "xxb-{xxbVersion}-1.noarch.rpm",
        xxb_linux_deb: "xxb_{xxbVersion}_1_all.deb",
        android: "xuanxuan.android.{androidVersion}.apk",
        owt_docker: "owt.{owtVersion}.docker.tar.xz",
        owt_docker_baidu: "{downloadDockerBaidu}",
        jisti_docker: "{jitsiDownloadUrl}",
        windows_bundle: "xxb.{xxbVersion}.bundle.win64.zip",
        linux_bundle: "xxb.{xxbVersion}.bundle.zbox_64.tar.gz",
    }
};
xuanxuan.downloadUrlOrigin = xuanxuan.downloadUrl;
xuanxuan.downloadUrl = xuanxuan.downloadUrl.format(xuanxuan);
xuanxuan.androidDownloadUrl = xuanxuan.androidDownloadUrl.format(xuanxuan);

var timeNow = new Date().getTime();
for(var downloadType in xuanxuan.downloads) {
    var url = xuanxuan.downloads[downloadType];
    var preUrl = url.indexOf('{xxcVersion}') > -1 ? xuanxuan.downloadUrl.format({version: xuanxuan.xxcVersion}) :
        (url.indexOf('{xxbVersion}') > -1 ? xuanxuan.downloadUrl.format({version: xuanxuan.xxbVersion}) :
        (url.indexOf('{xxdVersion}') > -1 ? xuanxuan.downloadUrl.format({version: xuanxuan.xxdVersion}) :
        (url.indexOf('{androidVersion}') > -1 ? xuanxuan.androidDownloadUrl.format({version: xuanxuan.androidVersion}) : (url.indexOf('{owtVersion}') > -1 ? xuanxuan.owtDownloadUrl : xuanxuan.downloadUrl))));
    xuanxuan.downloads[downloadType] = url.format(xuanxuan);
    var thisDownloadUrl = xuanxuan.downloads[downloadType];
    if (thisDownloadUrl.indexOf('https://') !== 0 && thisDownloadUrl.indexOf('http://')) {
        thisDownloadUrl = preUrl + thisDownloadUrl;
    }
    xuanxuan['download.' + downloadType] = thisDownloadUrl;
    xuanxuan['filename.' + downloadType] = xuanxuan.downloads[downloadType];
};

$(function() {
    $('[data-xuanxuan]').each(function() {
        var $this = $(this);
        var data = $this.data('xuanxuan');
        $.each(data.split(' '), function(idx, dataItem) {
            dataItem = dataItem.split('|');
            var attr = dataItem[0] || 'text';
            var key = dataItem[1];
            var value = xuanxuan[key];
            if(!key || !value) {
                var oldValue = attr === 'text' ? $this.text() : $this.attr(attr);
                if(oldValue) value = oldValue.format(xuanxuan);
            }
            if(attr === 'text') {
                $this.text(value);
            } else {
                $this.attr(attr, value);
            }
        });
    });
    $('.text-xuanxuan').each(function()
    {
        var $this = $(this);
        var format = $this.text();
        $this.text(format.format(xuanxuan));
    });
    $('.link-xuanxuan').each(function()
    {
        var $this = $(this);
        var attrName = $this.is('img') ? 'src' : 'href';
        var format = $this.data(attrName) || $this.attr(attrName);
        if(format.indexOf('/#') === 0) format = format.substr(2);
        else if(format.indexOf('#') === 0) format = format.substr(1);
        $this.attr(attrName, format.format(xuanxuan));
    });
});

if(screen.width > 767){
    $('#words').attr('placeholder','搜一搜');
    $("#searchbar").insertAfter("#navbarWrapper");
    $("#siteNav").insertAfter("#searchbar");
} else {
    $("#siteNav").insertAfter("#siteTitle");
};

$(document).ready(function(){
    if(typeof headerList != 'undefined') return ;
    headerList = true;
    $('#footer #icpInfo').after('<a class="privacy" href="/page/xuan-privacypolicy.html">隐私政策</a>');
    $('.m-user-register .form-horizontal .agreement-form span').after('<span>和《<a href="/page/xuan-privacypolicy.html" target="_blank">隐私政策</a>》</span>');
});

$(document).on('click', '.icon_img_bg', function(){open_floatWindow();});


// 首页点击空白处登录弹框隐藏
$(document).click(function(e) {
    if($(this).children('html').hasClass('m-user-login')) {
        return;
    } else {
        $('#loginModal').hide();
        if(window.qrCodeTimer) clearInterval(window.qrCodeTimer);
        $('#whitePaper').remove();
    }
})
$(document).on('click', '#loginModal, #privacyagreement, #agreement', function(e) {
    e.stopPropagation();
})
function showModalLogin(id, elem,  moreTop, moreLeft, showHeader, style, callback)
{
    var isVisible = document.getElementById(id) && document.getElementById(id).offsetParent;
    if(isVisible) return false;
    if(!style) {
        style = {}
    }

    var modalLoginOptions =
    {
        url     : "/user-loginmodal.html",
        name    : id,
        keyboard: false,
        backdrop: 'static',
        loaded  : function() {
            $('#' + id).addClass('modalLogin');
            if(showHeader == 0) $('#' + id + ' .close').hide();
            if($('html').hasClass('m-user-login')) $('#loginModal').css('height', $('.page-wrapper').height() + 100);
            callback && callback();
        },
        onHide: function(){
            if(window.smsTimer) clearInterval(window.smsTimer);
            if(window.qrCodeTimer) clearInterval(window.qrCodeTimer);
        }
    };
    var myModalTrigger = new $.zui.ModalTrigger(modalLoginOptions);
    myModalTrigger.show();
}
$('.demo-link').click(function(e)
{
    e.preventDefault();
    if (location.pathname == createLink('user', 'login', 'referer=pcDemo') || location.pathname == createLink('user', 'login', 'referer=mobileDemo')) {
        return;
    }
    var demoLink = $(this).attr('href');
    getUserFingerprint().then(visitorID => {
        if (demoLink == v.demoPcUrl) 
        {
          var postFunc = 'pc';
        }
        if (demoLink == v.demoMobileUrl) 
        {
          var postFunc = 'mobile';
        }
        var postLink = `/demo-${postFunc}`;
        $.post(postLink, 
        {
            url: demoLink,
            fingerprint: visitorID,
            referrer: location.href
        }, function(response) 
        {
            if(response.result == 'success')
            {
                if(response.data.open) 
                {
                    sessionStorage.setItem('demoOpen', response.data.open);
                } 
                else 
                {
                    sessionStorage.removeItem('demoOpen');
                }

                if(response.data.locate)
                {
                    sessionStorage.setItem('demoLocate', response.data.locate);
                    $.cookie('noDemoLogin', 0, {path: config.cookiePath});
                }

               if (response.data.target === '_blank') {
                    // 1. 获取原始URL和时间戳
                    const originalUrl = response.data.url;
                    const timestamp = new Date().getTime();
                
                    // 2. 分离URL的hash部分（#及后面的内容）
                    let urlWithoutHash = originalUrl;
                    let hashPart = '';
                    const hashIndex = originalUrl.indexOf('#');
                    if (hashIndex !== -1) {
                        urlWithoutHash = originalUrl.slice(0, hashIndex); // 截取#前面的URL
                        hashPart = originalUrl.slice(hashIndex); // 截取#及后面的hash
                    }
                
                    // 3. 处理URL参数（删除原有v，添加新v）
                    // 兼容相对路径：如果URL是相对路径，拼接当前页面origin
                    const baseUrl = window.location.origin;
                    const urlObj = new URL(urlWithoutHash, baseUrl);
                    urlObj.searchParams.delete('v'); // 移除原有v参数
                    urlObj.searchParams.append('v', timestamp); // 添加新的时间戳v参数
                
                    // 4. 拼接回完整URL（处理后的参数 + 原始hash）
                    const newUrl = urlObj.toString() + hashPart;
                
                    // 5. 打开新窗口
                    window.open(newUrl, '_blank', 'noopener');
                }
                else 
                {
                    window.location.href = response.data.url;
                }
            }
        }, 'json')
    });
});

$('.faq-block .question').click(function()
{
    $(this).siblings('.answer').toggleClass('hide');
    $(this).find('i').toggleClass('rotate');
});

function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    }
}

$('#searchbar').click(function(e)
{
    e.stopPropagation();
});

$(document).click(function()
{
    $('#searchbar form').removeClass('active');
    $('#searchbar .search-btn').removeClass('show-form');
});

$('#searchbar .search-btn').click(function(e)
{
    e.stopPropagation();
   $(this).siblings().addClass('active'); 
   $(this).addClass('show-form');
});
