
var windowWidth = $(window).width();
var windowHeight = $(window).height();
var accountVerifyCode = false
var valCodeInput = $("#val-code-input");
var valCodeItems = $("div[name='val-item']");
var regex = /^[\d]+$/;
var valCodeLength = 0;
var accountWarringTimeout = '';
var accountCurrectTimeout = '';
var nowlayerType = 'email';
var allli = $('.dggbMenu li');
var newemail = '';
var layerIndex = ''
$(document).ready(function () {
    valCodeInput = $("#val-code-input")
    valCodeItems = $("div[name='val-item']")
    allli = $('.dggbMenu li');
    $.each(allli, function (index, value) {
        // now dom    in same function click
        $(this).mouseover(function () {
            $(this).find('.dggbSubMenuBg').show();
            $(this).find('.dggbMenuTitle .menuline').hide();
        });
        $(this).mouseleave(function () {
            $(this).find('.dggbSubMenuBg').hide();
            $(this).find('.dggbMenuTitle .menuline').show();
        });
        let widths = $(this).find(".dggbMenuTitle").width();
    });
    $('.dggbSubMenuBg span a').on('mouseover',function(){
        $(this).addClass('chooses');
    })
    $('.dggbSubMenuBg span a').on('mouseleave',function(){
        $(this).removeClass('chooses');
    })


    $(".schtab").on('click',function(){
        $(".schtab").removeClass('check');
        $(this).addClass('check');
        let types = $(this).data('type');
        $('.schDown .scdownUl').hide();
        $('.schDown .'+types+'Ul').show();
        $('.schtitles').hide();
        $('.'+types+'Title').show();
    })
    if($('.headnoindexRight').length > 0){
        $('.headnoindexRight').addClass('headnoindexRightmouse');
        $('.headnoindexRight').removeClass('headnoindexRightmouse');
    }
   
    if (windowWidth > 750) {
      
        if($('.searchinputopbk .text1').val() === '' || $('.searchinputopbk .text1').val() === undefined){
            $('.searchinputopbk  .closesearch').hide();
        }else{
            $('.searchinputopbk  .closesearch').show();
        }
        $(document).on('click', function (e) {
            var $searchinputop = $('.searchinputop');
            var $closesearch = $('.closesearch');
            // search content div
            var $searchCons = $('#searchCons');
            var $headnoindexRight = $('.headnoindexRight');   // no-index-search   Search box outermost layer
            var $noindexSearchipad = $('.noindexSearchipad'); // no-index-search Non-homepage search iPad top search button
            var $topicsech = $('.topicsech'); //“Community search outermost layer”
            var $noindexsearchinput = $('.noindexsearchinput');
            var $headnoindexRight = $('.headnoindexRight');
            var $sercontopUlli = $('.sercontopUl li');
            if ($headnoindexRight.length <= 0) {  // has search 
                if (!$searchinputop.is(e.target) && $searchinputop.has(e.target).length === 0) {
                    if (!$searchCons.is(e.target) && $searchCons.has(e.target).length === 0) {
                        if ($('.searchinputop .text1').length > 0) {
                            if ($('.searchinputop .text1').val() != '') {
                                $('.searchLine').hide();
                                $('.searchCons').css('max-height','0');
                                $('.searchinputop .text1').val('');
                            } else {
                                $('.closesearch').hide();
                                $('.dggbDengSerTitle').removeClass('dggbDengSerTitlemouse');
                                $('.searchLine').hide();
                                $('.searchCons').css('max-height','0');
                                if($('.dggbDengSerTitle').find('.topicsech')){
                                    $topicsech.find('form').removeClass('dggbDengSerTitlemouse');
                                    $('.topicsech').removeClass('topicsechclick');
                                }
                            }
                        }
                    } else { }
                } else {
                    // index  click serch must goin this
                    $('.closesearch').show();
                    $('.searchLine').show();
                     $('.searchCons').css('max-height','560px');
                    $('.serconTitle img').show();
                    $('.searchinputop').css('z-index', '10');
                    $('.serconTitleRight').hide();
                    if ($('.searchinputop .text1').val() === '') {
                        // “Distinguish between the community PC search box and the search box on other pages. The top search on non-homepage pages does not go here.”
                        if($searchinputop.parent().hasClass('topicsech')){
                            $searchinputop.parent().addClass('topicsechclick');
                            $topicsech.addClass('topicsechclick');
                        }else{
                            $searchinputop.parent().addClass('dggbDengSerTitlemouse');
                        }
                    } else {
                        $('.searchinputop').css('z-index', '1003');
                    }
                    if (!$closesearch.is(e.target) && $closesearch.has(e.target).length === 0) {
                    } else {
                        if ($('.searchinputop .text1').val() == '') {
                            $('.closesearch').hide();
                            $('.searchLine').hide();
                             $('.searchCons').css('max-height','0');
                            $('.dggbDengSerTitle.dggbDengSerTitlemouse').removeClass('dggbDengSerTitlemouse');
                            if($('.dggbDengSerTitle').find('.topicsech')){
                                $topicsech.find('form').removeClass('dggbDengSerTitlemouse');
                                $('.topicsech').removeClass('topicsechclick');
                            }
                            $('.topicsech .closesearch').hide();
                        } else {
                            $('.searchinputop .text1').val('');
                        }
                    }
                }
            }else if($headnoindexRight.length > 0){
                if (!$headnoindexRight.is(e.target) && $headnoindexRight.has(e.target).length === 0) {
                    if (!$searchCons.is(e.target) && $searchCons.has(e.target).length === 0) {
                        if ($('.searchinputop .text1').length > 0) {
                            if ($('.searchinputop .text1').val().length == 0) {
                                $('.headnoindexRightmouse .closesearch').hide();
                                $('.headnoindexRight .searchLine').hide();
                                $('.headnoindexRight .searchCons').css('max-height','0');
                                $('.headnoindexRight').removeClass('headnoindexRightmouse');
                                $('.coinbkBody .headnoindexRight').removeClass('dggbDengSerTitlemouse');
                                $('.searchinputop .text1').val('');
                                $('.headnoindexRight').css('width', '262px');
                                $('.headnoindexRight').css('margin', '0 26px 0 0');
                            } else {
                                $('.headnoindexRight .searchLine').hide();
                                $('.headnoindexRight .searchCons').css('max-height','0');
                            }
                        }
                    } else {
                    }
                } else {
                    // click headnoindexRight   noindex search must goin this
                    $('.serconTitle img').show();
                    $('.noindexsearchinput').css('z-index', '10');
                    if ($('.noindexsearchinput').val() == '') {
                        // input no val
                        $('.headnoindexRight').addClass('headnoindexRightmouse');
                        $('.headnoindexRight .searchLine').show();
                        $('.headnoindexRight .searchCons').css('max-height','560px');
                        $('.headnoindexRight').css('width', '750px');
                        $('.headnoindexRight').css('margin', '0 26px 0 0');
                        $('.headnoindexRight .closesearch').show();
                        if (!$closesearch.is(e.target) && $closesearch.has(e.target).length === 0) {
                        } else {
                            $('.closesearch').hide();
                            $('.headnoindexRight .searchLine').hide();
                            $('.headnoindexRight .searchCons').css('max-height','0');
                            $('.headnoindexRight').removeClass('headnoindexRightmouse');
                            $('.coinbkBody .headnoindexRight').removeClass('dggbDengSerTitlemouse');
                            $('.headnoindexRight').css('width', '262px');
                            $('.headnoindexRight').css('margin', '0 26px 0 0');
                        }
                    } else {
                        // notindex search click closesearch   close and clear all
                        $('.noindexsearchinput').css('z-index', '1003');
                        if (!$closesearch.is(e.target) && $closesearch.has(e.target).length === 0) {
                            $('.headnoindexRight').addClass('headnoindexRightmouse');
                            $('.headnoindexRight .searchLine').show();
                            $('.headnoindexRight .searchCons').css('max-height','560px');
                            $('.headnoindexRight').css('width', '750px');
                            $('.headnoindexRight').css('margin', '0 26px 0 0');
                            $('.headnoindexRight .closesearch').show();
                        } else {
                            if($('.headnoindexRightmouse').length >0){
                                if ($('.headnoindexRight .text1').val() == '') {
                                    $('.headnoindexRightmouse .closesearch').hide();
                                    $('.headnoindexRight .searchLine').hide();
                                    $('.headnoindexRight .searchCons').css('max-height','0');
                                    $('.headnoindexRight').removeClass('headnoindexRightmouse');
                                    $('.coinbkBody .headnoindexRight').removeClass('dggbDengSerTitlemouse');
                                    $('.headnoindexRight').css('width', '262px');
                                    $('.headnoindexRight').css('margin', '0 26px 0 0');
                                } else {
                                    $('.headnoindexRightmouse .closesearch').show();
                                    $('.noindexsearchinput').val('');
                                }  
                              
                            }else{
          
                            }
                            
                        }
                    }
                 
                }
            }

        });
        $('.searchCons').on('click', function (e) {
            e.stopPropagation(); //  “Prevent click event propagation to the document”
        });
         // not index  header-search
         if (windowWidth <= 1024) {
            $('.noindexSearchipad').click(function () {
                $('.getMenuSearchipad').show();
                $('.searchinputop input').blur();
                $('.getMenuSearch .getMenuschTop .text1').focus();
            })

            $('.getMenuSearchipad .schtopleft b').click(function () {
                if($('.getMenuSearchipad .getMenuschTop .text1').val() == '' || $('.getMenuSearchipad .getMenuschTop .text1').val() == undefined){
                    $('.getMenuSearchipad').hide();
                }else{
                    $('.getMenuSearchipad .getMenuschTop .text1').val('');
                }
            })
            $('.getMenuSearch .getMenuschTop .text1').on('input', function () {
                if (!$(this).val()) { // 检查输入框是否为空
                    $('.searchdownCons .serconTitleRight').hide();
                    $('.getMenuschTop input.text1').css('color', '#A6B0C3');
                    if(!$(this).parent().parent().parent().parent().hasClass('getMenuSearchipad')){
                        $(this).parent().parent().addClass('dggbDengSerTitlemouse');
                    }
                } else {
                    $('.searchdownCons .serconTitleRight').show();
                    $('.getMenuschTop input.text1').css('color', '#000000');
    
                    $(this).parent().parent().removeClass('dggbDengSerTitlemouse');
                }
    
            });
        }
    } else {
        $(document).on('click', function (e) {
            var $noindexSearch = $('.noindexSearch');
            var $noindexSearchimg = $('.noindexSearch img');
            // click noindexSearch
            if($noindexSearch.is(e.target) || $noindexSearchimg.is(e.target)){
                $('.getMenuSearch').show();
                $('.searchinputop input').blur();
                $('.getMenuSearch .getMenuschTop .text1').focus();
            }
            if($('.getMenuSearchipad .schtopleft b').is(e.target)){
                if($('.getMenuSearchipad .getMenuschTop .text1').val() == '' || $('.getMenuSearchipad .getMenuschTop .text1').val() == undefined){
                    $('.getMenuSearchipad').hide();
                }else{
                    $('.getMenuSearchipad .getMenuschTop .text1').val('');
                }
            }
        })
        $('.searchinputop').on('click',function () {
            $('.getMenuSearch').show();
            $('.searchinputop input').blur();
            $('.getMenuSearch .getMenuschTop .text1').focus();
        })
        $('.searchinputopbk').on('click',function () {
            $('.getMenuSearch').show();
            $('.searchinputopbk input').blur();
            $('.getMenuSearch .getMenuschTop .text1').focus();
        })

        $('.schtopleft b').click(function () {
            if($('.getMenuSearch .getMenuschTop .text1').val().length == 0){
                $('.getMenuSearch').hide();
            }else{
                $('.getMenuSearch .getMenuschTop .text1').val('');
            }
        })

        $('.getMenuSearch .getMenuschTop .text1').on('input', function () {
            if (!$(this).val()) { // 检查输入框是否为空
                $('.searchdownCons .serconTitleRight').hide();
                $('.getMenuschTop input.text1').css('color', '#A6B0C3');
                if(!$(this).parent().parent().parent().parent().hasClass('getMenuSearchipad')){
                    $(this).parent().parent().addClass('dggbDengSerTitlemouse');
                }
            } else {
                $('.searchdownCons .serconTitleRight').show();
                $('.getMenuschTop input.text1').css('color', '#000000');

                $(this).parent().parent().removeClass('dggbDengSerTitlemouse');
            }

        });
        $('.schtopright').click(function () {
            $('.searchdownCons .serconTitleRight').hide();
            $('.getMenuschTop input.text1').css('color', '#A6B0C3');
            $('.getMenuschTop input.text1').val('');
            if(!$(this).parent().parent().parent().parent().hasClass('getMenuSearchipad')){
                $(this).parent().parent().addClass('dggbDengSerTitlemouse');
            }
        })
        // not index  header-search
        if (windowWidth <= 1024) {
            $('.noindexSearchipad').click(function () {
                $('.getMenuSearchipad').show();
                $('.searchinputop input').blur();
                $('.getMenuSearch .getMenuschTop .text1').focus();
            })

            $('.getMenuSearchipad .schtopleft b').click(function () {
                if($('.getMenuSearchipad .getMenuschTop .text1').val() == '' || $('.getMenuSearchipad .getMenuschTop .text1').val() == undefined){
                    $('.getMenuSearchipad').hide();
                }else{
                    $('.getMenuSearchipad .getMenuschTop .text1').val('');
                }
            })
        }
    }
    $('.sercondownUl li').mouseover(function () {
        $(this).addClass('checked');
    })
    $('.sercondownUl li').mouseout(function () {
        $(this).removeClass('checked');
    })

    //“Execute when input occurs in the input field”
    $('.searchinputop .text1').on('input', function () {
        if (!$(this).val()) { //“Check if the input field is empty”
            $('.showMores').hide() ;
            $(this).parent().parent().addClass('dggbDengSerTitlemouse');
            $('.searchLine').show();
            $('.searchinputop').css('z-index', '10');
        } else {
            var data_type = $('.schtab.check').attr('data-type');
            $('.searchLine').hide();
            $('.searchinputop').css('z-index', '1003');
            get_search_result(6, 'pc', data_type);
            $(this).parent().parent().addClass('dggbDengSerTitlemouse');
        }
    });

    $('.searchCons .schtab').click(function () {
        var data_type = $(this).attr('data-type');
        get_search_result(6, 'pc', data_type);
    })

    //“Mobile search tab switching”
    $('.getmuschCons .schtab').on('click',function () {
        var data_type = $(this).attr('data-type');
        get_search_result(6, 'mob', data_type);
    })

    $('.searchinputopbk .text1').on('input', function () {
        if (!$(this).val()) {
            $('.showMores').hide();
            $('.searchinputopbk  .closesearch').hide();
            $(this).parent().parent().addClass('dggbDengSerTitlemouse');
            $('.searchLine').show();
            $('.searchinputop').css('z-index', '10');
        } else {
            $('.searchinputopbk  .closesearch').show();
            get_search_wiki_list(6, 'pc');
        }
    });
    //“Mobile iPad search loading”
    $('.getMenuschTop .text1').on('input', function () {
        if (!$(this).val()) {
            $('.showMores').hide();
            if(!$(this).parent().parent().parent().parent().hasClass('getMenuSearchipad')){
                $(this).parent().parent().addClass('dggbDengSerTitlemouse');
            }
            $('.searchLine').show();
            $('.searchinputop').css('z-index', '10');
        } else {
            var data_type = $('.searchdownCons .check').attr('data-type');
            get_search_result(6, 'mob', data_type);
        }
    });

    //Mobile version encyclopedia search loading
    $('.getMenuschTop .wikitest').on('input', function () {
        if (!$(this).val()) {
            $('.showMores').hide();
            $(this).parent().parent().addClass('dggbDengSerTitlemouse');
            $('.searchLine').show();
            $('.searchinputop').css('z-index', '10');
        } else {
            get_search_wiki_list(6, 'mob');
        }
    });

    $('.serconTitleRightPc').on('click',function () {
        get_search_coin_list(100, 'pc');
        $('.serconTitleRight').hide();
    })

    $('.serconTitleRightMob').on('click',function () {
        get_search_coin_list(100, 'mob');
        $('.serconTitleRight').hide();
    })

    $('.showMorespc').on('click',function () {
        var data_type = $('.schtab.check').attr('data-type');
        get_search_result(100, 'pc', data_type);
        $('.showMores').hide();
    })
    $('.showMorespc').on('click',function () {
        var data_type = $('.schtab.check').attr('data-type');
        get_search_result(100, 'pc', data_type);
        $('.showMores').hide();
    })
    $('.showMoresmob').on('click',function () {
        var data_type = $('.schtab.check').attr('data-type');
        get_search_result(100, 'mob', data_type);
        $('.showMores').hide();
    })

    //New version search
    function get_search_result(size, device, data_type) {
        if (device == 'pc') {
            var search_keyword = $('.searchinputop .text1').val();
        } else {
            var search_keyword = $('.getMenuschTop input.text1').val();
        }
        if (search_keyword == '') {
            return;
        } else {
            $('.schDownNoData').hide();
            $('.loadingData').show();
            $('.schTitle').hide();
            $('.showMores').hide();
            $('.'+data_type+'Ul').hide();
        }
        
        var timestamp = new Date().getTime();
        $.ajax({
            url: "/index/index/get_search_result?page=1&size=" + size + '&data_type=' + data_type + '&search_keyword=' + search_keyword + '&doge_language=' + doge_language + '&timestamp=' + timestamp,
            type: 'GET',
            success: function (res) {
                if (device == 'pc') {
                    var curr_data_type = $('.searchCons .check').attr('data-type');
                } else {
                    var curr_data_type = $('.getmuschCons .schtab.check').attr('data-type');
                }
                if (curr_data_type != data_type) {
                    return;
                }
                $('.loadingData').hide();
                if (res == '') {
                    $('.schDown').show();
                    $('.schDownNoData').show();
                    $('.schTitle').hide();
                    $('.schDown .'+data_type+'Ul').hide();
                } else {
                    $('.schDownNoData').hide();
                    $('.'+data_type+'Ul').html(res);
                    $('.schDown .'+data_type+'Ul').show();
                    $('.schDown').show();
                    $('.schDown .'+data_type+'Title').show();
                    $('.schTitle').show();
                }
                if (res != '' && size == 6) {
                    $('.showMores').show()
                }
            },
            error: function (error) {
                // 处理错误  
                console.error('Error fetching data: ', error);
            }
        });
        $(this).parent().parent().removeClass('dggbDengSerTitlemouse');
        $('.searchLine').hide();
        $('.searchinputop').css('z-index', '1003');
    }

    function get_search_coin_list(size, device) {
        if (device == 'pc') {
            var search_keyword = $('.searchinputop .text1').val();
        } else {
            var search_keyword = $('.getMenuschTop input.text1').val();
        }
        var timestamp = new Date().getTime();
        $.ajax({
            url: "/index/index/get_search_coin_list?page=1&size=" + size + '&search_keyword=' + search_keyword + '&doge_language=' + doge_language + '&timestamp=' + timestamp,
            type: 'GET',
            success: function (res) {
                $('.sercontopUl').html(res);
            },
            error: function (error) {
                // 处理错误  
                console.error('Error fetching data: ', error);
            }
        });
        $('.serconTitleRight').show();
        $(this).parent().parent().removeClass('dggbDengSerTitlemouse');
        $('.searchLine').hide();
        $('.searchinputop').css('z-index', '1003');
    }

    function get_search_wiki_list(size, device) {
        if (device == 'pc') {
            var search_keyword = $('.searchinputopbk .text1').val();
        } else {
            var search_keyword = $('.getMenuschTop input.wikitest').val();
        }
        var timestamp = new Date().getTime();
        $.ajax({
            url: "/index/wiki/get_search_wiki_list?page=1&size=" + size + '&search_keyword=' + search_keyword + '&doge_language=' + doge_language + '&timestamp=' + timestamp,
            type: 'GET',
            success: function (res) {
                if (device == 'pc') {
                    $('.bksearchList').html(res);
                } else {
                    $('.bksearchListweb').html(res);
                }
            },
            error: function (error) {
                // 处理错误  
                console.error('Error fetching data: ', error);
            }
        });
        $('.serconTitleRight').show();
        $(this).parent().parent().removeClass('dggbDengSerTitlemouse');
        $('.searchLine').hide();
        $('.searchinputop').css('z-index', '1003');
    }

    //   login  登录 
    $('.pwdSee').click(function () {
        $(this).toggleClass('pwdShow pwdnotShow');
        if ($(this).parent().find('.passwords').attr('type') == 'password') {
            $(this).parent().find('.passwords').prop('type', 'text');
        } else {
            $(this).parent().find('.passwords').prop('type', 'password');
        }
        if ($(this).parent().hasClass('newPwddiv')) {
            if ($('.pwdNew .newpwdInput').attr('type') == 'password') {
                $('.pwdNew .newpwdInput').prop('type', 'text');
            } else {
                $('.pwdNew .newpwdInput').prop('type', 'password');
            }
        } else if ($(this).parent().hasClass('againnewPwddiv')) {
            if ($('.pwdNew .againnewpwd').attr('type') == 'password') {
                $('.pwdNew .againnewpwd').prop('type', 'text');
            } else {
                $('.pwdNew .againnewpwd').prop('type', 'password');
            }
        }
    })

    function validateEmail(email) {
        const emailPattern = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-zA-Z]{2,}$/;
        return emailPattern.test(email);
    }
    function validatePassword(password) {
        // 验证密码的规则：包含至少一个大写字母、一个小写字母和一个数字，长度在8到16之间
        const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,16}$/;
        return regex.test(password);
    }

    //验证邮箱密码格式是否正确
    $('.lrconLogin').click(function () {
        // let emails = $('.inputsEmail input').val()
        // warAndcurrect($('.lrCons'))
        // if (!validateEmail(emails)) {
        //     accountWarring('邮箱格式错误！')
        //     // alert('邮箱格式错误！')
        //     return;
        // }
        // let pwds = $('.inputsPwd input').val()
        // if (!validatePassword(pwds)) {
        // accountWarring('密码格式错误！至少一个大写字母、一个小写字母和一个数字，长度在8到16之间')
        // alert('密码格式错误！至少一个大写字母、一个小写字母和一个数字，长度在8到16之间')
        // return;
        // }
        // alert('邮箱密码格式正确！')
    })

    //输入框点击样式
    $('.changeShadow').on('focusin', function () {
        $(this).addClass('check');
    }).on('focusout', function () {
        $(this).removeClass('check');
    })

    $('.sendemail-again').click(function () {
        //Resend email
        var email = $('#email').val();
        // var newemail = $('#newemail').val();
        // Verify if the email verification code is correct here
        if (newemail) {
            sendEmail(newemail);
        } else {
            sendEmail(email);
        }
    });

    let targetTime = '';
    let intervalId = 0;
    let daojishi = false;
    let codeError = false;
    $('.verifycode-again').click(function () {
        accountLayuiInit();
    })
    // Update countdown function
    function updateCountdown() {
        var currentTime = new Date().getTime();
        let targetTime = getCookie('targetTime');
        var timeLeft = targetTime - currentTime;
        if ((timeLeft - 3) >= 0) {
            let minutes = Math.floor(((timeLeft - 3) / 1000 / 60) % 60);
            let seconds = Math.floor(((timeLeft - 3) / 1000) % 60);
            // 格式化显示
            document.getElementById('verirfycodetimes').innerText = minutes + ":" + seconds;
            $('.verifycode-time').show();
            $('.verifycode-again').hide();
        } else {
            daojishi = true;
            clearInterval(intervalId);
            document.getElementById('verirfycodetimes').innerText = "00:00";
            $('.verifycode-again').show();
            $('.verifycode-time').hide();
        }
    }

    $(document).on('click', '.lrCons', function () {
        $("div[name='val-item']").removeClass('errorCode');

    })
    // Account security layer initialization
    function accountLayuiInit() {
        // Reset the verification code input box
        $('#val-code-input').val('');
        $("div[name='val-item']").empty();
        $("div[name='val-item']").removeClass('available')
        $("div[name='val-item']").removeClass('errorCode');
        $(".newEmailsinput").val('');
        $(".newpwdInput").val('');
        $(".againnewpwd").val('');
        clearAllTimeout();
        closeAllLayer();
    }
    function clearAllTimeout() {
        clearTimeout(accountWarringTimeout);
        clearTimeout(accountCurrectTimeout);
    }
    function closeAllLayer() {
        $('.correct').hide();
        $('.warring').hide();
    }
    // Input error input box color change
    function warnChangeinput() {
        $('.newEmails').addClass('inputWarn');
        setTimeout("$('.newEmails').removeClass('inputWarn')", 3000);
    }

    //Warning successful pop-up window
    function warAndcurrect(dom) {

        var domTop = Math.ceil(dom.offset().top);
        var domLeft = Math.ceil(dom.offset().left);
        var domInnerwidth = Math.ceil(dom.innerWidth());
        var warAdnCorrwidth = Math.ceil($('#warring').innerWidth());
        var warAdnCorrheight = Math.ceil($('#warring').innerHeight());
        if (dom.find('.titles').length > 0) { // Change email and password operation
            var titleTop = Math.ceil(dom.find('.titles').offset().top);
        } else {
            var titleTop = domTop;
        }
        if (windowWidth <= 1024) {
            $('#warring').css('top', (titleTop - warAdnCorrheight) / 2);
            $('#warring').css('left', Math.ceil(((windowWidth - warAdnCorrwidth) / 2) + 10));
            $('#correct').css('top', (titleTop - warAdnCorrheight) / 2);
            $('#correct').css('left', Math.ceil(((windowWidth - warAdnCorrwidth) / 2) + 10));
        } else {
            $('#warring').css('top', (titleTop - warAdnCorrheight) / 2);
            $('#warring').css('left', Math.ceil((domInnerwidth / 2) + domLeft) - (warAdnCorrwidth / 2));
            $('#correct').css('top', (titleTop - warAdnCorrheight) / 2);
            $('#correct').css('left', Math.ceil((domInnerwidth / 2) + domLeft) - (warAdnCorrwidth / 2));
        }
    }



    function countdown(targetDate) {
        const target = new Date(targetDate).getTime(); //Timestamp of target time
        const interval = setInterval(() => {
            const now = new Date().getTime(); // The timestamp of the current time
            const distance = target - now; // time difference
            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);
            // document.getElementById("countdown").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
            if (distance < 0) {
                clearInterval(interval);
                // document.getElementById("countdown").innerHTML = "EXPIRED";
            }
        }, 1000);
    }
    //Demo
    layui.use('form', function () {
        var form = layui.form;
        form.on('submit(formDemo)', function (data) {
            layer.msg(JSON.stringify(data.field));
            return false;
        });
    });
    var clipboardData1 = null;

    if ($('.securityCode').length > 0) {
        // var vCode = new VerifyCode()
        var activeIndexs = 0;
        var verifycodelen = 0;

        function VerifyCode() {
            this.domCont = null;
            this.spans = [];
            this.passWord = [];
            this.activeIndex = 0;

            this.initDomSpans = () => {
                this.domCont = document.querySelector('#securityCode');
                this.spans = this.domCont.getElementsByTagName('span');
                return this;
            }
            this.clear = function () {
                this.passWord.length = 0;
                this.activeIndex = 0;
                let { spans } = this;
                for (var i = 0, len = spans.length; i < len; i++) {
                    spans[i].setAttribute('contenteditable', i == 0 ? true : false);
                    spans[i].innerHTML = '';
                }
            }
            // 监测验证码输入
            this.init = function (cb) {
                let { spans, passWord, domCont } = this.initDomSpans();
                //   spans[0].focus()
                domCont.addEventListener('click', e => {
                    let acIndex = this.activeIndex !== 6 ? this.activeIndex : 5;
                    spans[acIndex].focus();
                })
                // 监测输入
                domCont.addEventListener('keypress', e => {
                    123456
                    if (e.target.tagName.toLowerCase() === 'span') {
                        // clipboardData1 = e.originalEvent.clipboardData.getData('text');

                        // console.log(e.charCode)
                        // console.log(clipboardData1)
                        e.preventDefault();
                        if (e.target.innerHTML.length === 0 && this.activeIndex < spans.length && e.keyCode !== 8) {
                            var k = String.fromCharCode(e.charCode);
                            if (/\d/.test(k)) {
                                if (this.activeIndex !== spans.length - 1) {
                                    this.go(this.activeIndex + 1);
                                }
                                passWord.push(k);
                                spans[this.activeIndex].innerHTML = k;

                                this.activeIndex++;
                                activeIndexs++;

                                cb();
                            } else {
                                alert('请输入数字');
                            }
                        }
                    }
                }, false)
                domCont.addEventListener('compositionend', e => {
                    if (e.charCode == undefined) {
                        alert('请输入数字');
                        spans[this.activeIndex].innerHTML = '';
                    }
                })
                domCont.addEventListener('keyup', e => {
                    e = e || window.event;
                    if (e.keyCode === 8) {
                        if (this.activeIndex > 0) {
                            this.activeIndex--;
                            activeIndexs--;
                            this.back(this.activeIndex);
                        }
                    }
                }, false);
            }

            this.go = function (index) {
                let { spans } = this;
                for (var i = 0, len = spans.length; i < len; i++) {
                    spans[i].setAttribute('contenteditable', i == index ? true : false);
                }
                spans[index].focus();
                //   el = spans[index]; // jquery 对象转dom对象  
                // el.focus();
                // var range = document.createRange();
                // range.selectNodeContents(el);
                // range.collapse(false);
                // var sel = window.getSelection();

                // sel.removeAllRanges();
                // sel.addRange(range);
            }
            this.back = index => {
                let { spans, passWord } = this;
                if (index >= 0 && index < spans.length) {
                    for (var i = 0, len = spans.length; i < len; i++) {
                        spans[i].setAttribute('contenteditable', i == index ? true : false);
                    }
                    spans[index].innerHTML = '';
                    spans[index].focus();
                    passWord.pop();
                }
            }
        }
    }


    // next step  Monitor whether the verification code is entered completely
    $('.securicodebtn').click(function () {
        let length = Math.floor(Math.log10(activeIndexs)) + 1;
        if (activeIndexs == 0) {
            alert('请输入验证码1');
            return;
        }
        if (activeIndexs != 6) {
            alert('请输入验证码2');
        }
    })

    $('.lrconCreate').click(function () {
        let doms = '';
        let classs = '';
        if ($(this).data('id')) {
            classs = $(this).data('id').split("-");
            doms = $('.' + classs[0] + ' .lrCons');
        } else {
            doms = $('.lrCons');
        }
        warAndcurrect(doms);
    })

    $('.accountLaybtn').click(function () {
        $('.pwduploading').addClass('showUpload');
        $('.lrconCreate').addClass('noclick');
        $('.verifycode-again').hide();
        $('.verifycode-time').show();
        document.getElementById('verirfycodetimes').innerText = "01:00";

        if (windowWidth <= 1024) {  //iPad  web 
            $('.layuiDivaccount').show();
            $('.layuiDivaccount').addClass('weblayuiDivaccount');
            $('.accountlayCon').addClass('accountlayConWeb');
            var fixedElement = $('.accountlayCondiv'); // 获取layer位置
            if ($(this).hasClass('accountChange')) {
                nowlayerType = 'email';
                $('.emailTitle').show();
                $('.pwdTitle').hide();
                //账号 密码修改
            } else if ($(this).hasClass('accountChangepwd')) {
                nowlayerType = 'pwd';
            }
            warAndcurrect(fixedElement);
        } else {
            $('.layuiDivaccount').removeClass('weblayuiDivaccount');
            $('.accountlayCon').removeClass('accountlayConWeb');
            layerIndex = layer.open({
                type: 1,
                title: false,
                closeBtn: false,
                shadeClose: false,
                area: ['497px'],
                // maxHeight:heights + 'px',
                offset: '',
                scrollbar: true,
                content: $('#layuiDivaccount')
            });
            var email = $('#email').val();
            sendEmail(email);
            // 账号 邮箱修改
            if ($(this).hasClass('accountChange')) {
                nowlayerType = 'email';
                $('.emailTitle').show();
                $('.pwdTitle').hide();
                //账号 密码修改
            } else if ($(this).hasClass('accountChangepwd')) {
                nowlayerType = 'pwd';
            }
            var fixedElement = $('#layuiDivaccount').parent().parent(); // 获取layer位置
            var domWidth = Math.ceil(fixedElement.css('width').slice(0, -2));
            var domLeft = Math.ceil(fixedElement.css('left').slice(0, -2));
            var domTop = Math.ceil(fixedElement.css('top').slice(0, -2));
            $(valCodeInput).focus();
            $(valCodeItems[0]).addClass('available');
            $('#warring').css('top', domTop - 20 - 64);
            $('#warring').css('left', domLeft + Math.ceil(((domWidth - 368) / 2)));
            $('#correct').css('top', domTop - 20 - 64);
            $('#correct').css('left', domLeft + Math.ceil(((domWidth - 368) / 2)));

        }
        $('#layuiDivaccount').parent().css('overflow-y', 'hidden');
    })

    function sendEmail(email) {
        
        accountVerifyCode = false;
        $('.lrconCreate').addClass('noclick');
        $('.lrconCreate').prop('disabled', true);

        var logemail = replaceEmailMiddleChars(email);
        $('.logemail').text(logemail);
        var timestamp = new Date().getTime();
        $('.pwduploading').addClass('showUpload');
        $.ajax({
            url: "/index/user/forgetpwd_send_email?doge_language=" + doge_language + '&timestamp=' + timestamp,
            type: 'POST',
            data: {
                'email': email,
            },
            dataType: 'json',
            success: function (res) {
                if (res.code) {
                    accountCurrect(res.msg);
                    // var currentTime = new Date().getTime();
                    // let targetTime = getCookie('targetTime');
                    // var timeLeft = targetTime - currentTime;
                    // if (timeLeft < 0) {
                    //     targetTime = new Date().getTime() + 60 * 1000 //当前时间
                    //     setCookie('targetTime', targetTime, 1);
                    // }

                    $('.verifycode-again').hide();
                    $('.verifycode-time').show();
                    document.getElementById('verirfycodetimes').innerText = "01:00";

                    targetTime = new Date().getTime() + 60 * 1000; //current time
                    setCookie('targetTime', targetTime, 1);
                    intervalId = setInterval(updateCountdown, 1000);
                } else {
                    $('.verifycode-again').show();
                    $('.verifycode-time').hide();
                    deleteCookie('targetTime');
                    accountWarring(res.msg);
                }
                $('.pwduploading').removeClass('showUpload');
            },
            error: function (error) {
                // console.error('Error fetching data: ', error);
            }
        });
    }

    function checkEmailCpatcha(email, captcha) {
        $('.lrconCreate').addClass('noclick');
        $('.pwduploading').addClass('showUpload');
        var timestamp = new Date().getTime();
        $.ajax({
            url: "/index/user/forgetpwd_check_captcha?doge_language=" + doge_language + '&timestamp=' + timestamp,
            type: 'POST',
            data: {
                'email': email,
                'captcha': captcha,
            },
            dataType: 'json',
            success: function (res) {
                if (res.code) {
                    accountVerifyCode = true
                    accountCurrect(res.msg)
                    $('.lrconCreate').removeClass('noclick');
                    $('.lrconCreate').prop('disabled', false);
                } else {
                    accountWarring(res.msg);
                    accountVerifyCode = false;
                    $(valCodeItems).addClass('errorCode');
                    setTimeout(function () {
                        accountLayuiInit();
                    }, 3000);
                }
                $('.pwduploading').removeClass('showUpload');
            },
            error: function (error) {
                return false;
                // console.error('Error fetching data: ', error);
            }
        });
    }
    $(document).on("click", '.accountlayCon .lrconTop b', function () {
        if ($('.personalBody')) {
            $('.emailVerifycode').show();
            $('.emailNew').hide();
            $('.pwdNew').hide();
            $('.emaliSuccess').hide();
            $('.lrconCreate.verifycodeNext').removeClass('newemialCode');
            accountLayuiInit();
            layer.close(layerIndex)
            if (windowWidth <= 1024) {  //iPad  web 
                $('.layuiDivaccount').hide();
            } else {

            }
        }
    })

    $('#val-code-input').on('paste', function (e) {
        // Block default behavior
        e.preventDefault();
        // Retrieve data from the clipboard
        var clipboardData = e.originalEvent.clipboardData || window.clipboardData;
        var verificationCode = clipboardData.getData('text');
        valCodeInput.focus();
        $('#val-code-input').val(verificationCode);
        //Verify the verification code here
        if (valCodeInput.val().length == 6) {
            var captcha = valCodeInput.val();
            var email = $('#email').val();
            // Verify if the email verification code is correct here
            if (newemail) {
                checkEmailCpatcha(newemail, captcha);
            } else {
                checkEmailCpatcha(email, captcha);
            }
        } else if (valCodeInput.val().length < 6) {
            $(this).prop('disabled', false);
        } else {
            // Exceeding the length to extract the first six digits
            valCodeInput.val($(this).val().substring(0, 6));
        }

        valCodeLength = valCodeInput.val().length;
        $.each(verificationCode, function (index, value) {
            // Operate on the obtained numbers
            $(valCodeItems).removeClass('available');
            $(valCodeItems[index]).addClass('available');
            $(valCodeItems[index]).text(value);
        });
    });
    //Click to get verification code or click on the first digit input box to get focus, add available class style
    $(".val-box div").on("click", function () {
        if ($(".val-box").find(".available").length < 1) {
            $(valCodeInput).focus();
            $(valCodeItems[0]).addClass('available');
        }
    })

    // When we click on four small grids, the focus will be on the input box
    $('#val-box').on('click', function () {
        if ($(".val-box").find(".available").length == 1) {
            valCodeInput.focus();
        }
        warAndcurrect($(this).closest('.lrCons'));
    })

    // After changing the input box, take out the numbers inside and display them separately in four divs
    valCodeInput.on('input propertychange change', function (e) {
        valCodeLength = valCodeInput.val().length;
        if (valCodeInput.val() && regex.test(valCodeInput.val())) {
            $(valCodeItems).removeClass('available');
            $(valCodeItems[valCodeLength - 1]).addClass('available');
            $(valCodeItems[valCodeLength - 1]).text(valCodeInput.val().substring(valCodeLength - 1, valCodeLength));
        }
    })
    var that = this

    //Delete key, the length calculated by valCodeLength will decrease by one every time a number is deleted from the input box
    //Just delete the numbers in the corresponding cells and remove the available class style
    $(this).on('keyup', function (e) {
        if (e.keyCode === 8) {
            $(valCodeItems[valCodeLength]).text("");
            if (valCodeLength !== 0) {
                $(valCodeItems[valCodeLength]).removeClass('available');
                $(valCodeItems).removeClass('errorCode');
            }
        }
    });
    // When the verification code is filled with four digits, it begins to determine if it is correct
    $(valCodeInput).on("input propertychange", function () {
        if (valCodeInput.val().length == 6) {
            var captcha = valCodeInput.val();
            var email = $('#email').val();
            if (newemail) {
                checkEmailCpatcha(newemail, captcha);
            } else {
                checkEmailCpatcha(email, captcha);
            }
        } else if (valCodeInput.val().length < 6) {
            $(this).prop('disabled', false);
        } else {
            valCodeInput.val($(this).val().substring(0, 6));
        }
    })
    $('#val-code-input').blur(function () {
        // $(valCodeItems).removeClass('available');
    });

    // 1. Verify if the first display of the account pop-up layer is correct - redirect to input email address
    $('.accountlayCon .verifycodeNext').click(function () {
        $('.accountlayCon .verifycodeNext').addClass('noclick');
        $('.pwduploading').addClass('showUpload');
        $('.accountlayCon .verifycodeNext').prop('disabled', true);
        if (accountVerifyCode == true) {
            // Reset the verification code input box
            accountLayuiInit();
            $('.emailVerifycode').hide();
            if (nowlayerType == 'email') {
                // The previous step of monitoring is the verification of new/old email addresses码
                if ($(this).hasClass('newemialCode')) {
                    $('.emailNew').hide();
                    $('.emaliSuccess').show();
                } else {
                    $('.emailNew').show();
                }
            } else {
                $('.emailTitle').hide();
                $('.pwdTitle').show();
                $('.pwdNew').show();
            }
        } else {
            accountWarring();
        }
        $('.pwduploading').removeClass('showUpload');
        $('.accountlayCon .verifycodeNext').prop('disabled', false);
    })
    // 2. New email redirect - send verification code
    $('.accountlayCon .newemailNext').click(function () {
        if (nowlayerType == 'email') {
            newemail = $('#newemail').val();
            if (!validateEmail($('.newEmailsinput').val())) {
                accountWarring(email_format_error);
                warnChangeinput();
            } else {
                clearInterval(intervalId);
                deleteCookie('targetTime');
                sendEmail(newemail);
                $("#val-code-input").focus();
                $('.emailVerifycode').show();
                $('.emailNew').hide();
                $('.lrconCreate.verifycodeNext').addClass('newemialCode');
                $('.lrconCreate.newemialCode').removeClass('verifycodeNext');
            }
        } else if (nowlayerType == 'pwd') {
            $('.lrconCreate').addClass('noclick');
            $('.pwduploading').addClass('showUpload');
            $('.lrconCreate').prop('disabled', true);
            var email = $('#email').val();
            var newpassword = $('#newpassword').val();
            var renewpassword = $('#renewpassword').val();

            if ($('.newpwdInput').val() === $('.againnewpwd').val()) {
                //这里修改密码提交
                var timestamp = new Date().getTime();
                $.ajax({
                    url: "/index/user/forgetpwd?doge_language=" + doge_language + '&timestamp=' + timestamp,
                    type: 'POST',
                    data: {
                        'email': email,
                        'newpassword': newpassword,
                        'renewpassword': renewpassword,
                    },
                    dataType: 'json',
                    success: function (res) {
                        if (res.code) {
                            accountCurrect(res.msg);
                            $('.pwdNew').hide();
                            $('.emaliSuccess').show();
                            $('.emailchangeSuccess').hide();
                            $('.pwdchangeSuccess').show();
                            accountLayuiInit();
                            clearInterval(intervalId);
                            deleteCookie('targetTime');
                        } else {
                            accountWarring(res.msg);
                        }
                        $('.pwduploading').removeClass('showUpload');
                        $('.lrconCreate').removeClass('noclick');
                        $('.lrconCreate').prop('disabled', false);
                    },
                    error: function (error) {
                        // console.error('Error fetching data: ', error);
                    }
                });

            } else {
                accountWarring(the_two_password_inputs_are_inconsistent);
                $('.pwduploading').removeClass('showUpload');
                $('.lrconCreate').removeClass('noclick');
                $('.lrconCreate').prop('disabled', false);
            }
        }
    })

    // 3.The new email verification code is correct
    $(document).on('click', '.accountlayCon .newemialCode', function () {
        $('.accountlayCon .newemialCode').addClass('noclick');
        $('.accountlayCon .newemialCode').prop('disabled', false);
        // var captcha = valCodeInput.val();
        // var email = $('#email').val();
        // var newemail = $('#newemail').val();
        // if (newemail) {
        //     checkEmailCpatcha(newemail, captcha);
        // } else {
        //     checkEmailCpatcha(email, captcha);
        // }
        if (accountVerifyCode) {
            var timestamp = new Date().getTime();
            $.ajax({
                url: "/api/user/profile?doge_language=" + doge_language + '&timestamp=' + timestamp,
                type: 'POST',
                data: {
                    'email': newemail,
                },
                dataType: 'json',
                success: function (res) {
                    if (res.code) {
                        $('.emailVerifycode').hide();
                        $('.emailNew').hide();
                        $('.emaliSuccess').show();
                        accountLayuiInit();
                        clearInterval(intervalId);
                        deleteCookie('targetTime');
                        // window.location.reload();
                    }
                },
                error: function (error) {
                }
            });
        }
    })



    $('.accountlayCon .Closure').click(function () {
        accountLayuiInit();
        $("#val-code-input").focus();
        $('.emailVerifycode').show();
        $('.emailNew').hide();
        $('.emaliSuccess').hide();
        $('.lrconCreate.verifycodeNext').removeClass('newemialCode');
        if (windowWidth <= 1024) {  //iPad  web 
            $('.layuiDivaccount').hide();
        } else {
            $('.layuiDivaccount').show();
        }
        layer.close(layerIndex);
        window.location.reload();
    })

    $('.avatarDiv').mouseover(function () {
        $('.avaSelect').show();
    })
    $('.avatarDiv').mouseout(function () {
        $('.avaSelect').hide();
    })


    $('.coloridiv').mouseover(function () {
        $('.coloridivnod').show();
    })
    $('.coloridiv').mouseout(function () {
        $('.coloridivnod').hide();
    })

})

