/* Js for , Version=1792566086 */
 ;if(typeof(v) != "object") v = {};v.theme = {"template":"default","theme":"wide","device":"desktop"};;v.lang = {"confirmDelete":"\u60a8\u786e\u5b9a\u8981\u6267\u884c\u5220\u9664\u64cd\u4f5c\u5417\uff1f","deleteing":"\u5904\u7406\u4e2d","doing":"\u5904\u7406\u4e2d","loading":"\u52a0\u8f7d\u4e2d","updating":"\u66f4\u65b0\u4e2d...","timeout":"\u7f51\u7edc\u8d85\u65f6,\u8bf7\u91cd\u8bd5","errorThrown":"\u6267\u884c\u51fa\u9519\uff1a","continueShopping":"\u7ee7\u7eed\u8d2d\u7269","required":"\u5fc5\u586b","back":"\u8fd4\u56de","continue":"\u7ee7\u7eed","bindWechatTip":"\u53d1\u5e16\u529f\u80fd\u8bbe\u7f6e\u4e86\u7ed1\u5b9a\u5fae\u4fe1\u7684\u9650\u5236\uff0c\u8bf7\u5148\u7ed1\u5b9a\u5fae\u4fe1\u4f1a\u5458\u3002","importTip":"\u53ea\u5bfc\u5165\u4e3b\u9898\u7684\u98ce\u683c\u548c\u6837\u5f0f","fullImportTip":"\u5c06\u4f1a\u5bfc\u5165\u6d4b\u8bd5\u6570\u636e\u4ee5\u53ca\u66ff\u6362\u7ad9\u70b9\u6587\u7ae0\u3001\u4ea7\u54c1\u7b49\u6570\u636e"};;
$(function()
{
  $('.carousel-caption-title').css('color', $('.carousel-caption-title').data('color'));
});
;$('.icon-remove').click(function(e){
    e.stopPropagation();
    $(this).parents('.block-system-slide').remove();
    $('#header').css('top', 0);
    $('.page-wrapper').css('marginTop', '100px');
    resetStyle();
    localStorage.setItem('adClose', Date.now() + 7 * 24 * 3600 * 1000);
});

if(localStorage.getItem('adClose'))
{
    var now = new Date().getTime();
    if(now > Number(localStorage.getItem('adClose')))
    {
        localStorage.removeItem('adClose');
    }
    $('#header').css('top', 0);
    $('#block1506').hide();
    $('.page-wrapper').css('marginTop', '100px');
    resetStyle();
}

if(!localStorage.getItem('adClose') && $('.salon-ad').length > 0)
{
    $('#block1506').show();
    $('#header').css('top', '60px');
    $('.page-wrapper').css('marginTop', '160px');
    $('.parent-category').css('top', '88px');
    if($('html').hasClass('m-book-read'))
    {
        $('.search-wrap').css('top', '60px');
        $('.page-wrapper').css('marginTop', '60px');
    }
    if($('.ad-remove').length > 0) $('.table-heading').css('top', '159px');
}

function resetStyle()
{
    if($('html').hasClass('m-book-read'))
    {
        $('.search-wrap').css('top', 0);
        $('.page-wrapper').css('marginTop', 0);
    }
    $('.table-heading, .m-zentaoversion-history .type-title').css('top', '100px');
    $('.parent-category').css('top', '28px');
    $("#navbar[data-type='new_desktop_top'] .nav-item > .mega, .m-forum .directory, .m-ask .page-wrapper .col-md-2 .panel").css('top', '100px');
};
/* 国产替代导航 A/B 实验埋点：仅记录点击，POST 至 /event-log.html。 */
$(function()
{
    var BEACON = '/event-log.html';
    var ua = navigator.userAgent || '';
    if(/bot|crawl|spider|slurp|bingpreview|facebookexternalhit|monitor|headless/i.test(ua)) return;

    function send(node)
    {
        if(!node) return;
        $.ajax({
            url: BEACON,
            type: 'POST',
            data: {
                objectType: 'domestic_nav',
                objectID: 0,
                extra: 'domestic_nav_click',
                content: node.data('label') || '',
            }
        });
    }

    $('[data-experiment]').on('click', function()
    {
        send($(this));
    });
});

  /* 顶部导航选中态：根据当前 URL 高亮所属一级菜单。 */
  function normalizeNavHref(href)
  {
      var link = document.createElement("a");
      link.href = href;
      return {
          pathname: link.pathname || "/",
          search:   link.search || "",
          hash:     link.hash || "",
          hostname: link.hostname || ""
      };
  }

  var $newNav = $("#navbar[data-type=\"new_desktop_top\"]");
  if($newNav.length)
  {
      var currentPath = location.pathname + location.search;
      var currentURL  = location.pathname + location.search + location.hash;
      var hasActive   = $newNav.find(".navbar-nav > li.active").length > 0;

      if(!hasActive)
      {
          $newNav.find(".navbar-nav > li").each(function()
          {
              var $top    = $(this);
              var matched = false;

              $top.find("a").each(function()
              {
                  var href = $(this).attr("href");
                  if(!href || href.charAt(0) === "#") return;

                  var normalized = normalizeNavHref(href);
                  if(normalized.hostname && normalized.hostname !== location.hostname) return;

                  var navPath = normalized.pathname + normalized.search;
                  var navFull = navPath + normalized.hash;
                  if(navPath === currentPath || (normalized.hash && navFull === currentURL))
                  {
                      matched = true;
                      return false;
                  }
              });

              if(matched)
              {
                  $top.addClass("active");
                  return false;
              }
          });
      }
  }
;setTimeout(function(){$('#contactModal .modal-header .close').html('<span aria-hidden="true">×</span>')}, 500);
$('#contactModal').on('shown.zui.modal', function() {
    if($('.user-dropdown-menu').length > 0)
    {
        $.post(createLink('user', 'behavior'), {
            referrer: document.referrer,
            url: '/contactus',
            title: '联系我们',
            timestamp: Date.parse(new Date()) / 1000
      });
    }
    else
    {
        var userBehaviorData = JSON.parse(localStorage.getItem('userBehavior'));
        if(!userBehaviorData){ userBehaviorData = []; }
        userBehaviorData.push({
            referrer: document.referrer,
            url: '/contactus',
            title: '联系我们',
            timestamp: Date.parse(new Date()) / 1000
        })
        localStorage.setItem('userBehavior', JSON.stringify(userBehaviorData));
    }
});;setTimeout(function(){$('#touchModal .modal-header .close').html('<span aria-hidden="true">×</span>')}, 500);;let page = 'register';
if(location.href.includes('demo'))     page = 'demo';
if(location.href.includes('download')) page = 'download';
if(localStorage.getItem('giftType'))   page = localStorage.getItem('giftType');

