window.onload = function() {
  var script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');
  script.src = 'https://stat.xiaonaodai.com/stat.php?id=6356299';
  document.body.appendChild(script);
  var _hmt = _hmt || [];
  if (window.device == 1) {
    /**
     *   使用fastclick
     */
    FastClick.attach(document.body); //去手机延时
    $('.header-mobile').show();
    $('.footer-mobile').show();
    $($('.drawer-main')[0]).show();
    //右滑菜单
    // $('.drawer').drawer();
    // $('.js-trigger').click(function () {
    //   $('.drawer').drawer('open');
    // });
    $('.logo').on('click touchend', function() {
      window.location.href = '/index';
    });
    //右滑菜单
    $('.menu-btn').on('click', function() {
      $('.drawer-main ').css('right', '0');
      $('.drawer-overlay-upper').css({
        width: '100%',
        display: 'block'
      });
    });
    //关闭手机菜单
    $('.drawer-overlay-upper').on('click touchend', function() {
      $('.secondary-menu').hide();
      $('.product-menu').removeClass('active');
      $('.agricultura-menu').removeClass('active');
      $('.secondary-menu .secondary-list ').removeClass('active');
      $('.secondary-list ').removeClass('active');
      $('body').css('height', 'auto'); //关闭后打开body的scroll事件
      $('.drawer-main ').css('right', '-1000px');
      $(this).hide();
    });
    $('.drawer-main').on('touchstart', function(e) {
      $('body').css('height', '100%'); //防止页面上移，限制死页面，直接在css写死会影响index里的滚动事件
    });
    /***************** 头部搜索*******************/
    $('input').on('blur', function() {
      window.scroll(0, 0);
    });
    $('.header-mobile #search').on('click touchend', function() {
      $('.header-mobile #mask').show();
      $('.header-mobile #searchForm').show();
      setTimeout(function() {
        $('.header-mobile .search-content').addClass('animate');
      }, 200);
    });
    $('.header-mobile #closeSearch').on('click touched', function() {
      $('.header-mobile .search-content').removeClass('animate');
      setTimeout(function() {
        $('.header-mobile #mask').fadeOut(300);
        $('.header-mobile #searchForm').fadeOut(400);
      }, 200);
    });
    $('.header-mobile .search-btn').on('click touched', function() {
      var code = $('.header-mobile #search-input').val();
      if (code) {
        window.open('https://antifake.jgwcjm.com/?code=' + code)
        // if (code.length == 16 || code.length == 17 || code.length == 18) {
        //   if (!/^\d+$/.test(code)) {
        //     toastr.error('请输入正确的防伪溯源码！');
        //   } else {
        //     // window.location.href = 'http://ncp2.cjm.so/index.aspx?code=' + code;
        //     window.open(
        //       'http://wap.cjm.so/Operator/Common/TraceQueryResult.aspx?code=' +
        //         code
        //     );
        //   }
        // } else if (
        //   code.length == 20 ||
        //   code.length == 21 ||
        //   code.length == 22 ||
        //   code.length == 36
        // ) {
        //   if (!/^\d+$/.test(code)) {
        //     toastr.error('请输入正确的防伪溯源码！');
        //     return;
        //   }
        //   var validate = '';
        //   if ($('.header-mobile #verifyCode').is(':visible')) {
        //     validate = $('.header-mobile #verifyCodeInput').val();
        //     if (!validate || validate.length < 4) {
        //       toastr.error('请输入右侧图片中的4位数字');
        //       return;
        //     }
        //   }
        //   $.ajax({
        //     url: '/index/antiFakeQuery',
        //     cache: false,
        //     type: 'post',
        //     data: {
        //       code: code,
        //       validate: validate
        //     },
        //     dataType: 'json',
        //     success: function(r) {
        //       if (r.data.success) {
        //         if (r.data.result.ResultID.length > 0) {
        //           location.href =
        //             'http://wap.cjm.so/Operator/Common/AntiFakeQueryResult.aspx?type=anti&ID=' +
        //             r.data.result.ResultID +
        //             '&code=' +
        //             code;
        //         } else {
        //           toastr.error(r.data.message);
        //         }
        //       } else {
        //         if (r.data.result && r.data.result.validate_code_error == '1') {
        //           if ($('.header-mobile #verifyCodeImg').length > 0) {
        //             $('.header-mobile #verifyCodeImg').attr(
        //               'src',
        //               'http://wap.cjm.so/Common/ValidateCode.ashx?Type=&Demand=&w=&h=&r=' +
        //                 Math.random()
        //             );
        //             $('.header-mobile .verifyCodeInput').val('');
        //             $('.header-mobile .search-case .search-input').css({
        //               'border-bottom-right-radius': '0',
        //               'border-bottom-left-radius': '0'
        //             });
        //             $('.header-mobile #verifyCode').show();
        //           }
        //         } else {
        //           toastr.error(r.data.message);
        //         }
        //       }
        //     },
        //     error: function() {
        //       console.log('请求异常');
        //     }
        //   });
        // } else {
        //   toastr.error('请输入正确的防伪溯源码！');
        // }
      } else {
        toastr.error('请输入正确的防伪溯源码！');
      }
    });
    $('.header-mobile .header-mobile #verifyCodeImg').on(
      'click touched',
      function() {
        $('.header-mobile #verifyCodeImg').attr(
          'src',
          'http://wap.cjm.so/Common/ValidateCode.ashx?Type=&Demand=&w=&h=&r=' +
            Math.random()
        );
      }
    );
    /********** *手机菜单点击***************/
    $('.drawer-nav-list li').on('click', function(e) {
      if ($(e.target).hasClass('first-menu')) {
        $('.secondary-menu').hide();
        $('.drawer-nav-list li').removeClass('active');
        $(this).addClass('active');
        var htmlDeheight = document.documentElement.clientHeight;
        var secondaryListHeight =
          $(this).find('.secondary-list').length * $(this).height();
        var firstMenuIndex = $(this).data('num') - 1;
        if (secondaryListHeight > htmlDeheight) {
          var topPer = -firstMenuIndex + '00%';
          $(this)
            .find('.secondary-menu')
            .css({
              top: topPer,
              'overflow-y': 'scroll',
              height: htmlDeheight
            });
        }
        $(this)
          .find('.secondary-menu')
          .fadeIn(300);
        $(this)
          .find('.secondary-list')
          .on('click', function(e) {
            $('.drawer-nav-list .secondary-list').removeClass('active');
            $(this).addClass('active');
            window.location.href = $(this).data('href');
          });
      }
    });

    $('#xiaomage-help-entry-mobile #gotoTop').hide(); //隐藏go to top按钮
    $(window).scroll(function() {
      var scrollHeight = $(document).height() * 0.02;
      if ($(this).scrollTop() > scrollHeight) {
        $('#xiaomage-help-entry-mobile #gotoTop').fadeIn(300);
      } else {
        $('#xiaomage-help-entry-mobile #gotoTop').fadeOut(300);
      }
    });
    $('#qqDialogMobile').on('click touchend', function() {
      // window.open('mqqwpa://im/chat?chat_type=wpa&uin=2410542817&version=1&src_type=web&web_src=oicqzone.com')
      window.open(
        'http://wpa.qq.com/msgrd?v=3&uin=2410542817&site=baidu.com&menu=yes'
      );
    });
    $('#xiaomage-help-entry-mobile .panel-close').on(
      'click touchend',
      function() {
        $('#xiaomage-help-entry-mobile .xiaomage-panel').removeClass(
          'panelShow'
        );
      }
    );
    $('#xiaomage-help-entry-mobile .xiaomage-entry-button').on(
      'click touchend',
      function() {
        setTimeout(function() {
          $('#xiaomage-help-entry-mobile .xiaomage-panel').addClass(
            'panelShow'
          );
        }, 200);
      }
    );
  } else {
    $('.header-pc').show();
    $('.footer-pc').show();
    $('#gotoTop').hide(); //隐藏go to top按钮
    $(window).scroll(function() {
      var scrollHeight = $(document).height() * 0.02;
      if ($(this).scrollTop() > scrollHeight) {
        $('#gotoTop').fadeIn();
      } else {
        $('#gotoTop').fadeOut();
      }
    });
    /**
     * 右侧咨询动画
     */
    $('#xiaomage-help-entry-pc .panel-close').click(function() {
      setTimeout(function() {
        $('#xiaomage-help-entry-pc .xiaomage-panel').removeClass('panelShow');
      }, 10);
    });
    $('#xiaomage-help-entry-pc .xiaomage-entry-button').on(
      'mouseover click',
      function() {
        setTimeout(function() {
          $('#xiaomage-help-entry-pc .xiaomage-panel').addClass('panelShow');
        }, 200);
      }
    );
    $('#xiaomage-help-entry-pc .xiaomage-entry-button').on(
      'mouseout',
      function() {
        setTimeout(function() {
          $('.xiaomage-panel').removeClass('panelShow');
          $('.xiaomage-panel').on('mouseover', function() {
            setTimeout(function() {
              $('#xiaomage-help-entry-pc .xiaomage-panel').addClass(
                'panelShow'
              );
            }, 200);
          });
          $('#xiaomage-help-entry-pc .xiaomage-panel').on(
            'mouseout',
            function() {
              setTimeout(function() {
                $('#xiaomage-help-entry-pc .xiaomage-panel').removeClass(
                  'panelShow'
                );
              }, 200);
            }
          );
        }, 200);
      }
    );

    /**
     * 头部搜索
     */
    $('#search').on('click', function() {
      $('#mask').fadeIn(800);
      $('#searchForm').fadeIn(800);
      setTimeout(function() {
        $('.search-content').addClass('animate');
      }, 200);
    });
    $('#closeSearch').on('click', function() {
      $('.search-content').removeClass('animate');
      setTimeout(function() {
        $('#mask').fadeOut(300);
        $('#searchForm').fadeOut(400);
      }, 200);
    });
    $('.search-btn').on('click', function() {
      var code = $('#search-input').val();
      if (code) {
        // var label = $(this).data('track');
        // window._hmt && window._hmt.push(['_trackEvent', label, 'click']); //统计埋点
        // if (code.length == 16 || code.length == 17 || code.length == 18) {
        //   if (!/^\d+$/.test(code)) {
        //     toastr.error('请输入正确的防伪溯源码！');
        //   } else {
        //     // window.location.href = 'http://ncp2.cjm.so/index.aspx?code=' + code;
        //     window.open('http://aio.s315.net?code=' + code, '_blank');
        //   }
        // } else if (
        //   code.length == 20 ||
        //   code.length == 21 ||
        //   code.length == 22 ||
        //   code.length == 36
        // ) {
        //   if (!/^\d+$/.test(code)) {
        //     toastr.error('请输入正确的防伪溯源码！');
        //     return;
        //   }
        //   var validate = '';
        //   if ($('#verifyCode').is(':visible')) {
        //     validate = $('#verifyCodeInput').val();
        //     if (!validate || validate.length < 4) {
        //       toastr.error('请输入右侧图片中的4位数字');
        //       return;
        //     }
        //   }
        //   $.ajax({
        //     url: '/index/antiFakeQuery',
        //     cache: false,
        //     type: 'post',
        //     data: {
        //       code: code,
        //       validate: validate
        //     },
        //     dataType: 'json',
        //     success: function(r) {
        //       if (r.data.success) {
        //         if (r.data.result.ResultID.length > 0) {
        //           location.href =
        //             '/antifakeQueryResult?ID=' +
        //             r.data.result.ResultID +
        //             '&code=' +
        //             code;
        //         } else {
        //           toastr.error(r.data.message);
        //         }
        //       } else {
        //         if (r.data.result && r.data.result.validate_code_error == '1') {
        //           if ($('#verifyCodeImg').length > 0) {
        //             $('#verifyCodeImg').attr(
        //               'src',
        //               'http://wap.cjm.so/Common/ValidateCode.ashx?Type=&Demand=&w=&h=&r=' +
        //                 Math.random()
        //             );
        //             $('.verifyCodeInput').val('');
        //             $('.search-case .search-input').css({
        //               'border-bottom-right-radius': '0',
        //               'border-bottom-left-radius': '0'
        //             });
        //             $('#verifyCode').show();
        //           }
        //         } else {
        //           toastr.error(r.data.message);
        //         }
        //       }
        //     },
        //     error: function() {
        //       console.log('请求异常');
        //     }
        //   });
        // } else {
        //   toastr.error('请输入正确的防伪溯源码！');
        // }

        window.open('https://antifake.jgwcjm.com/?code=' + code)
      } else {
        toastr.error('请输入正确的防伪溯源码！');
      }
    });
    $('#verifyCodeImg').on('click', function() {
      $('#verifyCodeImg').attr(
        'src',
        'http://wap.cjm.so/Common/ValidateCode.ashx?Type=&Demand=&w=&h=&r=' +
          Math.random()
      );
    });

    $('#qqDialog').on('click', function() {
      window.open(
        'tencent://Message/?Uin=2410542817&websiteName=q-zone.qq.com&Menu=yes'
      );
    });
  }
  /**
   *   总体页面渐进切换
   */
  setTimeout(function() {
    $('.main').fadeIn(300);
  }, 200);
  /**
   * 头部header nav切换
   */
  var dropOnOff = true;
  if (dropOnOff) {
    $('#heaaderNav li').hover(
      function() {
        // $(this).addClass('nav-hover');
        $(this)
          .children('.nav-drop-list')
          .fadeIn(200);
        dropOnOff = false;
      },
      function() {
        // $(this).removeClass('nav-hover');
        $(this)
          .children('.nav-drop-list')
          .fadeOut(200);
        setTimeout(function() {
          dropOnOff = true;
        }, 600);
      }
    );
  }

  /**
   * 回到顶部
   */
  $('#gotoTop img').click(function() {
    $('html ,body').animate(
      {
        scrollTop: 0
      },
      300
    );
    return false;
  });
  //商桥链接跳转
  $('.shangqiao').on('click touchend', function() {
    console.log(111);
    if ($('#nb_invite_ok').length > 0) {
      $('#nb_invite_ok').click();
    }
    // window.open('http://p.qiao.baidu.com/cps/chat?siteId=10120001&userId=6356299')
  });
};

