var schelduleForm = (function () {
  'use strict';
  var SchelduleForm = function (params) {
    var p = this;
    p.params = {
      appid: '',
      accountsId: '',
      cfApp: null,
      devMode: false,
      dataApi: G.baseUri() + '/mobile/auth/demand/getdemand',
      postApi: G.baseUri() + '/mobile/auth/demand/updatedetailsinfo',
      changeApi: G.baseUri() + '/mobile/auth/demand/getmeetingclosetime',
      vt: ''
    };

    for (var param in params) {
      p.params[param] = params[param];
    }
    var cfApp = p.params.cfApp;

    if (p.params.devMode) {
      p.params.dataApi = 'json/my-scheldule-form.json';
      p.params.postApi = 'json/code.json';
      p.params.changeApi = 'json/code.json';


    }

    p.english = cfApp.getQueryString('english') == 1 ? true : false;
    console.log(p.english);



    p.submitHotel = '';
    p.submitAddress = '';
    p.submitRelayType = '';
    p.submitRelayStation = '';
    p.submitSendType = '';
    p.submitSendStation = '';


    p.changeRelay = false;
    p.changeSend = false;

    p.changeRelayType = '';
    p.changeSendType = '';

    p.relayStartTime = '';
    p.relayEndTime = '';

    var oneDay = 24 * 60 * 60 * 1000;


    /**
     * 判断app字段
     * @returns 是否app有值
     */
    var validAppField = function () {
      if (!p.params.appid || p.params.appid == '') {
        return false;
      } else {
        return true;
      }
    };

    /**
     * 确认初始化的app 和tokenId 两个值是否都存在
     * 如果不存在则获取一次,获取不到则初始化失败
     * @returns 初始化基础字段是否成功
     */
    var initBaseFields = function () {
      if (!validAppField()) {
        p.params.appid = cfApp.getQueryString('appid');
        //p.params.accountsId = cfApp.getQueryString('accountsId');
      }



      //如果获取不到app和tokenId,则直接从传入的CfApp中获取值
      if (!validAppField()) {
        if (p.params.cfApp) {
          p.params.appid = cfApp.getAppId();
          //p.params.tokenId = cfApp.getTokenId();
        }
      }
      p.empInfo = cfApp.getMpInfo();
      p.params.accountsId = p.empInfo.accountsId;
      return validAppField();
    };

    /**
     * 初始化组件
     * @returns {boolean}
     */


    p.init = function () {



      if (initBaseFields()) {
        var sideDiv = new side({
          currentIndex: '9',
          cfApp: cfApp

        });
        sideDiv.init();
        log();
        loadData();
        accordion();
        cardCtrl();
        chooseEvent();
        submit();

        $('.language').click(function () {
          if (!p.english) {
            location.href = 'my-schedule-form-english.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id') + '&english=1';
          } else {
            location.href = 'my-schedule-form.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id');
          }

        });
        return true;
      } else {
        return false;
      }
    };
    var log = function () {

      var formdata = {
        openid: p.empInfo.openId,
        module: "研讨会",
        modulename: "我的行程",
        keyword: "我的行程",
        keywordid: '',
        vt: new Date().getTime(),
        appid: cfApp.getQueryString('appid'),
        url: location.href
      };
      G.ajax(G.devModePost, '/schaeffler/mobile/testAsync/doLOg', formdata, function (retdata) {


      });
    }

    var loadData = function () {
      if(p.english){
        $.showLoading("Loading");
      }else{
        $.showLoading();
      }

      var formdata = {
        meetingId: cfApp.getQueryString('id'),
        member_uid: p.empInfo.memberId
      };
      G.ajax('get', p.params.dataApi, formdata, function (retdata) {
        $.hideLoading();
        if (retdata.errorNo == '0') {
          var detailsinfo = retdata.detailsinfo;
          var service = retdata.service;
          //选项
          service = JSON.parse(service);
          console.log(service)
          if(service.isHotel=="0"){
            service.hotel = JSON.parse(service.hotel);
          }
          if(service.isEat=="0"){
            service.eat = JSON.parse(service.eat);
          }
          if(service.isRelay=="0"){
            service.relay = JSON.parse(service.relay);
          }
          if(service.isTake=="0"){
            service.take = JSON.parse(service.take);
          }
          if(service.isfactory=="0"){
            service.factory = JSON.parse(service.factory);
          }
          p.relayStartTime = dataUtils.dateFormat(new Date(retdata.startTime), 'yyyy-MM-dd');
          p.relayEndTime = dataUtils.dateFormat(new Date(retdata.endTime), 'yyyy-MM-dd');
          console.log(p.relayStartTime, p.relayEndTime);
          //酒店
          if (service.isHotel == 0) {
            service.isHotel = true;
            var allHotels = []; //酒店名称
            var enAllHotels = []; //英文酒店名称
            var allHotelsAddress = []; //酒店地址
            var enAllHotelsAddress = []; //英文酒店地址

            var timeArr = []; //入住退房时间
            for (var i = 0, j = service.hotel.length; i < j; i++) {
              allHotels.push(service.hotel[i].title);
              enAllHotels.push(service.hotel[i].titleEn);
              allHotelsAddress.push(service.hotel[i].hoteladrress);
              enAllHotelsAddress.push(service.hotel[i].hoteladrressEn);
              var obj = new Object;
              obj.startDate = service.hotel[i].startDate;
              obj.endDate = service.hotel[i].endDate;
              timeArr.push(obj);
            }
            console.log(allHotels, enAllHotels, timeArr);
          } else {
            service.isHotel = false;
          }
          //餐饮           
          service.isEat = service.isEat == 0 ? true : false;
          if(service.isEat){
            var allEat = [];
            for (var i = 0, j = service.eat.length; i < j; i++) {
              allEat.push(service.eat[i].eatname);
            }
          }

          //接送服务
          if (service.isRelay == 0) {
            service.isRelay = true;
            var relay = service.relay;
            var allRelay = []; //所有交通方式
            var enAllRelay = []; //英文交通方式
            var highStation = []; //高铁站点
            var enHighStation = []; //英文高铁站点

            var planeStation = []; //飞机站点
            var enPlaneStation = []; //英文飞机站点

            if (relay.isHigh == 0) {
              allRelay.push('高铁');
              enAllRelay.push('Train');
              var high = relay.high;
              for (var i = 0, j = high.length; i < j; i++) {
                highStation.push(high[i].highsattion);
                enHighStation.push(high[i].highsattionEn);

              }
              console.log(highStation, enHighStation);
            }
            if (relay.isPlane == 0) {
              allRelay.push('飞机');
              enAllRelay.push('Flight');
              var plane = relay.plane;
              for (var i = 0, j = plane.length; i < j; i++) {
                planeStation.push(plane[i].planesattion);
                enPlaneStation.push(plane[i].planesattionEn);

              }
              console.log(planeStation, enPlaneStation);
            }
            if (relay.isOnedrive == 0) {
              allRelay.push('自驾');
              enAllRelay.push('Self-driving');
            }
            if (relay.isOther == 0) {
              allRelay.push('其他');
              enAllRelay.push('Others');

            }
            console.log(allRelay);
          } else {
            service.isRelay = false;
          }
          //试驾
          service.isTake = service.isTake == 0 ? true : false;
          var allTake = [];
          var allTakeDesc = [];
          if(service.isTake){
              for (var i = 0, j = service.take.length; i < j; i++) {
                  allTake.push(service.take[i].taketime);
                  allTakeDesc.push(service.take[i].take_des);
              }
          }

          //工厂
          service.isfactory = service.isfactory == 0 ? true : false;
          var allfactory = [];

          var allFactoryDesc=[];
          if(service.isfactory){
              for (var i = 0, j = service.factory.length; i < j; i++) {
                  allfactory.push(service.factory[i].visittime);
                  allFactoryDesc.push(service.factory[i].des);
              }
          }

          //retdata.detailsinfo = detailsinfo;
          retdata.service = service;


          //已填写过的信息
          if (detailsinfo && detailsinfo != '') {
            console.log('修改');
            detailsinfo = JSON.parse(detailsinfo);


            //酒店
            if (detailsinfo.isHotel == 0) {
              detailsinfo.isHotel = true
              detailsinfo.hotel = JSON.parse(detailsinfo.hotel);
              // var hotel = detailsinfo.hotel;
              // $(".items>div[data-target='one'] .checkbox").addClass('choose');
              // $('#hotel').val(hotel.title);
              // var index = allHotels.indexOf(hotel.title);
              // console.log(index);
              // $('#address').text(allHotelsAddress[index]);
              // $('#startTime').val(hotel.startDate);
              // $('#endTime').val(hotel.endDate);
              var hotelTitle = detailsinfo.hotel.title;
              var index = allHotels.indexOf(hotelTitle);
              detailsinfo.hotel.address = allHotelsAddress[index];
              if (p.english) {
                var hotelTitle = detailsinfo.hotel.title;
                var index = allHotels.indexOf(hotelTitle);
                detailsinfo.hotel.titleEn = enAllHotels[index];
                detailsinfo.hotel.addressEn = enAllHotelsAddress[index];
              }
            } else {
              detailsinfo.isHotel = false;
            }

            //接送服务
            if (detailsinfo.isRelay == 0) {
              detailsinfo.isRelay = true;
              //$(".items>div[data-target='three'] .checkbox").addClass('choose');
              detailsinfo.relay = JSON.parse(detailsinfo.relay);
              var relay = detailsinfo.relay;
              detailsinfo.send = JSON.parse(detailsinfo.send);
              var send = detailsinfo.send;
              //接机
              if (relay.isHigh == 0) {
                //$('#relay').val('高铁');
                relay.Transportation = '高铁';
                relay.Station = relay.high.highsattion;
                p.submitRelayStation = relay.Station;
                p.changeRelay = true;
                p.changeRelayType = 'T';

                if (p.english) {
                  relay.TransportationEn = 'Train';
                  var index = highStation.indexOf(relay.Station);
                  relay.StationEn = enHighStation[index];
                  p.submitRelayStation = relay.StationEn
                }
              }
              if (relay.isPlane == 0) {
                //$('#relay').val('飞机');
                relay.Transportation = '飞机';
                relay.Station = relay.plane.planesattion;
                p.submitRelayStation = relay.Station;
                console.log(p.submitRelayStation)
                p.changeRelay = true;
                p.changeRelayType = 'P';
                if (p.english) {
                  relay.TransportationEn = 'Flight';
                  var index = planeStation.indexOf(relay.Station);
                  relay.StationEn = enPlaneStation[index];
                  p.submitRelayStation = relay.StationEn


                }

              }
              if (relay.isOnedrive == 0) {
                //$('#relay').val('自驾');
                relay.Transportation = '自驾';
                if (p.english) {
                  relay.TransportationEn = 'Self-driving';
                }
                $("#relayStation").html('').hide();
                $('#relayClass').parents('li').hide();

              }
              if (relay.isOther == 0) {
                //$('#relay').val('其他');
                relay.Transportation = '其他';
                if (p.english) {
                  relay.TransportationEn = 'Others';
                }
                $("#relayStation").html('').hide();
                $('#relayClass').parents('li').hide();

              }
              //送机
              if (send.isHigh == 0) {
                //$('#send').val('高铁');

                send.Transportation = '高铁';
                send.Station = send.high.highsattion;
                p.submitSendStation = send.Station;
                p.changeSend = true;
                p.changeSendType = 'T';
                if (p.english) {
                  send.Transportation = 'Train';
                  var index = highStation.indexOf(send.Station);
                  send.StationEn = enHighStation[index];
                  p.submitSendStation = send.StationEn;
                }

              }
              if (send.isPlane == 0) {
                //$('#send').val('飞机');

                send.Transportation = '飞机';
                send.Station = send.plane.planesattion;
                p.submitSendStation = send.Station;
                p.changeSend = true;
                p.changeSendType = 'T';
                if (p.english) {
                  send.TransportationEn = 'Flight';
                  var index = planeStation.indexOf(send.Station);
                  send.StationEn = enPlaneStation[index];
                  p.submitSendStation = send.StationEn;
                }

              }
              if (send.isOnedrive == 0) {
                //$('#send').val('自驾');
                send.Transportation = '自驾';
                if (p.english) {
                  send.TransportationEn = 'Self-driving';
                }
                $("#sendStation").html('').hide();
                $('#sendClass').parents('li').hide();

              }
              if (send.isOther == 0) {
                //$('#send').val('其他');

                send.Transportation = '其他';
                if (p.english) {
                  send.TransportationEn = 'Others';
                }
                $("#sendStation").html('').hide();
                $('#sendClass').parents('li').hide();

              }
            } else {
              detailsinfo.isRelay = false;
            }

            //填充页面初始化
            retdata.detailsinfo = detailsinfo;
            console.log(retdata);

            // if (detailsinfo.desc && detailsinfo.desc != '') {
            //   $('#content').val(detailsinfo.desc);
            // }
            // console.log(detailsinfo);




          }


          var content = $('#template').html();
          p.template = Handlebars.compile(content);
          var htmlStr = p.template(retdata);
          $('.content').append(htmlStr);
          if (service.isHotel) {
            hotelInit(allHotels, allHotelsAddress, enAllHotels, enAllHotelsAddress, timeArr);
          }
          if (service.isRelay) {
            relayInit(allRelay, highStation, planeStation, enAllRelay, enHighStation, enPlaneStation);
          }
          //如果有填写过站点信息的初始化
          if (p.changeRelay) {
            if (p.changeRelayType == "T") {
              if (p.english) {
                $("#relayStation input").picker({
                  title: "",
                  cols: [{
                    textAlign: 'center',
                    values: enHighStation
                  }],
                  onClose: function () {
                    var value = $('#relayStation input').val();
                    var index = highStation.indexOf(value);
                    p.submitRelayStation = enHighStation[index];
                  }
                });
              } else {
                $("#relayStation input").picker({
                  title: "",
                  cols: [{
                    textAlign: 'center',
                    values: highStation
                  }],
                  onClose: function () {
                    p.submitRelayStation = $('#relayStation input').val();
                  }
                });
              }
            } else if (p.changeRelayType == 'P') {
              if (p.english) {
                $("#relayStation input").picker({
                  title: "",
                  cols: [{
                    textAlign: 'center',
                    values: enPlaneStation
                  }],
                  onClose: function () {
                    var value = $('#relayStation input').val();
                    var index = planeStation.indexOf(value);
                    p.submitRelayStation = enPlaneStation[index];
                  }
                });
              } else {
                $("#relayStation input").picker({
                  title: "",
                  cols: [{
                    textAlign: 'center',
                    values: planeStation
                  }],
                  onClose: function () {
                    p.submitRelayStation = $('#relayStation input').val();

                  }
                });
              }
            }
          }


          if (p.changeSend) {
            if (p.changeSendType == "T") {
              if (p.english) {
                $("#sendStation input").picker({
                  title: "",
                  cols: [{
                    textAlign: 'center',
                    values: enHighStation
                  }],
                  onClose: function () {
                    var value = $('#sendStation input').val();
                    var index = highStation.indexOf(value);
                    p.submitSendStation = enHighStation[index];
                  }
                });
              } else {
                $("#sendStation input").picker({
                  title: "",
                  cols: [{
                    textAlign: 'center',
                    values: highStation
                  }],
                  onClose: function () {
                    p.submitSendStation = $('#sendStation input').val();

                  }
                });
              }
            } else if (p.changeSendType == 'P') {
              if (p.english) {
                $("#sendStation input").picker({
                  title: "",
                  cols: [{
                    textAlign: 'center',
                    values: enPlaneStation
                  }],
                  onClose: function () {
                    var value = $('#sendStation input').val();
                    var index = planeStation.indexOf(value);
                    p.submitSendStation = enPlaneStation[index];
                  }
                });
              } else {
                $("#sendStation input").picker({
                  title: "",
                  cols: [{
                    textAlign: 'center',
                    values: planeStation
                  }],
                  onClose: function () {
                    p.submitSendStation = $('#sendStation input').val();

                  }
                });
              }
            }





          }

          if (detailsinfo && detailsinfo != '') {


            //如果已填写过信息，接送服务是自驾或其他，隐藏站点时间班次

            if(detailsinfo.isRelay){
              if (relay.isOnedrive==0 || relay.isOther==0) {
                $("#relayStation").html('').hide();
                $('#relayClass').parents('li').hide();
                $('#relayTime').parents('li').hide();
              }
              if (send.isOnedrive==0 || send.isOther==0) {
                $("#sendStation").html('').hide();
                $('#sendClass').parents('li').hide();
                $('#sendTime').parents('li').hide();
              }

            }
           
            //餐饮
            if (detailsinfo.isEat == 0) {
              detailsinfo.isEat = true;
              $('div.align-center[data-target="two"]').find('.checkbox').addClass('choose');
              detailsinfo.eat = JSON.parse(detailsinfo.eat);
              var eat = detailsinfo.eat;
              //$(".items>div[data-target='two'] .checkbox").addClass('choose');
              for (var i = 0, j = eat.length; i < j; i++) {
                var index = allEat.indexOf(eat[i].eatname);
                $('#two li:eq(' + (index + 1) + ') .checkbox').addClass('choose')
              }
            } else {
              detailsinfo.isEat = false;
              $('#two').addClass('display');
            }
            //试驾
            var taketime = null;
            if (detailsinfo.isTake == 0) {
              detailsinfo.isTake = true;
              $('div.align-center[data-target="four"]').find('.checkbox').addClass('choose');
              detailsinfo.take = JSON.parse(detailsinfo.take);
              var take = detailsinfo.take;
              //$(".items>div[data-target='four'] .checkbox").addClass('choose');
                for (var i = 0, j = take.length; i < j; i++) {
                  taketime = take[i].taketime;
                var index = allTake.indexOf(take[i].taketime);
                $('#four li:eq(' + (index + 1) + ') .checkbox').addClass('choose')
              }

              for(var i =0; i <$('#five li:first-child~li').find('p').length;i++){
                if($($('#five li:first-child~li').find('p')[i]).html() == taketime){
                  $($('#five li:first-child~li').find('p')[i]).parent().find('.checkbox').removeClass("choose");
                  $($('#five li:first-child~li').find('p')[i]).parent().css('display','none');
                  i = i+1;
                }
              }
            } else {
              detailsinfo.isTake = false;
              $('#four').addClass('display');
            }
            //工厂
            if (detailsinfo.isfactory == 0) {
              detailsinfo.isfactory = true;
              $('div.align-center[data-target="five"]').find('.checkbox').addClass('choose');
              detailsinfo.factory = JSON.parse(detailsinfo.factory);
              var factory = detailsinfo.factory;
              //$(".items>div[data-target='five'] .checkbox").addClass('choose');
              for (var i = 0, j = factory.length; i < j; i++) {
                var index = allfactory.indexOf(factory[i].visittime);
                //判断试乘试驾选中的日期
                if(index>-1){

                  index=allFactoryDesc.indexOf(factory[i].visitdesc);
                  $('#five li:eq(' + (index + 1) + ') .checkbox').addClass('choose');
                }

              }
              for(var i =0; i <$('#five li:first-child~li').find('p').length;i++){
                if($($('#five li:first-child~li').find('p')[i]).html() == taketime){
                  $($('#five li:first-child~li').find('p')[i]).parent().find('.checkbox').removeClass("choose");
                  $($('#five li:first-child~li').find('p')[i]).parent().css('display','none');
                  i = i+1;
                }
              }
            } else {
              detailsinfo.isfactory = false;
              $('#five').addClass('display');
            }

            /**
             * 初始化提交参数
             */
            initSubmitParams(detailsinfo);
          }


          else{

            $('div.align-center').each(function() {

              $(this).find('.checkbox').addClass('choose');
              var target=$(this).attr('data-target');
              if(target=='three'){

                $('#three1').removeClass('display');
                $('#three2').removeClass('display');
              }else{
                $('#'+target).removeClass('display');

              }

            })




          }

        }
      });
    }


    var initSubmitParams = function (detailsinfo) {
      /**
       * 初始化提交参数
       */
      if (detailsinfo.isHotel) {
        p.submitHotel = detailsinfo.hotel.title;
        p.submitAddress = detailsinfo.hotel.addressEn;
      }else{
        $("div[data-target='one'] span").removeClass("choose");
        $("#one").addClass('display');
      }
      //接送服务
      if (detailsinfo.isRelay) {
        var relay = detailsinfo.relay;
        var send = detailsinfo.send;
        //接机
        if (relay.isHigh == 0) {
          p.submitRelayType = "高铁";
          p.submitRelayStation = relay.high.highsattion;
        }
        if (relay.isPlane == 0) {
          p.submitRelayType = "飞机";
          p.submitRelayStation = relay.plane.planesattion;
        }
        if (relay.isOnedrive == 0) {
          p.submitRelayType = "自驾";
        }
        if (relay.isOther == 0) {
          p.submitRelayType = "其他";
        }
        if (send.isHigh == 0) {
          p.submitSendType = "高铁";
          p.submitSendStation = send.high.highsattion;
        }
        if (send.isPlane == 0) {
          p.submitSendType = "飞机";
          p.submitSendStation = send.plane.planesattion;
        }
        if (send.isOnedrive == 0) {
          p.submitSendType = "自驾";
        }
        if (send.isOther == 0) {
          p.submitSendType = "其他";
        }
      }
    }

    var hotelInit = function (hotel, address, enHotel, enAddress, time) {
      var pickerHotel = [];
      var pickAddress = [];
      if (p.english) {
        pickerHotel = enHotel;
        pickAddress = enAddress;

      } else {
        pickerHotel = hotel;
        pickAddress = address;

      }
      //选择酒店
      $("#hotel").picker({
        title: "",
        cols: [{
          textAlign: 'center',
          values: pickerHotel
        }],
        onClose: function () {
          var value = $('#hotel').val();
          var index = pickerHotel.indexOf(value);
          var startTime = time[index].startDate;
          var endTime = time[index].endDate;

          console.log(index, startTime, endTime);
          $('#address').text(pickAddress[index]);
          p.submitHotel = value;
          p.submitAddress = pickAddress[index];
          if (p.english) {
            p.submitHotel = hotel[index];
            p.submitAddress = address[index];
          }
          console.log('submitHotel:' + p.submitHotel);
          console.log('submitAddress:' + p.submitAddress);


          $("#startTime").parents('li').html('<span>入住时间：</span><input type="text" class="flex-1 f14" id="startTime" value="">');
          // $("#startTime").calendar({
          //   dateFormat: 'yyyy-mm-dd',
          //   monthNames: ['1111', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
          //   dayNamesShort: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
          // });

          //入住时间退房时间  


          var prevStartDay = dataUtils.dateFormat(new Date((new Date(startTime).getTime() - oneDay)), 'yyyy-MM-dd'); //进店时间前一天
          var prevCheckedDay = dataUtils.dateFormat(new Date((new Date(startTime).getTime())), 'yyyy-MM-dd'); //默认选中时间
          var prevEndDay = dataUtils.dateFormat(new Date((new Date(endTime).getTime())), 'yyyy-MM-dd'); //离店时间前一天

          if (p.english) {
            $("#startTime").parents('li').html('<span>Check in：</span><input type="text" class="flex-1 f14" id="startTime" value="">');
            $("#endTime").parents('li').html('<span>Check out：</span><input type="text" class="flex-1 f14" id="endTime" value="">');

            $("#startTime").calendar({
              dateFormat: 'yyyy-mm-dd',
              monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
              dayNamesShort: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
              minDate: prevStartDay,
              maxDate: prevEndDay,
              value: [prevCheckedDay]
            });
            $("#endTime").calendar({
              dateFormat: 'yyyy-mm-dd',
              monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
              dayNamesShort: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
              minDate: prevStartDay,
              maxDate: endTime,
              value: [prevCheckedDay]
            });
          } else {
            $("#startTime").parents('li').html('<span>入住时间：</span><input type="text" class="flex-1 f14" id="startTime" value="">');
            $("#endTime").parents('li').html('<span>退房时间：</span><input type="text" class="flex-1 f14" id="endTime" value="">');
            $("#startTime").calendar({
              dateFormat: 'yyyy-mm-dd',
              minDate: prevStartDay,
              maxDate: prevEndDay,
              value: [prevCheckedDay]

            });
            $("#endTime").calendar({
              dateFormat: 'yyyy-mm-dd',
              minDate: prevStartDay,
              maxDate: endTime,
              value: [prevCheckedDay]
            });
          }




        }
      });
      //入住时间退房时间
      var startTimeInit;
      var endTimeInit;

      for(var i=0;i<hotel.length;i++){
        if(p.submitHotel=hotel[i]){
          startTimeInit = time[i].startDate;
          endTimeInit = time[i].endDate;
        }
      }
      var prevStartDayInit = dataUtils.dateFormat(new Date((new Date(startTimeInit).getTime() - oneDay)), 'yyyy-MM-dd'); //进店时间前一天
      var prevEndDayInit = dataUtils.dateFormat(new Date((new Date(endTimeInit).getTime())), 'yyyy-MM-dd'); //离店时间前一天
      if (p.english) {
        $("#startTime").calendar({
          dateFormat: 'yyyy-mm-dd',
          monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
          dayNamesShort: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
          minDate: prevStartDayInit,
          maxDate: prevEndDayInit
        });
        $("#endTime").calendar({
          dateFormat: 'yyyy-mm-dd',
          monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
          dayNamesShort: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
          minDate: prevStartDayInit,
          maxDate: prevEndDayInit
        });
      } else {
        $("#startTime").calendar({
          dateFormat: 'yyyy-mm-dd',
          minDate: prevStartDayInit,
          maxDate: prevEndDayInit
        });
        $("#endTime").calendar({
          dateFormat: 'yyyy-mm-dd',
          minDate: prevStartDayInit,
          maxDate: prevEndDayInit
        });
      }

    }

    //接送服务
    var relayInit = function (allRelay, higesta, planesta, enAll, enHigh, enPlane) {

      if (p.english) {
        var all = enAll;

      } else {
        var all = allRelay;
      }
      //接站
      $("#relay").picker({
        title: "",
        cols: [{
          textAlign: 'center',
          values: all
        }],
        onClose: function () {
          var value = $('#relay').val();
          if (value == '高铁' || value == 'Train') {
            p.submitRelayType = '高铁';
            // $('#relayStation').parents('li').show();
            $('#relayClass').parents('li').show();
            $('#relayTime').parents('li').show();

            if (p.english) {
              $("#relayStation").html('<span>Arrival station：</span><input type="text" class="flex-1 f14" >').show();
              $("#relayStation input").picker({
                title: "",
                cols: [{
                  textAlign: 'center',
                  values: enHigh
                }],
                onClose: function () {
                  var value = $('#relayStation input').val();
                  var index = enHigh.indexOf(value);
                  p.submitRelayStation = higesta[index];
                }
              });
            } else {
              $("#relayStation").html('<span>到达站点：</span><input type="text" class="flex-1 f14" >').show();
              $("#relayStation input").picker({
                title: "",
                cols: [{
                  textAlign: 'center',
                  values: higesta
                }],
                onClose: function () {

                  p.submitRelayStation = $('#relayStation input').val();
                }
              });
            }

          } else if (value == '飞机' || value == 'Flight') {

            p.submitRelayType = '飞机';
            $('#relayClass').parents('li').show();
            $('#relayTime').parents('li').show();

            if (p.english) {
              $("#relayStation").html('<span>Arrival station：</span><input type="text" class="flex-1 f14" >').show();
              $("#relayStation input").picker({
                title: "",
                cols: [{
                  textAlign: 'center',
                  values: enPlane
                }],
                onClose: function () {
                  var value = $('#relayStation input').val();
                  var index = enPlane.indexOf(value);
                  p.submitRelayStation = planesta[index];
                }
              });
            } else {
              $("#relayStation").html('<span>到达站点：</span><input type="text" class="flex-1 f14" >').show();
              $("#relayStation input").picker({
                title: "",
                cols: [{
                  textAlign: 'center',
                  values: planesta
                }],
                onClose: function () {

                  p.submitRelayStation = $('#relayStation input').val();
                }
              });
            }

          } else if (value == '自驾' || value == 'Self-driving') {
            p.submitRelayType = '自驾';
            p.submitRelayStation = '';

            $("#relayStation").html('').hide();
            $('#relayClass').parents('li').hide();
            $('#relayTime').parents('li').hide();

          } else if (value == '其他' || value == 'Others') {
            p.submitRelayType = '其他';
            p.submitRelayStation = '';

            $("#relayStation").html('').hide();
            $('#relayClass').parents('li').hide();
            $('#relayTime').parents('li').hide();

          }
        }
      });


      //送站
      $("#send").picker({
        title: "",
        cols: [{
          textAlign: 'center',
          values: all
        }],
        onClose: function () {
          var value = $('#send').val();
          if (value == '高铁' || value == 'Train') {

            p.submitSendType = '高铁';
            // $('#relayStation').parents('li').show();
            $('#sendClass').parents('li').show();
            $('#sendTime').parents('li').show();

            if (p.english) {
              $("#sendStation").html('<span>Departure station:</span><input type="text" class="flex-1 f14" >').show();
              $("#sendStation input").picker({
                title: "",
                cols: [{
                  textAlign: 'center',
                  values: enHigh
                }],
                onClose: function () {
                  var value = $('#sendStation input').val();
                  var index = enHigh.indexOf(value);
                  p.submitSendStation = higesta[index];
                }
              });
            } else {
              $("#sendStation").html('<span>到达站点：</span><input type="text" class="flex-1 f14" >').show();
              $("#sendStation input").picker({
                title: "",
                cols: [{
                  textAlign: 'center',
                  values: higesta
                }],
                onClose: function () {

                  p.submitSendStation = $('#sendStation input').val();
                }
              });
            }

          } else if (value == '飞机' || value == 'Flight') {
            p.submitSendType = '飞机';
            //planesta
            $('#sendClass').parents('li').show();
            $('#sendTime').parents('li').show();


            if (p.english) {
              $("#sendStation").html('<span>Departure station:</span><input type="text" class="flex-1 f14" >').show();
              $("#sendStation input").picker({
                title: "",
                cols: [{
                  textAlign: 'center',
                  values: enPlane
                }],
                onClose: function () {
                  var value = $('#sendStation input').val();
                  var index = enPlane.indexOf(value);
                  p.submitSendStation = planesta[index];
                }
              });
            } else {
              $("#sendStation").html('<span>到达站点：</span><input type="text" class="flex-1 f14" >').show();
              $("#sendStation input").picker({
                title: "",
                cols: [{
                  textAlign: 'center',
                  values: planesta
                }],
                onClose: function () {

                  p.submitSendStation = $('#sendStation input').val();
                }
              });
            }

          } else if (value == '自驾' || value == 'Self-driving') {
            p.submitSendType = '自驾';
            p.submitSendStation = '';
            $("#sendStation").html('').hide();
            $('#sendClass').parents('li').hide();
            $('#sendTime').parents('li').hide();
          } else if (value == '其他' || value == 'Others') {
            p.submitSendType = '其他';
            p.submitSendStation = '';
            $("#sendStation").html('').hide();
            $('#sendClass').parents('li').hide();
            $('#sendTime').parents('li').hide();
          }
        }
      });
      console.log(p.relayStartTime)
      $("#relayTime").datetimePicker({
        min: "2018-08-01",

      });
      p.relayStartTime = p.relayStartTime.split('-');
      p.relayEndTime = p.relayEndTime.split('-');
      console.log(p.relayStartTime, p.relayEndTime);
      var minmonth = parseInt(p.relayStartTime[1]) - 1;
      var maxmonth = parseInt(p.relayEndTime[1]) - 1;
      if (minmonth == -1) {
        minmonth = 11
      }
      if (maxmonth == -1) {
        maxmonth = 11
      }
      console.log(p.relayStartTime[0], minmonth, p.relayStartTime[2], p.relayEndTime[0], maxmonth, p.relayEndTime[2]);

      $("#relayTime").mobiscroll().datetime({
        theme: '', //皮肤样式
        display: 'bottom', //显示方式 
        mode: 'scroller', //日期选择模式
        lang: 'zh',
        bootstrap: true,
        dateFormat: 'yy-mm-dd',
        min: new Date(parseInt(p.relayStartTime[0]), minmonth, parseInt(p.relayStartTime[2])),
        max: new Date((p.relayEndTime[0]), maxmonth, (p.relayEndTime[2]),23,59)
      });

      $("#sendTime").mobiscroll().datetime({
        theme: '', //皮肤样式
        display: 'bottom', //显示方式 
        mode: 'scroller', //日期选择模式
        lang: 'zh',
        bootstrap: true,
        dateFormat: 'yy-mm-dd',
        min: new Date(parseInt(p.relayStartTime[0]), minmonth, parseInt(p.relayStartTime[2])),
        max: new Date((p.relayEndTime[0]), maxmonth, (p.relayEndTime[2]),23,59)
      });
    }

    var accordion = function () {
      $('body').on('click', '.triangle', function () {
        var obj = $(this);
        var liObj = obj.parents('li').nextAll()
        if (obj.hasClass('up')) {
          liObj.hide();
          obj.removeClass('up');
        } else {
          liObj.show();
          obj.addClass('up');
        }
      });
    }


    var cardCtrl = function () {
      $('body').on('click', '.items>div', function () {
        var id = $(this).attr('data-target');
        if (id == 'three') {
          $('#three1').toggleClass('display');
          $('#three2').toggleClass('display');
        } else {
          $('#' + id).toggleClass('display');
        }
        $(this).find('.checkbox').toggleClass('choose');

      });
    }


    var taketime = null;
    var chooseEvent = function () {
      $('body').on('click', '#two li:first-child~li', function () {
        $(this).find('.checkbox').toggleClass('choose');
      })
      $('body').on('click', '#four li:first-child~li', function () {
        $(this).siblings("li").find(".checkbox").removeClass("choose");
        $(this).find('.checkbox').toggleClass('choose');
        taketime = $(this).find('p').html();
        if($(this).find('span').attr('class').indexOf('choose')>0){

          var mum = 0;
          $('#five li:first-child~li').each(function()
          {
            var node = $(this);
            if($(node.find("p")[0]).html()==taketime)
            {
              node.find("span").removeClass("choose");
              node.hide();
              mum=mum+1;
            }else {
              node.show();
            }
            /*if(){

            }*/
          });

          if( $('#five li:first-child~li').length == mum){
            $('#five').addClass('display');
            $($(".items>div[data-target='five']")).find('span').removeClass('choose');
          }

        }else{
          for(var i =0; i <$('#five li:first-child~li').find('p').length;i++){
              $($('#five li:first-child~li').find('p')[i]).parent().css('display','');
          }
        }

      })
      $('body').on('click','#five li:first-child~li',function(){
        $(this).find('.checkbox').toggleClass('choose');
      })

    }



    var submit = function () {


      $('#submit').click(function () {

        var formdata = {
          meetingId: cfApp.getQueryString('id')
        }
        G.ajax(G.devModePost, p.params.changeApi, formdata, function (retdata) {
          if (retdata.errorNo != '0') {
            if(p.english){
                $.modal({
                    title: "",
                    text: '<span>please contact your Schaeffler account manager.</span>',
                    buttons: [{
                        text: "确定OK",
                        onClick: function () {
                            // location.href='my-schedule-list.html?appid='+p.params.appid+'&id='+cfApp.getQueryString('id');
                        }
                    }]
                });
            }else{
                $.modal({
                    title: "",
                    text: '<span>更新行程，请联系您的专属舍弗勒客户经理。</span>',
                    buttons: [{
                        text: "确定OK",
                        onClick: function () {
                            // location.href='my-schedule-list.html?appid='+p.params.appid+'&id='+cfApp.getQueryString('id');
                        }
                    }]
                });
            }
            return false;
          } else {
            var change = {
              isHotel: 1,
              hotel: "",
              isEat: 1,
              eat: "",
              isRelay: 1,
              relay: "",
              send: "",
              isTake: 1,
              take: "",
              isfactory: 1,
              factory: "",
              desc: ""
            }

            //酒店
            if ($(".items>div[data-target='one'] .checkbox").hasClass('choose')) {
              change.isHotel = 0;
              if (submitHotel()) {
                change.hotel = JSON.stringify(submitHotel());
              } else {
                return false;
              }
            }
            //餐饮
            if ($(".items>div[data-target='two'] .checkbox").hasClass('choose')) {

              change.isEat = 0;

              if (submitEat()) {
                change.eat = JSON.stringify(submitEat());
              } else {
                return false;
              }
            }
            //接送
            if ($(".items>div[data-target='three'] .checkbox").hasClass('choose')) {
              change.isRelay = 0;
              if (submitRelay()) {
                change.relay = JSON.stringify(submitRelay());
              } else {
                return false
              }

              if (submitSend()) {
                change.send = JSON.stringify(submitSend());
              } else {
                return false;
              }
            }

            var str = $(".items>div[data-target='four'] .checkbox").hasClass('choose');
            //试驾
            if ($(".items>div[data-target='four'] .checkbox").hasClass('choose')) {


              change.isTake = 0;

              if (submitTake()) {
                change.take = JSON.stringify(submitTake());
              } else {
                return false;
              }
            }
            //工厂
            if ($(".items>div[data-target='five'] .checkbox").hasClass('choose')) {


              change.isfactory = 0;

              if (submitFactory()) {
                change.factory = JSON.stringify(submitFactory());
              } else {
                return false;
              }
            }


            var desc = $('#content').val();
            if (desc && desc != '') {
              change.desc = desc;
            }

            console.log(change + "");


            var formdata = {
              meetingId: cfApp.getQueryString('id'),
              member_uid: p.empInfo.memberId,
              detailsinfo: JSON.stringify(change),
              accountsId: p.empInfo.accountsId
            }
            G.ajax(G.devModePost, p.params.postApi, formdata, function (retdata) {
              if (retdata.errorNo == '0') {
                $.modal({
                  title: "",
                  text: '<span class="color-green">提交成功！</span><br>Success',
                  buttons: [{
                    text: "确定OK",
                    onClick: function () {

                      if (p.english) {
                        location.href = 'my-schedule-list-english.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id') + '&english=1';
                      } else {
                        location.href = 'my-schedule-list.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id');
                      }

                    }
                  }]
                });
              }
            })
          }
        })
      });
    }
    //提交住宿
    var submitHotel = function () {
      var hotelObj = {
        title: '',
        hoteladrress: '',
        startDate: '',
        endDate: ''
      }
      //var hotel = $('#hotel').val();
      if (!p.submitHotel || p.submitHotel == '') {
        $.modal({
          title: "",
          text: '<span class="color-green">请选择酒店</span><br>Please select the hotel.',
          buttons: [{
            text: "确定OK"
          }]
        });
        return false;
      }
      hotelObj.title = p.submitHotel;
      hotelObj.hoteladrress = p.submitAddress;
      var start = $('#startTime').val();
      if (!start || start == '') {
        $.modal({
          title: "",
          text: '<span class="color-green">请选择入住时间</span><br>Please select your check-in time.',
          buttons: [{
            text: "确定OK"
          }]
        });
        return false;
      }
      hotelObj.startDate = start;
      var end = $('#endTime').val();
      if (!end || end == '') {
        $.modal({
          title: "",
          text: '<span class="color-green">请选择退房时间</span><br>Please select your check-out time.',
          buttons: [{
            text: "确定OK"
          }]
        });
        return false;
      }
      hotelObj.endDate = end;
      return hotelObj;
    }


    //提交餐饮
    var submitEat = function () {
      var dinnerObj = [];
      if (!$('#two .checkbox.choose').length > 0) {
        $.modal({
          title: "",
          text: '<span class="color-green">请选择餐饮</span><br>Please select the catering.',
          buttons: [{
            text: "确定OK"
          }]
        });
        return false;
      } else {
        $('#two .checkbox.choose').each(function () {
          var obj = new Object;
          var item = $(this).next().attr('data-text');
          obj.eatname = item;
          dinnerObj.push(obj);
        })
      }

      return dinnerObj;
    }
    //提交接站
    var submitRelay = function () {
      var relayObj = new Object;
      var relay = p.submitRelayType;
      if (!relay || relay == '') {
        $.modal({
          title: "",
          text: '<span class="color-green">请选择接站交通方式</span><br>Please submit your arrival transportation.',
          buttons: [{
            text: "确定OK"
          }]
        });
        return false;
      }
      if (relay == '高铁' || relay == '飞机') {
        var station = p.submitRelayStation;
        if (!station || station == '') {
          $.modal({
            title: "",
            text: '<span class="color-green">请选择接站站点</span><br>Please submit your arrival station.',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }

        var relayClass = $('#relayClass').val();
        if (!relayClass || relayClass == '') {
          $.modal({
            title: "",
            text: '<span class="color-green">请输入接站班次！</span><br>Please choose the endDate',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }
        var relayTime = $('#relayTime').val();
        if (!relayTime || relayTime == '') {
          $.modal({
            title: "",
            text: '<span class="color-green">请选择接站到达时间</span><br>Please submit your departure time.',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }



        if (relay == '高铁') {
          relayObj.isHigh = 0;
          var highObj = {};
          highObj.highsattion = station;
          relayObj.high = highObj;
        } else {
          relayObj.isPlane = 0;
          var planeObj = {};
          planeObj.planesattion = station;
          relayObj.plane = planeObj;
        }
        relayObj.shift = relayClass;
        relayObj.arrivetime = relayTime;


      } else if (relay == '自驾') {
        relayObj.isOnedrive = 0;

      } else if (relay == '其他') {
        relayObj.isOther = 0;

      }

      return relayObj;

    }
    //提交送站
    var submitSend = function () {
      var sendObj = new Object;
      var send = p.submitSendType;
      if (!send || send == '') {
        $.modal({
          title: "",
          text: '<span class="color-green">请选择送站交通方式</span><br>Please submit your departure transportation.',
          buttons: [{
            text: "确定OK"
          }]
        });
        return false;
      }
      if (send == '高铁' || send == '飞机') {


        var station = p.submitSendStation;
        if (!station || station == '') {
          $.modal({
            title: "",
            text: '<span class="color-green">请选择接站站点</span><br>9.Please submit your departure station.',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }
        var sendClass = $('#sendClass').val();
        if (!sendClass || sendClass == '') {
          $.modal({
            title: "",
            text: '<span class="color-green">请输入送站班次！</span><br>Please choose the endDate',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }
        var sendTime = $('#sendTime').val();
        if (!sendTime || sendTime == '') {
          $.modal({
            title: "",
            text: '<span class="color-green">请选择送站到达时间！</span><br>Please choose the endDate',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }

        if (send == '高铁') {
          sendObj.isHigh = 0;
          var highObj = {};
          highObj.highsattion = station;
          sendObj.high = highObj;
        } else {
          sendObj.isPlane = 0;
          var planeObj = {};
          planeObj.planesattion = station;
          sendObj.plane = planeObj;
        }
        sendObj.shift1 = sendClass;
        sendObj.arrivetime1 = sendTime;
      } else if (send == '自驾') {
        sendObj.isOnedrive = 0;

      } else if (send == '其他') {
        sendObj.isOther = 0;

      }

      return sendObj;
    }

    //提交试驾
    var submitTake = function () {
      var takerObj = [];
      if (!$('#four .checkbox.choose').length > 0) {
        $.modal({
          title: "",
          text: '<span class="color-green">请选择试驾时间</span><br>Please select driving experience time.',
          buttons: [{
            text: "确定OK"
          }]
        });
        return false;
      }
      $('#four .checkbox.choose').each(function () {
        var obj = new Object;
        var item = $(this).next().text();
        var desc=$(this).attr('data-desc');
        obj.taketime = item;
        obj.take_des=desc;
        takerObj.push(obj);
      })


      return takerObj;
    }

    //提交工厂
    var submitFactory = function () {
      var factoryObj = [];
      if (!$('#five .checkbox.choose').length > 0) {
        $.modal({
          title: "",
          /*text: '<span class="color-green">请选择工厂参观</span><br>Please select plant tour time.',*/
          text: '<span class="color-green">往返班车</span><br>Please select Shuttle bus.',
          buttons: [{
            text: "确定OK"
          }]
        });
        return false;
      }
      $('#five .checkbox.choose').each(function () {
        var obj = new Object;
        var item = $(this).next().text();
        var desc=$(this).attr('data-desc');
        obj.visittime = item;
        obj.visitdesc=desc;
        factoryObj.push(obj);
      })


      return factoryObj;
    }



  };

  return SchelduleForm;
})();