const titleMap = {
    register: '注册成功',
    demo: '感谢试用',
    download: '感谢下载'
};
const descMap = {
    register: '注册',
    demo: '试用',
    download: '下载'
};

const tagSrc = `https://static.zentao.net/web/data/source/zentao/default/wide/${page}-tag.png`;
$('.gift-tag').attr('src', tagSrc);
$('.title-success').text(`${titleMap[page]}`);
$('.desc-tips').text(`${descMap[page]}`);
$('.gift-list').addClass(page);
;/* 许愿池「发布 / 编辑愿望」共用表单的交互：字段计分、附件上传与投入积分联动。*/
/* Wish form interactions shared by the publish page and the edit page: field scoring, attachment upload and invest score. */
$(document).ready(function()
{
    if(typeof(v) == 'undefined' || typeof(v.wishConfig) == 'undefined') return;

    var config = v.wishConfig;
    var reward = config.reward;
    var $form  = $('#wishForm');
    if(!$form.length) return;

    var investEdited = false;
    var lastScore    = 0;
    var rawResponses = [];   /* 上传接口的原始响应，用于失败时给出确切原因 */
    var staticIds    = parseIds($('#fileIdList').val());   /* 编辑页已有的附件（已绑定到愿望）*/
    var uploadedIds  = [];                                 /* 本次上传队列里成功拿到 id 的文件 */

    /* 附件：先上传后绑定，与论坛发帖一致；表单里的附件 id 一律写入 #fileIdList */
    if($('#wishUpload').length)
    {
        $('#wishUpload').uploader({
            file_data_name: 'file',
            autoResetFails: true,
            deleteConfirm: config.lang.attachDelete,
            /* 编辑页回显已有附件：它们不在本次上传队列里，由 staticFiles 渲染 */
            staticFiles: config.files,
            /* 前端先挡掉不支持的文件类型（服务端对危险后缀会直接丢弃文件） */
            filters: {mime_types: [{title: config.attachTitle, extensions: config.allowedExtensions}]},
            /* 移除附件：从 #fileIdList 里摘掉，保存时由服务端处理（已有附件走物理删除）*/
            deleteActionOnDone: function(file, done)
            {
                var fileID = fileServerID(file);
                if(fileID)
                {
                    staticIds   = removeID(staticIds, fileID);
                    uploadedIds = removeID(uploadedIds, fileID);
                }
                syncFileIds();
                return true;
            },
            onFileUploaded: function(item, response)
            {
                if(response && typeof(response.response) == 'string') rawResponses.push(response.response);
            },
            onUploadComplete: function(files)
            {
                var result = collectUploadFiles(files);
                rawResponses = [];

                uploadedIds = result.ids.map(function(id){return String(id);});
                syncFileIds();
                showAttachResult(result);
            }
        });
    }

    function parseIds(value)
    {
        var ids = [];
        String(value || '').split(',').map(function(id)
        {
            id = $.trim(id);
            if(id && ids.indexOf(id) < 0) ids.push(id);
        });
        return ids;
    }

    function removeID(ids, fileID)
    {
        return ids.filter(function(id){return id !== String(fileID);});
    }

    /* 上传队列里的文件取服务端 id，已有附件取自身 id */
    function fileServerID(file)
    {
        if(file && file.remoteData && file.remoteData.file && file.remoteData.file.id) return String(file.remoteData.file.id);
        if(file && file['static'] && file.id) return String(file.id);
        return '';
    }

    function syncFileIds()
    {
        var ids = staticIds.slice();
        uploadedIds.map(function(id)
        {
            if(ids.indexOf(id) < 0) ids.push(id);
        });
        $('#fileIdList').val(ids.join(','));
        updateScore();
    }

    function format(tpl, args)
    {
        var index = 0;
        return String(tpl).replace(/%s/g, function(){return args[index++];});
    }

    function hasAttachment()
    {
        return $.trim($('#fileIdList').val() || '') !== '';
    }

    /* 上传结果：成功拿到文件 id 才算数；失败（如超出服务端限制）时把原因带出来，避免"静默不加分" */
    function collectUploadFiles(files)
    {
        var result = {ids: [], failed: 0, message: ''};
        files.map(function(item)
        {
            var file = item && item.remoteData ? item.remoteData.file : null;
            if(file && file.id) return result.ids.push(file.id);

            result.failed++;
            if(!result.message && item && item.errorMessage) result.message = item.errorMessage;
            if(!result.message && item && item.remoteData && item.remoteData.message) result.message = item.remoteData.message;
        });

        /* 服务端没给出可读原因时，把原始响应带出来，避免又变成"静默不加分" */
        if(result.failed && !result.message && rawResponses.length)
        {
            var raw = String(rawResponses[0]).replace(/^\s+/, '');
            if(raw.charAt(0) == '{' || raw.charAt(0) == '[') result.message = raw.slice(0, 200);
        }
        return result;
    }

    function showAttachResult(result)
    {
        var $tip = $('[data-field="attachment"] .tip-score');
        if(!$tip.length) return;

        $tip.removeClass('is-failed').removeAttr('title');
        if(!result.failed) return;

        $tip.addClass('is-failed').find('.ts-todo').text(config.lang.attachFailed);
        if(result.message) $tip.attr('title', config.lang.attachMsg + result.message);
    }

    function isFilled(field)
    {
        if(field == 'authorize')  return $('#wishAuthorize').prop('checked');
        if(field == 'attachment') return hasAttachment();

        var $field = $form.find('[name="' + field + '"]');
        return $field.length > 0 && $.trim($field.val()) !== '';
    }

    function computeScore()
    {
        var score = 0;
        $.each(reward, function(field, points)
        {
            if(isFilled(field)) score += parseInt(points, 10);
        });
        return score;
    }

    /* 投入支持积分：下限 = 本次奖励积分，上限 = 已投入积分 + 当前积分 + 奖励积分差额，与后端同一口径。
       奖励回落时上限会随之收紧（差额不从 0 截断）：余额不够扣回奖励时，投入必须跟着下调，否则后端会以「积分不足」拦下。*/
    function maxInvestScore(awardScore)
    {
        var balance   = parseInt(config.balance, 10) || 0;
        var awardBase = parseInt(config.awardBase, 10) || 0;
        var invested  = parseInt(config.investBase, 10) || 0;
        return invested + balance + (awardScore - awardBase);
    }

    function updateInvest(awardScore, awardIncreased)
    {
        var $invest  = $('#wishInvest');
        var maxScore = maxInvestScore(awardScore);
        var value    = parseInt($invest.val(), 10);
        if(isNaN(value)) value = awardScore;

        /* 未手动改过时，投入跟随奖励积分下限上下浮动：奖励涨则跟涨，奖励回落则回到默认值；
           编辑页的默认值是该愿望当前投入（investBase），奖励高于原投入时跟涨，回落时回到原投入。
           已手动改过时只在奖励上涨超过手填值时抬到下限（需求第 6 条），不在输入过程中改动输入框。*/
        var base = parseInt(config.investBase, 10) || 0;
        if(!investEdited) value = Math.max(awardScore, base);
        else if(awardIncreased && value < awardScore) value = awardScore;

        if(value > maxScore) value = maxScore;

        var invalid = value < awardScore || value > maxScore;

        $invest.attr('min', awardScore).attr('max', maxScore).val(value);
        $('#wishInvestBox').toggleClass('is-error', invalid);
        $('#wishInvestTip').html(format(config.lang.investTip, [awardScore, config.balance])).toggleClass('is-error', invalid);
        $('#wishSubmit').prop('disabled', invalid);

        return value;
    }

    function updateScore()
    {
        var awardScore = computeScore();
        var increased  = awardScore > lastScore;

        if(increased)
        {
            $('#wishScore').addClass('is-up');
            setTimeout(function(){$('#wishScore').removeClass('is-up');}, 220);
        }
        lastScore = awardScore;

        $('#wishScore b').text(awardScore);
        $('#wishScore').toggleClass('is-zero', awardScore == 0);

        $form.find('[data-field]').each(function()
        {
            $(this).attr('data-filled', isFilled($(this).data('field')) ? '1' : '0');
        });

        updateInvest(awardScore, increased);
    }

    /* 加分提示文案与分值以后端配置为准 */
    $form.find('[data-field]').each(function()
    {
        var field  = $(this).data('field');
        var points = parseInt(reward[field], 10) || 0;
        $(this).attr('data-score-item', points);
        $(this).find('.ts-todo').text(format(config.lang.todo, [points]));
        $(this).find('.ts-got').text(format(config.lang.got, [points]));
    });

    $form.on('input change keyup', 'input, textarea, select', function(){updateScore();});
    $('#wishInvest').on('input', function(){investEdited = true;});

    /* 提交前再校验一次投入区间（键盘回车也会走到这里） */
    $form.submit(function()
    {
        var contact = $.trim($('#wishContact').val());
        if(!/^1[3-9]\d{9}$/.test(contact))
        {
            bootbox.alert(config.lang.contact);
            return false;
        }

        var awardScore = computeScore();
        var maxScore   = maxInvestScore(awardScore);
        var value      = parseInt($('#wishInvest').val(), 10);

        if(isNaN(value) || value < awardScore)
        {
            bootbox.alert(format(config.lang.minInvest, [awardScore]));
            return false;
        }
        if(value > maxScore)
        {
            bootbox.alert(format(config.lang.overBalance, [maxScore]));
            return false;
        }
        return true;
    });

    $.setAjaxForm('#wishForm', function(response)
    {
        if(response.result == 'success')
        {
            setTimeout(function(){location.href = response.locate;}, 1200);
        }
        else if(response.reason == 'needChecking') $('#captchaBox').html(Base64.decode(response.captcha)).show();
    });

    updateScore();
});