//mobile端内容区下拉图标
// lineNum: 限制行数
// onOff： 是否显示下拉
// className: class名 exp: '.content-limit8'
//注： 因为涉及到sessionstorage存储，不同的页面需设置不同class，否则会造成数据覆盖
var str = []; //用来装内容区的初始内容
function contentLimit(className, lineNum, onOff) {
  //初始化(对于一个页面里面有导航菜单切换并且不会跳转新网页时的初始化处理)
  if ($('.unfold-icon' + lineNum + className.slice(1)).length > 0) {
    var len = $(className).length;
    for (var i = 0; i < len; i++) {
      $($(className)[i]).html(JSON.parse(sessionStorage.getItem(className))[i]);
      if (
        $($(className)[i])
          .next()
          .hasClass('unfold-icon')
      ) {
        $($(className)[i])
          .next()
          .remove();
      }
    }
  }
  var refer = parseFloat($('html').css('fontSize'));
  //默认高度
  var defHeight = (44 * lineNum) / 75; //转换为rem
  // initContent(onOff, refer, defHeight);
  for (var i = 0; i < $(className).length; i++) {
    $($(className)[i]).data('num', i);
    //如果高度超出
    var infoHeight = $($(className)[i]).height() / refer; //转rem
    if (onOff) {
      str[i] = $($(className)[i]).html();
    }
    // console.log(infoHeight);
    if (infoHeight > defHeight) {
      // console.log(111);
      //设置默认高度,隐藏超出部分
      var text = $($(className)[i]).html();
      var temp = '';
      var j = 0;
      $($(className)[i]).html(temp);
      while ($($(className)[i]).height() / refer <= defHeight) {
        temp = text.substring(0, j + 1);
        j++;
        $($(className)[i]).html(temp);
      }
      var slen = temp.length;
      tempstr = temp.substring(0, slen - 1);
      len = tempstr.length;
      $(className)[i].innerHTML = tempstr.substring(0, len - 4) + '......'; //替换string后面三个字符
      //按钮显示
      if (onOff) {
        var downDrop = '<img class="unfold-icon">';
        $($(className)[i]).after(downDrop);
        $($(className)[i])
          .next()
          .attr('src', '/static/src/images/about/unfold.png');
        $($(className)[i])
          .next()
          .addClass('unfold-icon' + lineNum + className.slice(1)); //为了防止同时添加多个限制函数造成事件重复添加
        // $($(className)[i]).next().css('margin-top', '0.2rem');
        if ($($(className)[i]).css('display') == 'block') {
          $($(className)[i])
            .next()
            .css('display', 'block');
        }
      }
    }
  }
  if (onOff) {
    sessionStorage.setItem(className, JSON.stringify(str));
  }
  // 点击按钮
  $('.unfold-icon' + lineNum + className.slice(1)).on('click', function() {
    var curHeight =
      $(this)
        .prev()
        .height() / refer;
    if (curHeight <= defHeight) {
      $(this).css('transform', 'rotate(180deg)');
      var index = $(this)
        .prev()
        .data('num');
      $(this)
        .prev()
        .html(JSON.parse(sessionStorage.getItem(className))[index]);
    } else {
      var text = $(this)
        .prev()
        .html();
      var temp = '';
      var j = 0;
      $(this)
        .prev()
        .html(temp);
      while (
        $(this)
          .prev()
          .height() /
          refer <=
        defHeight
      ) {
        temp = text.substring(0, j + 1);
        j++;
        $(this)
          .prev()
          .html(temp);
      }
      var slen = temp.length;
      tempstr = temp.substring(0, slen - 1);
      len = tempstr.length;
      $(this)
        .prev()
        .html(tempstr.substring(0, len - 4) + '......'); //替换string后面三个字符
      $(this).css('transform', 'rotate(0)');
    }
  });
}