//Email verification error prompt
function accountWarring(msg) {
    clearTimeout(accountCurrectTimeout);
    $('.correct').hide();

    clearTimeout(accountWarringTimeout);
    $('.warring p').html(msg);
    $('.warring').show();
    accountWarringTimeout = setTimeout("$('.warring').hide()", 5000);
}
// Email verification correct prompt
function accountCurrect(msg) {
    clearTimeout(accountWarringTimeout);
    $('.warring').hide();

    clearTimeout(accountCurrectTimeout);
    $('.correct p').html(msg);
    $('.correct').show();
    accountCurrectTimeout = setTimeout("$('.correct').hide()", 5000);
}

function replaceEmailMiddleChars(email) {
    // Split email into two parts: username and domain name
    const [username, domain] = email.split('@');

    // If the username length is less than 5, the middle four characters cannot be replaced (at least 8 characters are required to replace the middle four)  
    if (username.length < 5) {
        return email; 
    }

    //Replace the middle four characters with****
    //Note: If the username length is 8, we will replace the 2nd to 5th characters;
    //If the username is longer, we replace the characters from (length/2-2) to (length/2+1) (rounded up)
    //For simplicity, we assume that the 2nd to 5th characters are always replaced (applicable in most cases)  
    const start = 1; //The index starts from 0, so the index of the second character is 1
    const end = 5; //Replace to the 5th character (excluding)  

    // Splicing together the new username section
    let newUsername = username.slice(0, start) + '****' + username.slice(end);

    // Return to a new email address
    return newUsername + '@' + domain;
}

/**
 * @param {number} number 
 * @param {boolean} dot 
 * @param {number} len 
 * @returns {string} 
 */
function decimal(number, dot = false, len = 4) {
    if (number >= 1) {
        return number.toFixed(len);
    }
    if (number < 1 && number > 0) {
        let numStr = number.toString();
        if (numStr.includes('e')) {
            numStr = number.toFixed(25);
        }
        let firstNonZero = -1;
        for (let i = 2; i < numStr.length; i++) {
            if (numStr[i] !== '0') {
                firstNonZero = i;
                break;
            }
        }
        if (firstNonZero === -1) {
            return '0.00';
        }
        const significantDigits = numStr.substring(firstNonZero, firstNonZero + len);
        if (dot && firstNonZero - 2 >= len) {
            return `0.0...0${significantDigits}`;
        }
        return `0.${'0'.repeat(firstNonZero - 2)}${significantDigits}`;
    }
    return '0.00';
}