/* 许愿池前台共享的列表行【删除】*/
$(document).ready(function()
{
    /* 在按钮右侧显示提示气泡（成功绿 / 失败红），删除结果的统一出口。*/
    function wishTip($el, text, type)
    {
        if($el.data('zui.popover')) $el.popover('destroy');
        $el.popover({trigger: 'manual', content: text, placement: 'right', container: 'body', tipClass: 'popover-' + (type || 'success')}).popover('show');
    }

    $(document).on('click', '.wish-del', function()
    {
        var $link   = $(this);
        var href    = $link.attr('href');
        var tip     = $link.data('confirm');
        var failTip = $link.data('errortip');

        var dialog = bootbox.confirm(tip, function(result)
        {
            if(!result) return true;

            var $btn = dialog.find(".modal-footer [data-bb-handler='confirm']");
            $btn.prop('disabled', true);

            $.ajax({url: href, dataType: 'json'}).done(function(response)
            {
                if(response && response.result == 'success')
                {
                    wishTip($btn, response.message);
                    setTimeout(function(){location.href = response.locate;}, 1200);
                    return;
                }

                $btn.prop('disabled', false);
                wishTip($btn, (response && response.message) ? response.message : failTip, 'danger');
            }).fail(function()
            {
                $btn.prop('disabled', false);
                wishTip($btn, failTip, 'danger');
            });

            return false;   /* 结果返回前保持弹窗打开 */
        });
        return false;
    });
});

/* 主页与「往期已完成愿望」共用的搜索框：折叠时点放大镜展开，点关闭清空，带关键词时关掉即回到未筛选的列表。*/
/* The search box shared by the home page and the finished page: the magnifier opens it, the close icon resets it. */
$(document).ready(function()
{
    var $search = $('.wb-search');
    if(!$search.length) return;

    var $form  = $search.find('form');
    var $input = $search.find('.wbs-input');

    /* 页面本身是搜索结果的地址（含搜索词），关闭时必须回未筛选地址，否则输入框清空但列表还是筛选后的。*/
    /* The page was opened with a keyword, so closing has to go back to the unfiltered url. */
    var isFiltered = $search.hasClass('is-filtered');

    $search.find('.wbs-btn').on('click', function()
    {
        /* 折叠状态点图标只展开并聚焦，不提交；展开后交给表单原生提交。*/
        /* A click on the collapsed icon only opens the box, an open box submits as usual. */
        if($search.hasClass('is-open')) return true;

        $search.addClass('is-open');
        $input.trigger('focus');
        return false;
    });

    $search.find('.wbs-close').on('click', function()
    {
        $input.val('');
        if(isFiltered) return location.href = $search.data('url');

        $search.removeClass('is-open');
        return false;
    });

    /* 地址栏里的关键词被手动改掉后，提交仍走表单的 GET，页码自然回到第一页。*/
    /* The form submits as a GET, so a new search always starts from the first page. */
    $form.on('submit', function()
    {
        $input.val($.trim($input.val()));
        return true;
    });
});