function getParams(key) {
  var url = window.location.search,
    searchResult = {},
    strs = [],
    i = 0,
    item,
    params = {};
  if (url.indexOf('?') >= 0) {
    strs = url.substr(1).split('&');
    for (; i < strs.length; i++) {
      item = strs[i].split('=');
      searchResult[item[0].toLowerCase()] = decodeURIComponent(item[1]);
    }
  }
  params = searchResult;
  return params[key.toLowerCase()];
}

function htmlDecode(text) {
  //1.首先动态创建一个容器标签元素，如DIV
  var temp = document.createElement('div');
  //2.然后将要转换的字符串设置为这个元素的innerHTML(ie，火狐，google都支持)
  temp.innerHTML = text;
  //3.最后返回这个元素的innerText(ie支持)或者textContent(火狐，google支持)，即得到经过HTML解码的字符串了。
  var output = temp.innerText || temp.textContent;
  temp = null;
  return output;
}

function loadCss(src, fn) {
  //加载完CSS
  var node = document.createElement('link');
  node.rel = 'stylesheet';
  node.href = src;
  document.head.insertBefore(node, document.head.lastChild);
  if (node.attachEvent) {
    node.attachEvent('onload', function() {
      fn(null, node);
    });
  } else {
    setTimeout(function() {
      poll(node, fn);
    }, 0); // for cache
  }

  function poll(node, callback) {
    var isLoaded = false;
    if (/webkit/i.test(navigator.userAgent)) {
      //webkit
      if (node['sheet']) {
        isLoaded = true;
      }
    } else if (node['sheet']) {
      // for Firefox
      try {
        if (node['sheet'].cssRules) {
          isLoaded = true;
        }
      } catch (ex) {
        // NS_ERROR_DOM_SECURITY_ERR
        if (ex.code === 1000) {
          isLoaded = true;
        }
      }
    }
    if (isLoaded) {
      setTimeout(function() {
        callback(null, node);
      }, 1);
    } else {
      setTimeout(function() {
        poll(node, callback);
      }, 10);
    }
  }

  node.onLoad = function() {
    fn(null, node);
  };
}
