$(function(){
  if ($('.scroll-to-target').length) {
    $(".scroll-to-target").on('click', function() {
        var target = $(this).attr('data-target');
        // animate
        $('html, body').animate({
            scrollTop: $(target).offset().top
        }, 1000);
        return false;
    });
  }

  $(window).on('scroll', function() {
    if ($('.scroll-to-top').length) {
        var strickyScrollPos = 100;
        if ($(window).scrollTop() > strickyScrollPos) {
            $('.scroll-to-top').fadeIn(500);
        } else if ($(this).scrollTop() <= strickyScrollPos) {
            $('.scroll-to-top').fadeOut(500);
        }
    }
  });

  $('.menu-mobile-btn').click(function () {
    $('.side-panel-menu').addClass('viewed');
    $('#mask').addClass('viewed');
  })

  $('#mask').click(function(){
    $('.side-panel-menu').removeClass('viewed');
    $('#mask').removeClass('viewed');
    closeLayer();
  })

  // 导航下拉
  $('header .dropdown').hover(function(){
    $(".subnav").removeClass('show').addClass('hidden');
    var subid = $(this).data('id');
    $(".subnav_"+subid).removeClass('hidden').addClass('show'); 
  },function(){
    $('.subnav').hover(function(){
    },function(){
      $(".subnav").removeClass('show').addClass('hidden');
    });
  });


  $('.icon_wechat').hover(function(){
    $('img.wechat_logo').fadeIn(500);
  },function(){
    $('img.wechat_logo').fadeOut(500);
  });

  initTopNav()
  clickTopNav();
  clickTopMenu();
  productLists();
});


function initTopNav() {  //初始化导航滑块位置
    var list=$('.nav').children('.item')
    $.each(list,function (index,item) {  
      var b=$(`.nav .item:nth-child(${index+1})`)
      if($(this).attr('data-active')=='1'){
        //初始化滑块
        var slip = $('.topnavslip');
        slip.show()
        slip.css({
          'left': parseInt($(this).position().left) + $(this).outerWidth(true)*0.5 - slip.width()/2 +'px'
        });

        return
      }
    })
}

function clickTopNav() {  //改变导航滑块位置
  var slip = $('.topnavslip')
  $('.nav .item').mouseenter(function () {
    if($(this).prop("className")!='item dropdown'){
      $(".subnav").removeClass('show').addClass('hidden');
    }
    //显示滑块
    if (slip.css('display') == 'none') {
      slip.show();
    };
    //移动滑块
    slip.stop().animate({
      left: parseInt($(this).position().left) + $(this).outerWidth(true)*0.5 - slip.width()/2 +'px'
    }, 300);
  });
  
    $('.nav').mouseleave(function(){  //当鼠标离开头部时 滑块位置复位
      initTopNav()
    })
};


function clickTopMenu() {
    $('.right-menu').click(function () {
      if ($('.menu-list').is(':hidden')) {
        $('.menu-list').show()
      } else {
        $('.menu-list').hide()
      }
    })
  };
  
function showWechat() {  
  $('footer .icons').mouseenter(function(){
    $('footer .icons .wechat-png').show()
  })
  $('footer .icons').mouseleave(function(){
    $('footer .icons .wechat-png').hide()
  })
}

/**
 * 加盟合作
 * @return {[type]} [description]
 */
function showLayerJMHZ(id=0){
  var str = '<form action="javascript:void(0);" id="JMHZForm" novalidate="novalidate">';
      str += '<div class="con row">';
      str += '<div class="col-md-6"><img src="/statics/images/web/jmhz.png"></div>';
      str += '<div class="col-md-6"><h4>加盟合作<span>提交后，我们将在6个工作小时内与您联系</span></h4><div class="form"><div class="label"><svg class="icon icon_wechat" aria-hidden="true"><use xlink:href="#icon-company"></use></svg><input type="text" name="company" placeholder="请输入公司名称"></div><div class="label"><svg class="icon icon_wechat" aria-hidden="true"><use xlink:href="#icon-name"></use></svg><input type="text" name="name" placeholder="姓名（必填）"></div><div class="label"><svg class="icon icon_wechat" aria-hidden="true"><use xlink:href="#icon-mobile"></use></svg><input type="text" name="mobile" placeholder="手机号码（必填）"></div><div class="label"><svg class="icon icon_wechat" aria-hidden="true"><use xlink:href="#icon-city"></use></svg><input type="text" name="city" placeholder="城市"></div></div></div>';
      str += '</div>';
      str += '<div class="bot row"><div class="col-12" style="text-align:right;"><button class="btn btn-sm"  onclick="sendJMHZ();">提交</button></div></div></form>';
  $('#mask').addClass('viewed');
  $('#layer').html(str).fadeIn().addClass('JHMZLayer');
}