/* 许愿池前台共享的【支持愿望（我也想要）】弹窗：主页列表行与详情页标题条共用同一份实现。*/
/* The support wish modal shared by the home list and the detail page. */
$(document).ready(function()
{
    var mask = document.getElementById('voteMask');
    if(!mask) return;

    var input      = document.getElementById('voteInput');
    var hint       = document.getElementById('voteHint');
    var balanceEl  = document.getElementById('voteBalance');
    var cancelBtn  = document.getElementById('voteCancel');
    var confirmBtn = document.getElementById('voteConfirm');
    var lang       = (typeof(v) == 'object' && v.wishVoteLang) ? v.wishVoteLang : {};

    var balance = parseInt(balanceEl.innerHTML, 10);
    var wishID  = 0;
    var posting = false;
    if(isNaN(balance)) balance = 0;

    function showHint(text, isError)
    {
        hint.innerHTML = text;
        hint.className = isError ? 'vm-hint is-error' : 'vm-hint';
    }

    function setDisabled(disabled)
    {
        confirmBtn.disabled = disabled;
        confirmBtn.className = disabled ? 'btn btn-solid btn-done' : 'btn btn-solid';
    }

    /* 成功提示：与列表行【删除】的 wishTip 同款，在【确认支持】按钮右侧弹 popover-success（样式见主题 style.css）。*/
    /* The same right-side popover-success the delete action uses, anchored on the confirm button. */
    function voteTip($el, text)
    {
        if($el.data('zui.popover')) $el.popover('destroy');
        $el.popover({trigger: 'manual', content: text, placement: 'right', container: 'body', tipClass: 'popover-success'}).popover('show');
    }
    /* 校验支持积分：整数、不小于 1、不超过剩余积分；不合法时在输入框后提示并禁用【确认支持】。*/
    /* Validate the points before submitting, the confirm button is disabled while invalid. */
    function check()
    {
        var score = String(input.value || '').replace(/\s/g, '');
        if(!/^[1-9]\d*$/.test(score))
        {
            input.className = 'vm-input num is-error';
            showHint(lang.scoreError || '', true);
            setDisabled(true);
            return 0;
        }
        if(parseInt(score, 10) > balance)
        {
            input.className = 'vm-input num is-error';
            showHint((lang.over || '').replace('%s', balance), true);
            setDisabled(true);
            return 0;
        }

        input.className = 'vm-input num';
        showHint(lang.tip || '', false);
        setDisabled(false);
        return parseInt(score, 10);
    }

    function open(id)
    {
        wishID = parseInt(id, 10) || 0;
        input.className = 'vm-input num';
        showHint(lang.tip || '', false);
        setDisabled(false);
        mask.className = 'vote-mask on';

        /* 光标放到默认值 1 的后面：type=number 不支持 setSelectionRange，而聚焦时浏览器把光标放在数字前面，
           只有值真正变化才会把光标移到末尾，所以先清空再赋值。*/
        /* Put the caret after the default value: focus() places it before the digit, and only a real value
           change moves it to the end, so the field is cleared first. */
        input.value = '';
        input.focus();
        input.value = 1;
    }

    function close()
    {
        if(posting) return;
        mask.className = 'vote-mask';
    }

    $(document).on('click', '.js-wish-vote', function()
    {
        open($(this).data('wish'));
        return false;
    });

    $(cancelBtn).on('click', close);
    $('#voteClose').on('click', close);
    $(mask).on('click', function(e){ if(e.target === mask) close(); });
    $(document).on('keydown', function(e){ if(e.key === 'Escape') close(); });
    $(input).on('input', check);

    $(confirmBtn).on('click', function()
    {
        if(posting) return;

        var score = check();
        if(!score) return;

        posting = true;
        confirmBtn.disabled = true;

        $.ajax({url: createLink('wish', 'vote', 'wishID=' + wishID), type: 'POST', data: {score: score}, dataType: 'json'})
        .done(function(response)
        {
            /* 支持成功：在【确认支持】按钮右侧弹 popover-success，2 秒后关闭弹窗并刷新当前页，
               刷新后列表数字、我的卡片余额、详情页支持人数与头像组都由服务端重算。*/
            /* On success show a popover-success on the right of the button, then close the modal and reload
               the page after 2 seconds so every counter comes from the server. */
            if(response && response.result == 'success')
            {
                posting = true;
                voteTip($(confirmBtn), (lang.success || '').replace('%s', score));
                setTimeout(function()
                {
                    $(confirmBtn).popover('destroy');
                    mask.className = 'vote-mask';
                    location.href = location.href.split('#')[0];
                }, 2000);
                return;
            }

            posting = false;
            setDisabled(false);
            showHint((response && response.message) ? response.message : (lang.failed || ''), true);
            if(response && response.balance !== undefined)
            {
                balance = parseInt(response.balance, 10) || 0;
                balanceEl.innerHTML = balance;
            }
        })
        .fail(function()
        {
            posting = false;
            setDisabled(false);
            showHint(lang.failed || '', true);
        });
    });
});

