var carInfo = [];
$(window).on('load', function(){
    
    if(localStorage.getItem("carInfo")){ 
       carInfo = JSON.parse(localStorage.getItem('carInfo'));
       addedItem = Object.keys(carInfo).length;
       if(addedItem){
           carInfo = JSON.parse(localStorage.getItem('carInfo'));
           // var HasZeroDep = (carInfo.isPartDepProCover=="1")?"Added":"N/A";
           //$('#span-ZeroDep').text(HasZeroDep);
           //if(carInfo.customerInfo){
            //   $("#first_name").val(carInfo.customerInfo.fname);
            //   $("#last_name").val(carInfo.customerInfo.lname);
            //   $("#email").val(carInfo.customerInfo.email);
            //   $('#dob').val(carInfo.customerInfo.dob);
            //   $("#nominee_dob").val(carInfo.customerInfo.nominee_dob);
            //   $("#nominee_name").val(carInfo.customerInfo.nominee_name);
            //   $('#nominee_relation').val(carInfo.customerInfo.nominee_relation).trigger('change');
               //if(carInfo.customerInfo.mobile!=""){  $("#mobile").val(carInfo.customerInfo.mobile);}
        //       //else{ var userInfo = JSON.parse(localStorage.getItem('customersDetails')); $("#mobile").val(userInfo.mobile);  }
        //   }else{
        //         var userInfo = JSON.parse(localStorage.getItem('customersDetails')); $("#mobile").val(userInfo.mobile);
        //   }
           if(carInfo.addressInfo){
             //  $("#pincode").val(carInfo.addressInfo.pincode);
             //  $("#address").val(carInfo.addressInfo.address);
              if(carInfo.addressInfo.state){
                  var stateStr = carInfo.addressInfo.state;
                  $('#state_id').val(stateStr).trigger('change');
               }
              if(carInfo.addressInfo.city!=null || carInfo.addressInfo.city!=undefined){ 
                  $('#city_id').val(carInfo.addressInfo.city).trigger('change');
              } 
              
           }
           //if(carInfo.vehicleInfo){
               //$("#chassis_number").val(carInfo.vehicleInfo.chassis_number);
               //$("#e_number").val(carInfo.vehicleInfo.engine_number);
            //   $("#reg_date").val(carInfo.vehicleInfo.reg_date);
            //   (carInfo.vehicleInfo.carnumber!="")?$("#car_number").val(carInfo.vehicleInfo.carnumber):$("#car_number").val(carInfo.carnumber);
            //   if(carInfo.vehicleInfo.policyno!=undefined){
            //       $('#policy_no').val(carInfo.vehicleInfo.policyno);
            //   }
            //   if(carInfo.vehicleInfo.policy_exp_date!=undefined){
            //       $('#policy_exp_date').val(carInfo.vehicleInfo.policy_exp_date);
            //   }
           //}else{
                // if(carInfo.newCar==0 && carInfo.withoutCarNo==0){
                //   $("#car_number").val(carInfo.carnumber);
                // }else{
                //   $("#car_number").val(carInfo.rto_code);
                // } 
           //}
       }
    }else{
        alert("Something went wrong");
    }
});
$('#car_number').mask('SS00SS0000');
$('.dob-mask').mask('00-00-0000');
$(document).ready(function() {
    $('#choosePolicyFile').bind('change', function () {
          var filename = $("#choosePolicyFile").val();
          if (/^\s*$/.test(filename)) {
            $(".file-upload").removeClass('active');
            $("#noFile").text("No file chosen..."); 
          }
          else {
            $(".file-upload").addClass('active');
            $("#noFile").text(filename.replace("C:\\fakepath\\", "")); 
          }
        });
        
    function uploadFile(ref,deviceToken){
            if($('#choosePolicyFile').val()!==""){
                var formData = new FormData();
                formData.append('enc', ref);
                formData.append('deviceToken', deviceToken);
                // Attach file
                formData.append('policy_doc', $('#choosePolicyFile')[0].files[0]);
                    $.ajax({
                        url: base_url + "/car-insurance/upload-files/"+ref,
                        type: "POST",
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(response) {
                            
                        },
                        error: function(response) {
                        
                        }
                    });
                return true;
            }else{
               return false; 
            }
        }
     
    $("body").on("click","#btn-step-1",function() {
        var form = $("#profile_form");
        form.validate({
            errorElement: 'span',
            errorClass: 'error',
            errorPlacement: function(error, element) {
                error.insertAfter(element.parent('.form-group'));
            },
            
            highlight: function(element, errorClass, validClass) {
                $(element).closest('.form-group').addClass("has-error");
            },
            unhighlight: function(element, errorClass, validClass) {
                $(element).closest('.form-group').removeClass("has-error");
            },
            
            rules: {
                
                first_name: {
                    required: true,
                    minlength: 3,
                    chars: true,
                },
                last_name: {
                    required: true,
                    minlength: 3,
                    chars: true,
                },
                email: {
                    required: true,
                    email: true,
                },
                dob:{required:true},
                gender: {
                    required: true,
                },
                mobile: {
                    number:true,
                    minlength:10,
                    maxlength:10,
                    required: true,
                },
                nominee_name: {
                    required: true,
                    fullname: true,
                },
                nominee_relation: {
                    required: true,
                },
                company_name: {
                      required: function(element) {
                        return $('#company_name').length > 0 ;
                      }
                },
                gstin_number: {
                  required: function(element) {
                    return $('#gstin_number').length > 0 ;
                  },
                  gst_number:true,
                }
            }
        });
        if (form.valid() === true) {
            var carInfo = JSON.parse(localStorage.getItem('carInfo'));
            var profileInfo = {};
            var company = (carInfo.policyHolderType=="COR")?$('#company_name').val().toUpperCase():"";
            var gstin   = (carInfo.policyHolderType=="COR")?$('#gstin_number').val().toUpperCase():"";
            profileInfo.company_name = company;
            profileInfo.gstin_no = gstin;
            profileInfo.title = $("input[name='title']:checked").val();
            profileInfo.fname = $('#first_name').val();
            profileInfo.lname = $('#last_name').val();
            profileInfo.email = $('#email').val();
            profileInfo.dob = $('#dob').val();
            profileInfo.gender = $("input[name='gender']:checked").val();
            profileInfo.mobile = $('#mobile').val();
            profileInfo.nominee_dob = $('#nominee_dob').val();
            profileInfo.nominee_name = $('#nominee_name').val();
            profileInfo.nominee_relation = $('#nominee_relation').val();
            profileInfo.dob = $('#dob').val();
            profileInfo.hypothecationAgency = $('#hypothecationAgency').val();
            carInfo.customerInfo = profileInfo;
            localStorage.setItem("carInfo", JSON.stringify(carInfo));
            $("#owner_data").removeClass('active-step');
            $("#communication_address").addClass('active-step');
            $("#progress-step-1").removeClass('active').addClass('completed');
            $("#progress-step-2").addClass('active');
        }
    });
    
    $("body").on("click","#btn-step-2",function() {
        var form = $("#address_form");
        form.validate({
            errorElement: 'span',
            errorClass: 'error',
            highlight: function(element, errorClass, validClass) {
                $(element).closest('.form-group').addClass("has-error");
            },
            unhighlight: function(element, errorClass, validClass) {
                $(element).closest('.form-group').removeClass("has-error");
            },
            errorPlacement: function(error, element) {
                error.insertAfter(element.parent('.form-group'));
            },
            rules: {
                pincode: {
                    required: true,
                    minlength: 6,
                    maxlength: 6,
                },
                address: {
                    required: true,
                    minlength: 3,
                },
                city_id: {
                    required: true,
                },
                state_id: {
                    required: true,
                    
                },
            },
            messages: {
                pincode: {
                    required: "Area pincode is required!",
                    minlength:"Enter valid pincode number.",
                    maxlength:"Enter valid pincode number.",
                },
                address: {
                    required: "Your address  is required.",
                },
                city_id: {
                    required: "Your city is required.",
                },
                state_id: {
                    required: "Your State provision is required.",
                },
            }
        });
        if (form.valid() === true) {
            var carInfo = JSON.parse(localStorage.getItem('carInfo'));
            var addressInfo = {};
            addressInfo.pincode = $('#pincode').val();
            addressInfo.address = $('#address').val();
            addressInfo.city = $('#city_id').val();
            addressInfo.state = $('#state_id').val();
            carInfo.addressInfo = addressInfo;
            localStorage.setItem("carInfo", JSON.stringify(carInfo));
            $("#owner_data").removeClass('active-step');
            $("#communication_address").removeClass('active-step');
            $("#vehicle_data").addClass('active-step');
            $("#progress-step-1").removeClass('active').addClass('completed');
            $("#progress-step-2").removeClass('active').addClass('completed');
            $("#progress-step-3").addClass('active');
        }
    });
    
    $("body").on("click","#btn-back-step-2",function() {
            $("#communication_address").removeClass('active-step');
            $("#vehicle_data").removeClass('active-step');
            $("#owner_data").addClass('active-step');
            $("#progress-step-2").removeClass('active').removeClass('completed');
            $("#progress-step-3").removeClass('active').removeClass('completed');
            $("#progress-step-1").addClass('active');
    });
    
    $("body").on("click","#btn-step-3",function() {
        var ref = $(this).attr('data-ref');
        var form = $("#vehicle_form");
        form.validate({
            errorElement: 'span',
            errorClass: 'error',
            highlight: function(element, errorClass, validClass) {
                $(element).closest('.form-group').addClass("has-error");
            },
            unhighlight: function(element, errorClass, validClass) {
                $(element).closest('.form-group').removeClass("has-error");
            },
            rules: {
                chassis_number: {
                    required: true,
                    minlength: 6,
                    maxlength:20
                },
                e_number: {
                    required: true,
                    minlength: 6,
                    maxlength:20
                },
                reg_date: {
                    required: true,
                },
                car_number: {
                    required: true,
                    rtono: true
                },
                policy_no: {
                    required: true,
                },
                policy_exp_date: {
                    required: true,
                },
                previousInsurer: {
                    required: true,
                }
               
            },
            messages: {
                chassis_number: {
                    required: "Classic number required.",
                },
                e_number: {
                    required: "Engine number required.",
                },
                reg_date: {
                    required: "Registration date required.",
                },
                 car_number: {
                    required: "Car Registration number required.",
                    rtono:"Enter valid RTO number."
                },
                policy_no: {
                    required: "Policy number is required.",
                },
                policy_exp_date: {
                    required: "Policy expiry date is required.",
                },
                previousInsurer: {
                    required: "Choose your prevoius insurer.",
                }
                 
            }
        });
        if (form.valid() === true ) {
            var deviceToken = localStorage.getItem('deviceToken');
             var isValid = uploadFile(ref,deviceToken);
             if(isValid){
             $('#btn-step-3').loadButton('on',{faClass:'fa',faIcon:'fa-spinner', doSpin:true,loadingText:'Submitting...', });
            var carInfo = JSON.parse(localStorage.getItem('carInfo'));
            var vehicleInfo = {};
            vehicleInfo.car_number = $('#car_number').val();
            vehicleInfo.reg_date = $('#reg_date').val();
            vehicleInfo.engine_number = $('#e_number').val();
            vehicleInfo.chassis_number = $('#chassis_number').val();
            var carnumber = $('#car_number').val();
            var rto = carnumber.substring(0, 4);
            carInfo.carnumber  = carnumber.toUpperCase();
            carInfo.rto_code   = rto.toUpperCase();
            carInfo.previousInsurer = $('#previousInsurer').val();
            vehicleInfo.car_number = carnumber.toUpperCase();
            
            vehicleInfo.policyno = $('#policy_no').val();
            vehicleInfo.policy_exp_date = $('#policy_exp_date').val();
            carInfo.vehicleInfo = vehicleInfo;
            localStorage.setItem("carInfo", JSON.stringify(carInfo));
            $("#vehicle_data").addClass('active-step');
             var carInfo = JSON.parse(localStorage.getItem('carInfo'));
             var customerData = JSON.parse(localStorage.getItem('customersDetails'));
             
              $.post(base_url + "/car-insurance/create-proposal/"+ref,{enc:ref,deviceToken:deviceToken,carInfo:carInfo,customerData:customerData}, 
              function (resp){
                  $('#btn-step-3').loadButton('off');
                    var status = $.trim(resp.status);
                    if(status=='success'){
                        var enc = resp.data.enc;
                       window.location.href=base_url+"/car-insurance/plan-summary/"+enc;
                     }else{
                          $.toast({
                          text: resp.message,
                          showHideTransition: 'slide',
                          position:'bottom-right',
                          hideAfter:6000,
                          allowToastClose:false
                        }); 
                     }
              });
           }else{
                $.toast({
                  text: 'Please your previous policy document.',
                  showHideTransition: 'slide',
                  position:'bottom-right',
                  hideAfter:6000,
                  allowToastClose:false
                }); 
           }
        }
    });
    
    $("body").on("click","#btn-back-step-3",function() {
            $("#vehicle_data").removeClass('active-step');
            $("#owner_data").removeClass('active-step');
            $("#communication_address").addClass('active-step');
            
            $("#progress-step-1").removeClass('active').addClass('completed');
            $("#progress-step-3").removeClass('active').removeClass('completed');
            $("#progress-step-2").addClass('active');
    });
    
    $("body").on("change","#state_id",function() {
       var state = $(this).val();
       var stateID = state.split('-');
        $.get(base_url + "/get-cities/"+stateID[0], function (resp) {
              if(resp.status=='success'){
                 var citydata =resp.data;
                 $("#city_id").empty();
                     var newState_ = new Option("Select City", "", false, false);
                      $("#city_id").append(newState_);//.trigger('change');
                jQuery.each(citydata, function (index, item) {
                    var newState = new Option(item['value'], item['id'], false, false);
                      $("#city_id").append(newState);//.trigger('change');
                   });
                  
                  if(carInfo.addressInfo.city){ 
                    $('#city_id').val(carInfo.addressInfo.city).trigger('change');
                  } else{
                     $('#city_id').val('').trigger("change");
                  }
              }
        });
    });
    
    $("body").on("change","#city_id",function() {
       var city = $(this).val();
       if(city!=""){
         var CT = city.split('-');
         $.post(base_url + "/get-city-pincode/",{city:CT[1]}, function (resp) { 
              if(resp.status=="success"){
                  $('#pincode').val(resp.pincode);
                //   availableTags = resp.data;
                //   console.log(availableTags);
              }
          },'json');
       }else{
          $('#pincode').val('') 
       }
    })
     
    var start = new Date();
    var default_end = new Date(start.getFullYear()-80, start.getMonth(), start.getDate());
    var end = new Date(start.getFullYear()-18, start.getMonth(), start.getDate());
    
   $("#nominee_dob").datepicker({
        changeMonth: true, changeYear: true,
        minDate : default_end,maxDate: end,
        dateFormat: 'dd-mm-yy', autoclose: true,
     });
     $("#dob").datepicker({
        changeMonth: true, changeYear: true,
        yearRange: "-100:+0",
        minDate : default_end,maxDate: end,
        dateFormat: 'dd-mm-yy', autoclose: true,
     });
     
     $("#reg_date").datepicker({
       changeMonth: true, changeYear: true,
        maxDate: 0,dateFormat: 'dd-mm-yy', autoclose: true,
     });
     
     $("#policy_exp_date").datepicker({
        changeMonth: true, changeYear: true,
        dateFormat: 'dd-mm-yy', autoclose: true,
     });
     
      
     $('body').on('change','#reg_date', function(e){
        var str =  $(this).val();
        $('#span_reg_date').text(str.split("-")[2]);
     })
     
     $('body').on('keyup','#car_number', function(e){
        var str =  $(this).val();
        $('#span_rto_no').text(str.toUpperCase());
     })
 
});

$('body').on('click','.Premium-Breakup', function(e){
    e.preventDefault();
    var ref = $(this).attr('data-ref');
       $.dialog({
            title: '',
            content: 'url:'+base_url+"/common/load-moter-premiumbreakup-modal/enq/"+ref,
            animation: 'scale',
            columnClass: 'medium',
            closeAnimation: 'scale',
            backgroundDismiss: true,
        });
});