/**
 * 留言咨询
 * @return {[type]} [description]
 */
function showLayerFeedback(id=0){
  getSite();
  //productLists(id);
  var str = '<form action="javascript:void(0);" id="feedbackForm" novalidate="novalidate"><div class="banner" style="background:url(\'/statics/images/web/layer_contact_banner.jpg\') top left / cover no-repeat;"></div>';
      str += '<div class="con row">';
      str += '<div class="col-md-6 intro"><div class="desc">我们期待与您交流机器人和智能装备产业相关领域的技术成果，实现发展共赢。</div><p>我们的联系电话</p><div class="val tel">0571-56757613<br>0571-56757600转8002</div><p>我们的邮件地址</p><div class="val email">zymponye@126.com</div></div>';
      //str += '<div class="col-md-6"><div class="form"><div class="label"><img src="/statics/images/web/form-icon-1.png"><select name="dataid" class="product_sel"><option>=请选择您感兴趣的项目=</option></select></div><div class="label"><img src="/statics/images/web/form-icon-2.png"><input type="text" name="name" placeholder="您的姓名（必填）"></div><div class="label"><img src="/statics/images/web/form-icon-3.png"><input type="text" name="mobile" placeholder="您的手机号（必填）"></div><div class="label"><img src="/statics/images/web/form-icon-4.png"><input type="text" name="company" placeholder="您的公司"></div><div class="label"><img src="/statics/images/web/form-icon-5.png"><textarea name="remark" placeholder="您的留言"></textarea></div></div></div>';
      str += '<div class="col-md-6"><div class="form"><div class="label"><img src="/statics/images/web/form-icon-1.png"><select name="dataid" class="product_sel"><option value="">=请选择你的项目=</option><option value="机器视觉检测系统">机器视觉检测系统</option><option value="服务机器人">服务机器人</option><option value="智能无人叉车">智能无人叉车</option><option value="agv小车">agv小车</option><option value="巡检机器人">巡检机器人</option><option value="其他机器人">其他机器人</option></select></div><div class="label"><img src="/statics/images/web/form-icon-2.png"><input type="text" name="name" placeholder="您的姓名（必填）"></div><div class="label"><img src="/statics/images/web/form-icon-3.png"><input type="text" name="mobile" placeholder="您的手机号（必填）"></div><div class="label"><img src="/statics/images/web/form-icon-4.png"><input type="text" name="company" placeholder="您的公司"></div><div class="label"><img src="/statics/images/web/form-icon-5.png"><textarea name="remark" placeholder="您的留言"></textarea></div></div></div>';
	  str += '</div>';
      str += '<input type="hidden" name="module" value="product">';
      str += '<div class="bot row"><div class="col-sm-6"><a href="/product.html" class="blue">->前去了解我们的产品</a></div><div class="col-sm-6" style="text-align:right;"><button class="btn btn-sm"  onclick="sendFeedbackFromLayer();">发送</button></div></div></form>';
  $('#mask').addClass('viewed');
  $('#layer').html(str).fadeIn().addClass('feedbackLayer');
}

function closeLayer(){
  $('#mask').removeClass('viewed');
  $('#layer').fadeOut(100);
  setTimeout(function(){
	$('#layer').empty().removeClass();
  },300);
}

/**
 * 产品列表
 * @return {[type]} [description]
 */