/* 期次 tab 条（愿望主页 / 排期名单页共用）：一行放不下时出现左右箭头，点箭头滚动一个 tab 宽度，到头置灰。*/
/* The period tab bar shared by the wish home and the schedule page: the arrows show up only when the tabs overflow. */
$(document).ready(function()
{
    $('.wish-ui .tabbar').each(function()
    {
        var $bar    = $(this);
        var $scroll = $bar.find('.tabbar-scroll');
        var $prev   = $bar.find("[data-tabnav='prev']");
        var $next   = $bar.find("[data-tabnav='next']");
        if(!$scroll.length) return;

        function maxScroll()
        {
            return $scroll[0].scrollWidth - $scroll[0].clientWidth;
        }

        function refresh()
        {
            var max = maxScroll();
            $bar.toggleClass('tabbar--scrollable', max > 1);
            if(max <= 1) return;
            $prev.prop('disabled', $scroll.scrollLeft() <= 1);
            $next.prop('disabled', $scroll.scrollLeft() >= max - 1);
        }

        function scrollBy(dir)
        {
            var $tab = $scroll.find('a').first();
            var step = $tab.length ? Math.max($tab.outerWidth() + 26, 120) : 200;
            $scroll.stop().animate({scrollLeft: $scroll.scrollLeft() + dir * step}, 200, refresh);
        }

        $prev.on('click', function(){scrollBy(-1);});
        $next.on('click', function(){scrollBy(1);});
        $scroll.on('scroll', refresh);

        /* 主页搜索框展开 / 收起会改掉 tab 条的可用宽度，动画结束再算一次箭头状态。*/
        /* The home search box changes the width of the tab bar, refresh the arrows when its transition ends. */
        var $search = $bar.parent().find('.wb-search form');
        if($search.length) $search.on('transitionend', refresh);

        var timer = null;
        $(window).on('resize', function()
        {
            clearTimeout(timer);
            timer = setTimeout(refresh, 150);
        });

        refresh();

        /* 打开页面时把当前 tab 带进可视区：期次多时它可能落在箭头外面，看不出来选中的是哪期。*/
        /* Bring the active tab into view: with many periods it may sit outside the arrows on load. */
        var $on = $scroll.find('a.on').first();
        if($on.length)
        {
            var onBox = $on[0].getBoundingClientRect();
            var scBox = $scroll[0].getBoundingClientRect();
            var target = $scroll[0].scrollLeft + (onBox.left - scBox.left) - ($scroll[0].clientWidth - onBox.width) / 2;
            $scroll[0].style.scrollBehavior = 'auto';   /* 首屏直接落位，不要走一趟滚动动画 */
            $scroll[0].scrollLeft = Math.max(0, target);
            $scroll[0].style.scrollBehavior = '';
        }

        refresh();
    });
});
$(document).ready(function()
{
    /* ---------- ① 投票截止倒计时 ---------- */
    var hotbar = document.getElementById('whHotbar');
    if(hotbar)
    {
        var deadline = parseInt(hotbar.getAttribute('data-deadline'), 10);
        var serverNow = parseInt(hotbar.getAttribute('data-now'), 10);
        /* 本机时钟与服务端时钟的偏差，只在页面打开时取一次；之后一律按折算后的服务端时间计算。 */
        var clockOffset = isNaN(serverNow) ? 0 : serverNow - (new Date()).getTime();
        var pad = function(number)
        {
            number = String(number);
            return number.length < 2 ? '0' + number : number;
        };
        var setDigit = function(key, value)
        {
            var node = hotbar.querySelector("[data-cd='" + key + "']");
            if(node) node.innerHTML = value;
        };
        /* 天数位数不固定（可能超过 99 天），按实际位数重建数字格。 */
        var setDigits = function(node, value)
        {
            if(!node) return;
            var html = '';
            for(var i = 0; i < value.length; i++) html += "<span class='cd-d'>" + value.charAt(i) + "</span>";
            node.innerHTML = html;
        };
        var timer = null;
        var stop = function()
        {
            if(timer)
            {
                clearInterval(timer);
                timer = null;
            }
        };
        var tick = function()
        {
            var left = Math.floor((deadline - ((new Date()).getTime() + clockOffset)) / 1000);
            if(left <= 0)
            {
                hotbar.style.display = 'none';
                stop();
                return;
            }
            var day    = pad(Math.floor(left / 86400));
            var hour   = pad(Math.floor(left % 86400 / 3600));
            var minute = pad(Math.floor(left % 3600 / 60));
            var second = pad(Math.floor(left % 60));
            setDigits(hotbar.querySelector("[data-cd='day']"), day);
            setDigit('hour1', hour[0]);
            setDigit('hour2', hour[1]);
            setDigit('min1', minute[0]);
            setDigit('min2', minute[1]);
            setDigit('sec1', second[0]);
            setDigit('sec2', second[1]);
        }
        tick();
        timer = setInterval(tick, 1000);
        /* 浏览器会节流后台标签页的定时器，回到页面时立刻重算，避免看到过期数字。 */
        $(window).on('focus pageshow', tick);
        $(document).on('visibilitychange', function()
        {
            if(!document.hidden) tick();
        });
    }
});
$('#foot').insertBefore('#footer');

$(document).ready(function(){
    if(typeof headerList != 'undefined') return ;
    headerList = true;
    $('#footer #footNav').append('<a class="privacy" href="/page/zentao-privacypolicy.html">隐私政策</a>');
    $('#footer #powerby').append('<a class="ipip" href="https://www.ipip.net/" target="_blank">本站IP数据由IPIP.NET提供</a>');
    $('#siteNav').append(`<a class="language" href="http://www.zentao.pm/" target="_blank"><i class="icon icon-globe"></i>English</a>`);
    $('.m-user-register .form-horizontal .agreement-form span').after(`<span>和《<a href="/page/zentao-privacypolicy.html" target="_blank">隐私政策</a>》</span>`);
});

if($('html').hasClass('m-index-index'))
{
    setTimeout(function(){$('#rightDocker').hide();}, 50);
    $(document).on('scroll', function()
    {
        var showTop = $(window).width() > 1440 ? 300 : 600;
        if($(window).scrollTop() > showTop)  $('#rightDocker').show();
        if($(window).scrollTop() < showTop)  $('#rightDocker').hide();
    })
}

$('.m-faq #top #toggleToc').text('隐藏目录').addClass('hide');
var isAdvanced = false;
$('.m-faq #top #toggleToc').on('click', function() {
   isAdvanced = !isAdvanced;
   if (isAdvanced) {
       $(this).text('显示目录').addClass('show').removeClass('hide');
   } else {
       $(this).text('隐藏目录').addClass('hide').removeClass('show');
   }
});

var windowScrollHeight = window.innerHeight;
var minScrollHeight = windowScrollHeight - $('#header').height() - $('#footer').height() - $('#foot:visible').height() - $('.salon-ad').height();
if($('.page-wrapper').height() < minScrollHeight) {
    $('.page-wrapper').css('minHeight', minScrollHeight)
}

