<script type="text/javascript">

$('body').on('change keyup', '.damaged_qty', function() {
  var count = 0;
  $(".damaged_qty").each(function() {
    if(parseFloat($(this).val())>0){
      count++;
    }
    $("#stock_transfer_count").val(count);
  });
});


var stock_list_table=function(location_id='',location_name='') {
  $('#stock_list_table_caption').text("List of Materials Available in "+location_name);
  $('#stock_list_table').dataTable().fnDestroy();
  function GetSearchLocation(){
    return $('#location_from').val();
  }
  function GetSearchMaterial(){
    return $('#material_filter').val();
  }
  var loc_name = $("#location_from option:selected").text();
  $("#stock_list_div_title").text('List of Available Stock in '+loc_name);

  var table = $('#stock_list_table').DataTable({
    "ajax":{
      url :"<?php echo base_url().'stock/select_stock_register_2/damages' ?>", // json datasource
      type: "post", // type of method  , by default would be get
      data: function(d){
        d.location_id = GetSearchLocation();
        d.material_id = GetSearchMaterial();
        d.quantity = 'available';
        <?php if($page_name=='work_profile'){?>
          d.work_id = "<?php echo $work_data->work_id?>";
          <?php }elseif($page_name=='work_profile_master' || $page_name=='work_summary_master'){?>
            d.work_ids = "<?php echo implode(',',$sub_project_ids)?>";
            <?php }else{ ?>
            d.location_id = location_id;
            <?php } ?>
          }
        },
        "bProcessing": true,
        "deferRender": true,
        "bDeferRender": true,
        dom:"<'row'<'col-sm-6 text-left material_filter'><'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
        ],
        "columnDefs": [
          {
            "targets": [ 1,2,3,4,11,12,13,14,15,16,17,18,19,20,21 ],
            className: "hidden"
          }
        ],
        'paging': false,
        'order': false,
      });
      $(".hide_column").hide();
      $(".hidden").hide();
      $('<div class="form-group m-form__group row" >'+
      '<div class="col-lg-6"><div class="m-select2 m-select2--air m-select2--pill">'+
      '<select style="width: 100%" class="form-control m-select2 table_filter" id="material_filter"  name="material_filter" >'+
      '<option value="all">All Materials</option>'+
      <?php
      foreach($materials as $row): ?>
      '<option value="<?php echo $row->material_id?>"><?php echo $row->material_name.' [ in '.$row->unit_name.']';?></option>'+
      <?php
    endforeach;
    ?>
    '</select></div></div></div>').appendTo("#stock_list_table_wrapper .material_filter");
    $("#material_filter").select2({
      // dropdownParent: $("#form_purchase_add"),
      placeholder: "Select Material"
    })
    $(".table_filter").on("change", function() {
      table.ajax.reload();
    });
  }

  $('body').on('change', '#damages_location_add', function() {
    var location_id = $(this).val();
    if(location_id!='' && location_id!=null && location_id!='Select Location'){
      var location_name = $('#damages_location_add option:selected').text();
      stock_list_table(location_id,location_name);
      $("#stock_view_div").show();
    }
  })

    $("#damages_location_add").select2({
      placeholder: "Select Location",
      dropdownParent: $("#form_damages_add"),
    })

    </script>




    <script>

    <?php if($page_name!='work_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: {
            quantity: {
              number: !0
            }
          }, invalidHandler: function (e, r) {
            var i = $("#" + form_id + "_msg");
            i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
          }, submitHandler: function (e) {
          }
        }),
        $(".numeric_fields").each(function () {
          // $(this).rules('add', {
          //   number: !0
          // });
        }), 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+"_select").val('').trigger("change");
              toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
              swal({
                width: 500,
                title: obj.flashdata_title,
                text: obj.flashdata_msg,
                type: obj.flashdata_type,
                // showCancelButton: !0,
                confirmButtonText: "Ok",
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                reverseButtons: !0,
                closeOnClickOutside: false,
                allowOutsideClick: false
              }).then(function(e) {
                stock_damages_view_table.ajax.reload();
                <?php if($page_name!='work_profile'){?>
                  $("#damages_work_add").val('').trigger('change');
                  $("#stock_view_div").hide();
                  // stock_list_table('','');
                  <?php } ?>
                })
              } 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 } ?>
      $("#damage_date").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 } ?>
        })

        </script>