function productLists(id=0){
  let html = '';
  $('.product_sel').html('<option value="0">=请选择=</select>');
  $.getJSON('/index.php?m=product&c=api&a=lists',function(res){
    if(res.state=='1'){
      $.each(res.data,function(k,v){
        var sel = id == v.id ? 'selected' : '';
        html += '<option value="'+v.id+'"  '+sel+'>'+v.title+'</option>';
      });
      $('.product_sel').append(html);
    }else{
      console.log(res.msg);
    }
  });
}

/**
 * 获得站点信息
 * @return {[type]} [description]
 */
function getSite(){
  $.getJSON('/index.php?m=content&c=api&a=site',function(res){
    if(res.state=='1'){
      $('.feedbackLayer email').text(res.data.sale_email);
      $('.feedbackLayer tel').text(res.data.sale_tel);
      $('.telLayer .sale_tel').text(res.data.sale_tel).attr('href','tel:'+res.data.sale_tel);
      // $('.telLayer .main_tel').text(res.data.tel).attr('href','tel:'+res.data.tel);
    }
  });
}

/**
 * 提交留言咨询信息（弹出层）
 * @return {[type]} [description]
 */
function sendFeedbackFromLayer(){
  $('#feedbackForm').validate({
    errorElement: 'span', //default input error message container
    errorClass: 'help-block', // default input error message class
    focusInvalid: false, // do not focus the last invalid input
    rules: {
    	product:{
    		required: true
    	},
        name: {
            required: true
        },
        mobile: {
            required: true
        }
    },
    messages: {
    	product: {
            required: "请选择咨询项目"
        },
        name: {
            required: "姓名必填"
        },
        mobile: {
            required: "手机号必填"
        }
    },

    invalidHandler: function(event, validator) {
      // $('.alert-danger', $('#zixun')).show();
    },

    highlight: function(element) {
        $(element).closest('.label').addClass('has-error'); // set error class to the control group
    },

    success: function(label) {
        label.closest('.label').removeClass('has-error');
        label.remove();
    },

    // errorPlacement: function(error, element) {
    //     error.insertAfter(element.closest('.input-icon'));
    // },
    submitHandler: function(form) {
      // form validation success, call ajax form submit
      var data = $('#feedbackForm').serialize();
      $.getJSON('/index.php?m=feedback&c=api&a=submit&type=1&'+data,function(res){
        if(res.state=='1'){
          alert(res.msg);
          closeLayer();
        }else{
          alert(res.msg);
        }
      });
      //form.submit(); 
    }
  });

  $('#feedbackLayer input').keypress(function(e) {
    if (e.which == 13) {
      if ($('#feedbackForm').validate().form()) {
          $('#feedbackForm').submit(); //form validation success, call ajax form submit
      }
      return false;
    }
  });
}

/**
 * 首页咨询
 * @return {[type]} [description]
 */
function sendIndex(){
  $('#zixunIndex').validate({
    errorElement: 'span', //default input error message container
    errorClass: 'help-block', // default input error message class
    focusInvalid: false, // do not focus the last invalid input
    rules: {
    	product:{
    		required: true
    	},
        name: {
            required: true
        },
        mobile: {
            required: true
        }
    },
    messages: {
    	product: {
            required: "请选择咨询项目"
        },
        name: {
            required: "姓名必填"
        },
        mobile: {
            required: "手机号必填"
        }
    },

    invalidHandler: function(event, validator) {
      // $('.alert-danger', $('#zixun')).show();
    },

    highlight: function(element) {
        $(element).closest('.label').addClass('has-error'); // set error class to the control group
    },

    success: function(label) {
        label.closest('.label').removeClass('has-error');
        label.remove();
    },

    // errorPlacement: function(error, element) {
    //     error.insertAfter(element.closest('.input-icon'));
    // },
    submitHandler: function(form) {
      // form validation success, call ajax form submit
      var data = $('#zixunIndex').serialize();
      $.getJSON('/index.php?m=feedback&c=api&a=submit&'+data,function(res){
        if(res.state=='1'){
          alert(res.msg);
          closeLayer();
        }else{
          alert(res.msg);
        }
      });
      //form.submit(); 
    }
  });

  $('#zixunIndex input').keypress(function(e) {
    if (e.which == 13) {
      if ($('#zixunIndex').validate().form()) {
          $('#zixunIndex').submit(); //form validation success, call ajax form submit
      }
      return false;
    }
  });
}