if($('.salon-ad').is(':visible')) $('.article .catalog-wrap').css('top', $('#header:visible').height() + $('.article .search-wrap').height() + 60 + 32);
var $articleSubtitle = $('.article .content h2, .article .content h3, .article .content h4, .article h5, .article .content h6');

$(window).scroll(function(){
    // if($(window).scrollTop()>230){
    //     $(".m-faq #top #toggleToc").addClass('fixed');
    // }else{
    //     $(".m-faq #top #toggleToc").removeClass('fixed');
    // }
    
    if($('body > .popover > .contact-popover-content').length > 0) $('body > .popover > .contact-popover-content').parents('.popover').remove();
    
    $articleSubtitle.each(function(idx, item)
    {
        var currentID = $(item).attr('id');
        if($(item).offset().top - $(document).scrollTop() > 0 && $(item).offset().top - $(document).scrollTop() + $('.book-header')?.height()  < $('.salon-ad:visible')?.height() + $('#header:visible')?.height())
        {
            $(`.catalog-wrap a[href='#${currentID}']`).parent('li').addClass('active').siblings().removeClass('active');
        }
    });
});

$(document).on('click', '.catalog-wrap li a', function(e)
{
    e.preventDefault();
    $(this).parent('li').addClass('active').siblings().removeClass('active');
    var selector  = $(e.target).attr('href');
    var scrollTop = $(selector).offset().top - $('#header:visible')?.height() - 20;
    if($('.salon-ad').is(':visible')) scrollTop = $(selector).offset().top - $('#header:visible')?.height() - 60 - 20;
    history.pushState('', '', location.pathname + selector);
    window.scrollTo({ top: scrollTop});
});

$('.m-faq table:last-child').before('<hr>');
// 首页点击空白处登录弹框隐藏
$(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();
}

function getWebToken()
{
    const timestamp = Math.floor(Date.now() / 1000);
    const random = Math.random().toString(36).substr(2, 8);
    const userAgent = btoa(navigator.userAgent);
    return btoa(`${timestamp}:${random}:${userAgent}`);
}

$('.input-group-btn .btn').click(function()
{
    var value = $(this).parent().prev('input').val();
    if(value)
    {
        $('#searchForm').submit();
    }
});

$('.input-group #words').keypress(function(e) 
{
    if(e.keyCode === 13) 
    {
        var value = $(this).val();   
        if(value)
        {
            $('#searchForm').submit();
        }
        return false;
    }
});

$('.banner[data-form=83] p').append('<span>（报告将于2024年3月发布）</span>');

$('#rightDocker #globalCode').hover(function() {
    $('#rightDocker img[data-src]').each(function()
    {
        var $this = $(this);
        $this.attr('src', $this.data('src')).removeAttr('data-src');
    });
});

if($(window).width() < 768) {
    $('.popover-wrapper').unbind('hover');
    $('.popover-wrapper').off('click').click(function() {
        if($('.overlay').is(':visible')) 
        {
            $('#rightDocker .overlay').hide();
            $(this).find('.popover').removeClass('active');
        }
        else
        {
            $('#rightDocker .overlay').show();
            $(this).find('.popover').addClass('active');
        }
    });
    $('#rightDocker .overlay').on('click', function(e){e.stopPropagation(); $('.popover').removeClass('active'); $(this).hide();});
    $('#rightDocker .overlay').on('touchmove', function(e){e.stopPropagation(); $('.popover').removeClass('active'); $(this).hide();});
    $('.popover').click(function(e){e.stopPropagation();});
}

$('.dropdown-hover').on('mouseenter', '.white-paper', function(e) {
    e.stopPropagation();
});

$('#navbar a[href=""], .dropdown-second-menu > a').click(function(e) {e.preventDefault();});

if($('#navbar').data('type') == 'desktop_top')
{
    if($('#navbar .dropdown > a').find('.caret').length < 1) $('#navbar .dropdown > a').append(`<b class="caret" style="margin-left: 8px"></b>`);
}

if($('html').hasClass('m-article-workshop')) $('a[href="/services.html"]').parent().addClass('active');

function getZentaoChangeLog(type, version) {
    $('.change-log').after(`<i class="icon icon-spin icon-spinner-indicator"></i>`);
    var options = {
        name: 'logModal',
        title: $('#article h1').text(),
        width: '700px'
    };
    $.get(`/zentaoversion-get-${type}-${version}.html`, function(response) {
        options.custom = response.changelog.replace(/\n/g, '<br>');
        var logModalTrigger = new $.zui.ModalTrigger(options);
        logModalTrigger.show();
        $('.icon-spin').remove();
    });
}

function checkUaIsMobile() {
    return /(iPhone|iPad|iPod|iOS|Android|Linux armv8l|Linux armv7l|Linux aarch64)/i.test(
        navigator.userAgent
    );
}

$('.m-ask-index .col-md-10 .panel-wrapper').on('click', '.question-name a', function(e){history.pushState('', '', $(this).attr('href'))});

if($(window).width() > 1440) $('#globalCode .button-text').html('社群交流');
if($(window).width() < 1440) $('#globalCode .button-text').html('交流');

function debounce(fn, delay = 300) {
    let timer = null;

    return function() {
        if (timer) {clearTimeout(timer)}
        timer = setTimeout(() =>
        {
            fn.apply(this, arguments);
            timer = null;
        }, delay);
    }
}
setTimeout(function()
{
    $('.mini-btn').css('box-shadow', 'unset').css('-webkit-box-shadow', 'unset');
}, 1000);

setTimeout(function()
{
    if($('#div_company_mini').length && $('#div_company_mini')[0].style.display == 'none' && $('.mini-btn')[0].style.display == 'block') open_floatWindow();
}, 4000);

if(typeof(FingerprintJS) !== 'undefined')
{
    FingerprintJS.load()
    .then((fp) => {
        return fp.get();
    })
    .then((result) => {
        const visitorId = result.visitorId;
        let   location  = 'home';
        $('.contact-analysis').click(function()
        {
            if($(this).data('location')) location = $(this).data('location');
            const postData = {
              fingerprint: visitorId,
              triggerType: 'click',
              location: location,
              triggerTime: Math.round(new Date().getTime() / 1000)
            };
            $.post(createLink('contact', 'event'), postData);
        });
    });
}

