<script>
$("#table_filter_vehicle").select2({
  placeholder: "Select Vehicle"
})

$("#vehicle_renewal_paid_date_add,#vehicle_renewal_paid_date_edit,#vehicle_renewal_reference_date_add").datepicker( {
  todayHighlight:!0, orientation:"bottom left", templates: {
    leftArrow: '<i class="la la-angle-left"></i>', rightArrow: '<i class="la la-angle-right"></i>'
  },
  endDate: '+0d',
  <?php if($this->session->userdata('user_role')!='admin' && $this->config->item('User_calendar_date_restriction_enabled')==1){ ?>
    startDate: '<?php echo $this->config->item('User_calendar_date_restriction_start_days');?>d'
    <?php } ?>
  })
  $("#next_renewal_date_add,#next_renewal_date_edit").datepicker( {
    todayHighlight:!0, orientation:"bottom left", templates: {
      leftArrow: '<i class="la la-angle-left"></i>', rightArrow: '<i class="la la-angle-right"></i>'
    }
    })


  $("#vehicle_renewal_debit_acc_add").select2({
    placeholder: "Select Debit Account",
    dropdownParent: $("#form_vehicle_renewal_add")
  })

  $("#renewal_vehicle_add").select2({
    placeholder: "Select vehicle",
    dropdownParent: $("#form_vehicle_renewal_add")
  })

  $("#renewal_work_add").select2({
    placeholder: "Select Work",
    dropdownParent: $("#form_vehicle_renewal_add"),
    templateResult: format_project_dropdown
  })
  $("#renewal_type_add").select2({
    placeholder: "Renewal Type",
    dropdownParent: $("#form_vehicle_renewal_add")
  })
  $("#renewal_type_edit").select2({
    placeholder: "Renewal Type",
    dropdownParent: $("#form_vehicle_renewal_edit")
  })

  $("#vehicle_renewal_debit_payment_mode").select2({
    placeholder: "Select Payment Mode",
    dropdownParent: $("#form_vehicle_renewal_add")
  })


  $("#vehicle_renewal_vehicle_id_edit").select2({
    placeholder: "Select Vehicle",
    dropdownParent: $("#form_vehicle_renewal_edit")
  })

  function calculate_renewal_pay_add(){

  }
  function calculate_renewal_pay_edit(){

  }
  function select_renewal_types(select_type,selected_value=''){
    var vehicle_id = $('#renewal_vehicle_'+select_type).val();
    $('#renewal_type_'+select_type).html('');
    $("#renewal_type_"+select_type).append("<option disabled selected >Select Renewal Type</option>");
    $.post("<?php echo base_url() ?>vehicles/select_renewal_type",{vehicle_id:vehicle_id},function(data) {
      var obj = $.parseJSON(data);
      var i=0;
      if(obj.count==1) {
        while (i < obj.data.length) {
          $("#renewal_type_"+select_type).append("<option value=" + obj.data[i] + ">" +(obj.data[i]).toUpperCase() + "</option>");
          i++;
        }
        if(selected_value!=''){
          $('#renewal_type_'+select_type).val(selected_value).trigger('change');
        }
      }
    })
  }
  $("#renewal_vehicle_add").change(function(e,data='') {
    if(data=='' || data['changeevent']!=false){
      select_renewal_types('add');
    }

  });
  $('body').on('click', '#btn_add_renewal_payment', function() {
    var no = $(this).closest('tr').children('td');
    var vehicle_id = no.eq(6).text();
    var renewal_type = no.eq(7).text();
    $('#renewal_vehicle_add').val(vehicle_id).trigger('change',{'changeevent':false});
    select_renewal_types('add',renewal_type);
  })
  $("#renewal_type_add").change(function() {
    var vehicle_id = $('#renewal_vehicle_add').val();
    var renewal_type = $('#renewal_type_add').val();
    $.post("<?php echo base_url() ?>vehicles/select_renewal_details",{vehicle_id:vehicle_id,renewal_type:renewal_type},function(data) {
      var obj = $.parseJSON(data);
      var i=0;
      if(obj.count==1) {
        $("#renewal_date_add").val(obj.data['renewal_date']);
        if(renewal_type=='emi'){
          $("#renewal_amount_add_div").show();
          $("#renewal_amount_add").val(obj.data['renewal_amount']);
          $("#vehicle_renewal_paid_amount_add").val(obj.data['renewal_amount']);
          $("#next_renewal_date_add_div").hide();
          $("#next_renewal_date_add").removeAttr('required',true);
        }else{
          $("#renewal_amount_add_div").hide();
          $("#next_renewal_date_add_div").show();
          $("#next_renewal_date_add").attr('required',true);
        }
      }
    })
  });

  $('body').on('change keyup', '.vehicle_renewal_calculate_fields', function() {
    if($(this).val()==''){
      $(this).val(0);
    }
    calculate_renewal_pay_add();
  })
  $('body').on('change keyup', '.vehicle_renewal_calculate_fields_edit', function() {
    if($(this).val()==''){
      $(this).val(0);
    }
    calculate_renewal_pay_edit();
  })
  $('body').on('change keyup', '.final_balance_calculate_fields', function() {
    var balance = $('#consignee_name_add_payment').val();
    var paid = $('#paid_amount_edit_bill_payment').val();
    var final_balance =  balance - paid;
    $('#balance_amount_add_bill_payment').val(final_balance);
    var balance_edit = $('#bill_balance_amount_edit_bill_payment').val();
    var paid_edit =  $('#paid_amount_edit_bill_payment').val();

    var final_balance_edit =  balance_edit - paid_edit;

    $('#balance_amount_edit_bill_payment').val(final_balance_edit);

  })


  function GetSearchVehicle(){
    return $('#table_filter_vehicle').val();
  }
  function GetSearchDate(){
    return $('#table_filter_date').val();
  }
  function GetSearchVehicle(){
    return $('#table_filter_vehicle').val();
  }

  var vehicle_renewal_transaction_view_table = $('#vehicle_renewal_transaction_view_table').DataTable({
    "ajax":{
      url :"<?php echo base_url().'vehicles/select_renewal_transactions' ?>", // json datasource
      type: "post", // type of method  , by default would be get
      data: function(d){
        <?php if($page_name=='vehicle_profile') { ?>
          d.vehicle_id = <?= $vehicle_data->id ?>;
          <?php } else { ?>
            d.vehicle_id = GetSearchVehicle();
            <?php } ?>
            <?php if($page_name=='renewal_payments') { ?>
            d.date = GetSearchDate();
            <?php } ?>
            <?php if($page_name=='user_profile') { ?>
              d.user_id = <?= $user_data->user_id ?>;
              <?php } ?>

            }
          },
          "bProcessing": true,
          "deferRender": true,
          "bDeferRender": true,
          "scrollX" : true,
          buttons: [
            { extend: 'print', className: 'btn dark btn-outline',exportOptions: {columns: ':visible'} ,title: 'Vehicle Renewal Transactions'},
            { extend: 'csv', className: 'btn purple btn-outline ' },
            { extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'}
          ],
          dom:"<'row'<'col-sm-6 text-left'B><'col-sm-6 text-right'f>>\n\t\t\t<'row'<'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>", // horizobtal scrollable datatable
          "lengthMenu": [
            [25, 50, 100, -1],
            [25, 50, 100, "All"] // change per page values here
          ],
          // set the initial value
          "pageLength": 25,
          "columnDefs": [
            {
              "targets": [ 7,8,9,19,<?php if($page_name=='vehicle_profile'){ echo "3,4"; }?>],
              className: "hidden"
            }
          ],
          'ordering': false
        });
        var vehicle_pending_renewal_view_table = $('#vehicle_pending_renewal_view_table').DataTable({
          "ajax":{
            url :"<?php echo base_url().'vehicles/select_pending_renewal' ?>", // json datasource
            type: "post", // type of method  , by default would be get
            data: function(d){
              <?php if($page_name=='vehicle_profile') { ?>
                d.vehicle_id = <?= $vehicle_data->id ?>;
                <?php } else { ?>
                  d.vehicle_id = GetSearchVehicle();
                  <?php } ?>
                  }
                },
                "bProcessing": true,
                "deferRender": true,
                "bDeferRender": true,
                "scrollX" : true,
                'searching' : false,
                dom:"<'row'<'col-sm-6 text-left'><'col-sm-6 text-right'f>>\n\t\t\t<'row'<'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>", // horizobtal scrollable datatable
                "lengthMenu": [
                  [25, 50, 100, -1],
                  [25, 50, 100, "All"] // change per page values here
                ],
                // set the initial value
                "pageLength": 25,
                "columnDefs": [
                  {
                    "targets": [ 6,7 ],
                    className: "hidden"
                  }
                ],
                'ordering': false
              });
        $(".table_filter").on("change", function() {
          vehicle_renewal_transaction_view_table.ajax.reload();
          vehicle_pending_renewal_view_table.ajax.reload();
        });
        $(".hide_column").hide();


        // Date Range Picker
        var start = moment();
        var end = moment();

        function cb(start, end) {
          $('#table_filter_date').val(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
          vehicle_renewal_transaction_view_table.ajax.reload();
        }

        $('#table_filter_date').daterangepicker({
          buttonClasses: "m-btn btn",
          applyClass: "btn-primary",
          cancelClass: "btn-secondary",
          startDate: start,
          endDate: end,
          locale: {
            format: 'MMMM D, YYYY'
          },
          ranges: {
            'Today': [moment(), moment()],
            'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            'Last 7 Days': [moment().subtract(6, 'days'), moment()],
            'Last 30 Days': [moment().subtract(29, 'days'), moment()],
            'This Month': [moment().startOf('month'), moment().endOf('month')],
            'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
            'All time': [moment('1970-01-01'), moment().add(9999, 'days')],
          }
        }, cb);

        cb(start, end);

        <?php if($page_name!='vehicle_profile') { ?>
          $(".form_submit_btn").click(function (e) {
            e.preventDefault();
            var a = $(this),
            l = $(this).closest("form"),
            action = l.attr('action');
            var form_id = l.attr('id');
            l.validate({
              rules: {
                worked_duration: {
                  number: !0,
                  min: 1
                },
                basic_charge: {
                  number: !0,
                  min:0
                }
              }, invalidHandler: function (e, r) {
                var i = $("#" + form_id + "_msg");
                i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
              }, submitHandler: function (e) {
              }
            }), l.valid() && (a.addClass("m-loader m-loader--right m-loader--light").attr("disabled", !0),
            l.ajaxSubmit({
              url: action,
              success: function (e, t, r, s) {
                var modal_id = l.attr('data-modal-id');
                var form_type = l.attr('data-form-type');
                $("#" + form_id + "_msg").addClass("m--hide");
                // Block UI
                mApp.blockPage({
                  overlayColor: "#000000",
                  type: "loader",
                  state: "success",
                  message: "Please wait..."
                }), setTimeout(function () {
                  mApp.unblockPage()
                }, 2e3);
                var obj = $.parseJSON(e);
                if (obj.status == 1) {
                  a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                  $("#"+modal_id).modal('toggle');
                  $("."+form_id+"_fields").val('');
                  $("."+form_id+"_fields_1").val(0);
                  $("."+form_id+"_fields_2").val(1);
                  $("."+form_id+"_select").val('').trigger("change");
                  toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
                  vehicle_renewal_transaction_view_table.ajax.reload();
                  vehicle_pending_renewal_view_table.ajax.reload();
                  $('#vehicle_renewal_paid_date_add').datepicker("setDate", "<?php echo date('d-m-Y')?>");
                } else {
                  a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                  toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
                }
                if (obj == null) {
                  setTimeout(function () {
                    a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                    toastr["warning"]("Your Attempt is Timed Out. Please Try Again.", "Timed Out");
                  }, 2e4)
                }
              },error: function() {
                a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                toastr["error"]("Sorry. There Has Been Some Error Occurred. Please Try Again.", "Error");
              }
            })
          )
        });

        <?php } ?>

        </script>