/**
 * 提交加盟合作信息
 * @return {[type]} [description]
 */
function sendJMHZ(){
  $('#JMHZForm').validate({
    errorElement: 'span', //default input error message container
    errorClass: 'help-block', // default input error message class
    focusInvalid: false, // do not focus the last invalid input
    rules: {
      company:{
        required: true
      },
      name: {
          required: true
      },
      mobile: {
          required: true
      }
    },
    messages: {
      company:{
        required: "请填写公司名称"
      },
      name: {
          required: "请填写姓名"
      },
      mobile: {
          required: "请填写手机号码"
      }
    },

    invalidHandler: function(event, validator) {
      // $('.alert-danger', $('#zixun')).show();
    },

    highlight: function(element) {
        $(element).closest('.label').addClass('has-error'); // set error class to the control group
    },

    success: function(label) {
        label.closest('.label').removeClass('has-error');
        label.remove();
    },

    // errorPlacement: function(error, element) {
    //     error.insertAfter(element.closest('.input-icon'));
    // },
    submitHandler: function(form) {
      // form validation success, call ajax form submit
      var data = $('#JMHZForm').serialize();
      $.getJSON('/index.php?m=feedback&c=api&a=submit&type=2&'+data,function(res){
        if(res.state=='1'){
          alert(res.msg);
          closeLayer();
        }else{
          alert(res.msg);
        }
      });
      //form.submit(); 
    }
  });

  $('#JMHZForm input').keypress(function(e) {
    if (e.which == 13) {
      if ($('#JMHZForm').validate().form()) {
          $('#JMHZForm').submit(); //form validation success, call ajax form submit
      }
      return false;
    }
  });
}


function sendFeedback(){
  $('#feedback').validate({
    errorElement: 'span', //default input error message container
    errorClass: 'help-block', // default input error message class
    focusInvalid: false, // do not focus the last invalid input
    rules: {
      company:{
        required: true
      },
      name: {
          required: true
      },
      mobile: {
          required: true
      }
    },
    messages: {
      company:{
		required: "请填写公司名称"
      },
      name: {
          required: "请填写姓名"
      },
      mobile: {
          required: "请填写手机号码"
      }
    },

    invalidHandler: function(event, validator) {
      // $('.alert-danger', $('#zixun')).show();
    },

    highlight: function(element) {
        $(element).closest('.label').addClass('has-error'); // set error class to the control group
    },

    success: function(label) {
        label.closest('.label').removeClass('has-error');
        label.remove();
    },

    // errorPlacement: function(error, element) {
    //     error.insertAfter(element.closest('.input-icon'));
    // },
    submitHandler: function(form) {
      // form validation success, call ajax form submit
      var data = $('#feedback').serialize();
      $.getJSON('/index.php?m=feedback&c=api&a=submit&'+data,function(res){
        if(res.state=='1'){
          alert(res.msg);
          closeLayer();
        }else{
          alert(res.msg);
        }
      });
      //form.submit(); 
    }
  });

  $('#JMHZForm input').keypress(function(e) {
    if (e.which == 13) {
      if ($('#JMHZForm').validate().form()) {
          $('#JMHZForm').submit(); //form validation success, call ajax form submit
      }
      return false;
    }
  });
}

/**
 * 打开百度商桥
 * @return {[type]} [description]
 */
function showShangQiao(){
  console.log('百度商桥:'+$('#nb_invite_ok').length);
  if ($('#nb_invite_ok').length > 0) {
    $('#nb_invite_ok').click();
  }
}

/**
 * 打开电话弹窗
 * @return {[type]} [description]
 */
function showLayerTel(){
  //getSite();
  var str = '';
      str += '<div class="con row">';
      str += '<div class="col-12"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-tel"></use></svg><p>企业电话：<a href="tel:0571-56757613">0571-56757613</a></p><p>市&nbsp;&nbsp;场&nbsp;&nbsp;部：<a href="tel:18906719937">18906719937</a></p></div>';
      str += '</div>';
  $('#mask').addClass('viewed');
  $('#layer').html(str).fadeIn().addClass('telLayer');
}