$(document).ready(function()
{
    var targetPages = [
        '/solution-interactive-whiteboard.html',
        '/solution-thinmory.html',
        '/solution-rd-performance.html',
        '/solution-instant-messaging.html'
    ];
    
    var currentPath = window.location.pathname;
    
    var isTargetPage = targetPages.some(function(page)
    {
        return currentPath.endsWith(page);
    });
    
    if(isTargetPage)
    {
        function updateContactInfo()
        {
            $('#contactPopover').find('.sales-image-box img.sales-image').attr({
                'src': 'https://static.zentao.net/web/data/source/zentao/default/wide/contact-limu.webp',
                'alt': '李木'
            });

            $('#contactPopover').find('.sales-introduction-image img.sales-qrcode').attr({
                'src': 'https://static.zentao.net/web/data/source/zentao/default/wide/contact-limu-qrcode.webp',
                'alt': '李木'
            });

            $('#contactPopover').find('.sales-name').text('李木');
            
            $('#contactPopover').find('.sales-contact a').html(`<i class="icon icon-phone"></i>18562583552`)
            $('#contactPopover').find('.sales-contact>div').html(`<i class="icon icon-qq"></i>3985895121`)
        }
        
        updateContactInfo();
        
        var observer = new MutationObserver(function(mutations)
        {
            if($('#contactPopover').length)
            {
                updateContactInfo();
                observer.disconnect(); 
            }
        });
        
        observer.observe(document.body,
        {
            childList: true,
            subtree: true
        });
        
        setTimeout(function()
        {
            observer.disconnect();
        }, 10000);
    }
});


$(document).ready(function()
{ 
    const fileDownloadLink  = $.cookie('fileDownloadLink');
    const userControlLength = $('.siteNav .top-user-control').length;
    const isDownloadReferer = window.location.href == $.cookie('fileDownloadReferer');

    if(fileDownloadLink && isDownloadReferer && userControlLength > 0)
    {
        $.removeCookie('fileDownloadLink', { path: '/' });
        window.location.href = fileDownloadLink;
    }
});

$(document).ready(function()
{
    function detectNavVersion()
    {
        return $('#navbarWrapper').hasClass('navbarWrapperNew') ? 'nav-a' : 'nav-b';
    }

    $(document).on('click', 'a[href*="/demo.html"], a[href*="/downloads.html"]', function(e) {
        e.preventDefault();
        const href = $(this).attr('href');
        var objectType = href.includes('demo.html') ? 'demo' : 'download'
        var objectType = 'click-' + objectType + '-link';
        getUserFingerprint(objectType).then(result => {
            var data = {
                objectType: objectType,
                objectID: 0,
                content: '',
                fingerprint: result,
                location: 'nav',
                extra: detectNavVersion()
            }
            $.post(createLink('event', 'log'), data, function(response)
            {
                if(response.result == 'success')
                {
                    console.log('log success');
                    window.location.href = href;
                }
                else
                {
                    console.log('log fail');
                    window.location.href = href;
                }
            }, 'json');
        });
    });
    
    if($('.salon-ad').length > 0)
    {
        if(!localStorage.getItem('adClose'))
        {
            $("#navbar[data-type='new_desktop_top'] .nav-item > .mega, .m-forum .directory, .m-ask .page-wrapper .col-md-2 .panel").css('top', '160px');
        }
        else
        {
            $("#navbar[data-type='new_desktop_top'] .nav-item > .mega, .m-forum .directory, .m-ask .page-wrapper .col-md-2 .panel").css('top', '100px');
        }
    }
});
;
$(document).ready(function()
{
    $('a[data-download=1]').each(function()
    {   
        link = window.btoa(window.encodeURIComponent($(this).attr('href')));
        fileName = window.btoa(window.encodeURIComponent($(this).text()));
        $(this).attr('data-toggle', 'modal').attr('href', createLink('misc', 'download', 'link=' + link + '&fileName=' + fileName));
    }); 
})
;(function() {var _53code = document.createElement("script");_53code.src = "https://tb.53kf.com/code/code/ef35685c8390f5aa37b2ddce53eca3e09/1";var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(_53code, s);})();;
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'AW-17656773669');
;(function(w,d,t,u,o){w[u]=w[u]||[],o.ts=(new Date).getTime();var n=d.createElement(t); n.src="https://bat.bing.net/bat.js?ti="+o.ti+("uetq"!=u?"&q="+u:""),n.async=1, n.onload=n.onreadystatechange=function(){var s=this.readyState;s&&"loaded"!==s&&"complete"!==s||( o.q=w[u],w[u]=new UET(o),w[u].push("pageLoad"),n.onload=n.onreadystatechange=null)}; var i=d.getElementsByTagName(t)[0];i.parentNode.insertBefore(n,i); })(window,document,"script","uetq",{ti:"187256618", enableAutoSpaTracking: true});;
function uet_report_conversion() {window.uetq = window.uetq || [];window.uetq.push('event', 'signup', {});}
function uet_report_conversion_submit() {window.uetq = window.uetq || [];window.uetq.push('event', 'submit_lead_form', {});}
;
function loadCartInfo(twinkle)
{
    var cartDialog = bootbox.dialog(
    {
        message: v.addToCartSuccess,
        buttons:
        {
            back:
            {
                label:     v.lang.continueShopping,
                className: 'btn-primary',
                callback:  function(){location.reload();}
            },
            cart:
            {
                label:     v.gotoCart,
                className: 'btn-primary',
                callback:  function(){location.href = createLink('cart', 'browse');}
            }
        }
    });
    cartDialog.on('hidden.zui.modal', function() {location.reload();})
}
;v.clickNavLogin = "\u70b9\u51fb\u5bfc\u822a\u767b\u5f55";;v.genFingerprintError = "\u751f\u6210\u6307\u7eb9\u4fe1\u606f\u51fa\u9519";;
async function getUserFingerprint()
{
    const agent  = typeof(FingerprintJS) !== 'undefined' ? await FingerprintJS.load() : '';
    const result = agent ? await agent.get() : '';
    return result ? result.visitorId : '';
}
$().ready(function()
{
    if(Number($.cookie('showTip')))
    {
        setTimeout(function()
        {
            if(!$('.download-modal').is(':visible')) 
            {
                $('#showGift').click();
                localStorage.removeItem('giftType');
                $.get('/user-showtip.html');
            }
        }, 50);
    }

    // set utm source.
    const urlParams = new URLSearchParams(window.location.search);

    // set rong pm source.
    const rongFromSource = urlParams.get('from');
    if(rongFromSource)
    {
        const rongPmFromArr = [
            'rrplnav',
            'rrpl',
            'boston-consulting-group-matrix',
            'appeals',
            '4ps',
            '3c-model',
            'PESTLE',
            'rrplOther',
            'column',
            'columnProducts',
            'columnProject',
            'columnTesting',
            'columnOps',
            'columnEffectiveness',
            'columnOther',
            'whitepaperDownload'
        ];
        const rongIndexFrom  = rongPmFromArr.indexOf(rongFromSource);
        if(rongIndexFrom !== -1) localStorage.setItem('utmSource', 'rongPm-' + rongFromSource);
    }

    // set google ads utm source.
    const utmSource = urlParams.get('utm_source');
    if(utmSource)
    {
        if(utmSource === 'google') localStorage.setItem('utmSource', utmSource);
    }


    getUserFingerprint().then(result => {
        // Record the user behavior.
        if($('.user-dropdown-menu').length > 0)
        {
            $.post(createLink('user', 'behavior'), {
                referrer: document.referrer,
                url: document.URL,
                title: document.title,
                timestamp: Date.parse(new Date()) / 1000,
                fingerprint: result
            });
        }
        else
        {
            var userBehaviorData = JSON.parse(localStorage.getItem('userBehavior'));
            if(!userBehaviorData){ userBehaviorData = []; }
            
            userBehaviorData.push({
                referrer: document.referrer,
                url: document.URL,
                title: document.title,
                timestamp: Date.parse(new Date()) / 1000,
                fingerprint: result
            })
            localStorage.setItem('userBehavior', JSON.stringify(userBehaviorData));
        }

        const utmSource = localStorage.getItem('utmSource') || '';
        if(utmSource)
        {
            $.post(createLink('ads', 'behavior'), {
                referrer: document.referrer,
                url: document.URL,
                title: document.title,
                timestamp: Date.parse(new Date()) / 1000,
                fingerprint: result,
                utmSource: utmSource
            });
        }

        // Record the time of mouse hover on the contact button.
        var mouseinTime, mouseoutTime;
        $('.popover-wrapper').hover(function() 
        {
            if($(window).width() < 768) return;
            if($(this).find('.contact').length > 0)
            {
                mouseinTime = new Date().getTime();
            }
            $(this).find('.popover').addClass('active')
        }, 
        function() 
        {
            if($(window).width() < 768) return;
            if($(this).find('.contact').length > 0)
            {
                mouseoutTime = new Date().getTime();
                if(mouseoutTime - mouseinTime > 3000)
                {
                    const postData = {
                        fingerprint: result,
                        triggerType: 'hover',
                        location   : 'rightDocker',
                        triggerTime: Math.round(mouseoutTime / 1000),
                        duration   : Math.round((mouseoutTime - mouseinTime) / 1000)
                    };
                    $.post(createLink('contact', 'event'), postData);
                }
            }
            $(this).find('.popover').removeClass('active')
        });

        // Record user behavior when clicking login button.
        if($(window).width() > 1240)
        {
            $(".siteNav .btn-login").off('click').click(function(elem)
            {
                $.cookie('extAutoDownloadID', 0);
                if(window.qrCodeTimer) window.clearInterval(window.qrCodeTimer);
                const id = 'loginModal';
                showModalLogin(id, elem.target, 13, 0, 1);
                $('body').css('padding-right', 'unset');
                var userBehaviorData = JSON.parse(localStorage.getItem('userBehavior'));
                if(!userBehaviorData) {userBehaviorData = []; }
                userBehaviorData.push({
                    referrer: document.referrer,
                    url: '/user-login.html',
                    title: v.clickNavLogin,
                    timestamp: Date.parse(new Date()) / 1000,
                    fingerprint: result
                });
                localStorage.setItem('userBehavior', JSON.stringify(userBehaviorData));
                return false;
            });

            $('.top-user-control').click(function(){location.href = $(this).attr('href');});
        }
    });
});

$('.cover-image').each(function(idx, item)
{
    const imgSrc = $(item).data('image');
    $(item).parent().css({'background-image': `url(${imgSrc})`});
})
if($(window).width() < 768)
{
    $('.navbar-toggle').off('click').click(function(e)
    {
        e.preventDefault();
        $('.navbar-collapse, .parent-category').toggle();
    });
}

setTimeout(function()
{
    $('.dropdown-hover').css('pointer-events', 'unset');
}, 1500);

var hoverTimer = 0, outTimer = 0;
$('.navbar-nav .dropdown-hover').off('mouseenter').on('mouseenter', function()
{
    clearTimeout(outTimer);
    var dropdownMenu = $(this).find('.dropdown-menu');
    hoverTimer = setTimeout(function()
    {
        $('.dropdown-menu').hide();
        dropdownMenu.css('display', 'flex');
        $('.navbar-nav li a .icon').removeClass('active');
        dropdownMenu.siblings('a').find('.icon').addClass('active');
    }, 400);
});
$('.navbar-nav .dropdown-hover').off('mouseleave').on('mouseleave', function()
{
    clearTimeout(hoverTimer);
    var menu = $(this).find('.dropdown-menu');
    outTimer = setTimeout(function()
    {
        menu.hide();
        menu.siblings('a').find('.icon').removeClass('active');
    }, 400);
});

$('.navbar').off('mouseleave').on('mouseleave', function()
{
    setTimeout(function(){$('.navbar-nav .dropdown-menu').hide();}, 400);
});

$('.nav li.dropdown-hover').unbind('mouseover');

if($(window).width() < 768)
{
    $('.navbar').unbind('mouseleave');
    $('.nav li.dropdown-hover').unbind('mouseenter').unbind('mouseleave').unbind('mouseover').unbind('mouseout');
    $('.dropdown-hover .first-nav-name').off('click').click(function(e)
    {
           e.preventDefault();
           e.stopPropagation();
           $(this).parent('li').toggleClass('open').siblings().removeClass('open');
    });
    $('.dropdown-third-menu a').click(function(e)
    {
        e.stopPropagation();
    });
    $('.close-nav-wrapper img').click(function(){$('.navbar-toggle').trigger('click');});
}

$('.global-search').click(function()
{
    $(this).siblings('form').addClass('active').find('input').focus();
});
$('#searchbar .icon-close').click(function()
{
    $(this).parents('form').removeClass('active').find('input').val('');
})
