
var table ,   block = $(".content-wrapper").parent();
    
    function transfer_stock(itemid,stock_name, erbil_code, turkish_code, total_len){


      stock_name      = decodeURIComponent_back(stock_name);
      erbil_code      = decodeURIComponent_back(erbil_code);
      turkish_code    = decodeURIComponent_back(turkish_code);
      
      $(".curnt_stock").html(stock_name);
      $(".erbil_code").html(erbil_code);
      $(".turkish_code").html(turkish_code);
      $(".product_leng").html(total_len);

      $("#edit_objid").val(itemid);
      $('#edit_form_cont').modal('toggle');
    }

    function delete_items(itemid) {
      block = $("#list_of_items_tbl");
      // bootstrap modal confirmation box
        swal({
            title: Translation("هل انت متأكد؟!"),
            text: Translation("سوف لن تستطيع استرجاع المعلومات المرتبطة بهذا السجل في حالة المسح"),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#EF5350",
            confirmButtonText: Translation("موافق: امسح!"),
            cancelButtonText: Translation("الغاء الامر"),
            closeOnConfirm: false,
            closeOnCancel: true
        },
        function(isConfirm){
            if (isConfirm) {
              $.ajax({
                url: "models/crul_stock.php",
                type:"POST",
                dataType : "JSON",
                data: {"type":"delete","obj_id":itemid} ,
                complete:function(){
                 // hideLoader();
                },
                beforeSend:function(){
                 // showLoader("Deleting Category");
                },
                success: function(res) {

                  if(res.is_success == true){
                    swal({
                            title: Translation("حذف"),
                            text: Translation(res.data),
                            confirmButtonColor: "#66BB6A",
                            type: "success"
                        });
                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                  }else{
                    swal({
                            title: Translation("خطأ"),
                            text: Translation(res.data),
                            confirmButtonColor: "#2196F3",
                            type: "error"
                        });
                  }
                }
            });
            }
        }); // /confirm
    }

    // finish_product

    function used_in_production(itemid,stock_name='', erbil_code='', turkish_code='', total_len='') {

      stock_name      = decodeURIComponent_back(stock_name);
      erbil_code      = decodeURIComponent_back(erbil_code);
      turkish_code    = decodeURIComponent_back(turkish_code);
      
      $(".curnt_stock").html(stock_name);
      $(".erbil_code").html(erbil_code);
      $(".turkish_code").html(turkish_code);
      $(".product_leng").html(total_len);

      $("#id_production").val(itemid);
      $('#production_form_cont').modal('toggle');
      
    }

    function finish_product(itemid) {
      block = $("#list_of_items_tbl");
      // bootstrap modal confirmation box

             swal({
                  title: Translation("هل انت متأكد؟!"),
                  text: Translation("هل انت متأكد انه تم استخدام هذا العنصر بالكامل في الانتاج ولم يبقى منه شي؟"),
                  type: "warning",
                  showCancelButton: true,
                  confirmButtonColor: "#EF5350",
                  confirmButtonText: Translation("موافق"),
                  cancelButtonText: Translation("الغاء الامر"),
                  closeOnConfirm: true,
                  closeOnCancel: true
              },
              function(isConfirm){
                  if (isConfirm) {
                        $.ajax({
                              url: "models/crul_stock_detail.php",
                              type:"POST",
                              dataType : "JSON",
                              data: {"type":"finish_product","obj_id":itemid} ,
                              complete:function(){
                               // hideLoader();
                              },
                              beforeSend:function(){
                               // showLoader("Deleting Category");
                              },
                              success: function(res) {

                                if(res.is_success == true){
                                  noty({
                                                width: 200,
                                                text: Translation(res.data), //'Product Successfully Update',
                                                type: 'success',
                                                dismissQueue: true,
                                                timeout: 3000,
                                                layout: 'topRight',
                                              });
                                  $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                                }else{
                                  noty({
                                                width: 200,
                                                text: Translation(res.data), //'Product Successfully Update',
                                                type: 'error',
                                                dismissQueue: true,
                                                timeout: 3000,
                                                layout: 'topRight',
                                              });
                                }
                              }
                          });
                  }
              }); // /confirm


            
            
      
    }

    
    function add_damage(itemid ,stock_name, erbil_code, turkish_code, total_len) {


      stock_name      = decodeURIComponent_back(stock_name);
      erbil_code      = decodeURIComponent_back(erbil_code);
      turkish_code    = decodeURIComponent_back(turkish_code);
      
      $(".curnt_stock").html(stock_name);
      $(".erbil_code").html(erbil_code);
      $(".turkish_code").html(turkish_code);
      $(".product_leng").html(total_len);

      $("#id_damage").val(itemid);
      $('#add_damage_form_cont').modal('toggle');

    }

    function fully_damages(itemid) {
      block = $("#list_of_items_tbl");
      // bootstrap modal confirmation box
        swal({
            title: Translation("هل انت متأكد؟!"),
            text: Translation("هل انت متأكد ان هذا العنصر هو تالف بالكامل لانه سيعتبر كتالف نهائي ولايمكن استراجاعه"),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#EF5350",
            confirmButtonText: Translation("موافق!"),
            cancelButtonText: Translation("الغاء الامر"),
            closeOnConfirm: true,
            closeOnCancel: true
        },
        function(isConfirm){
            if (isConfirm) {
                  $.ajax({
                      url: "models/crul_stock_detail.php",
                      type:"POST",
                      dataType : "JSON",
                      data: {"type":"damages","obj_id":itemid} ,
                      complete:function(){
                       // hideLoader();
                      },
                      beforeSend:function(){
                       // showLoader("Deleting Category");
                      },
                      success: function(res) {

                        if(res.is_success == true){
                          noty({
                                        width: 200,
                                        text: Translation(res.data), //'Product Successfully Update',
                                        type: 'success',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'topRight',
                                      });
                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                        }else{
                          noty({
                                        width: 200,
                                        text: Translation(res.data), //'Product Successfully Update',
                                        type: 'error',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'topRight',
                                      });
                        }
                      }
                  });
            }
        }); // /confirm



            
      
    }


    function get_Stock(){

            $.ajax({
                  url : 'models/crul_stock.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<li><a  href="index.php?p=stock_detail"><i class="icon-stackoverflow text-orange-800 text-black"></i><span id="stocks_filter_link_0">'+Translation('جميع المخازن')+'</span></a></li>';
                      var attach1 ='<option value="" selected="selected">'+Translation('تحديد المخزن')+'</option>';
                        for(var i=response.length-1 ; i >= 0;i--){
                          var tp =Translation("خزن");
                          if(response[i][2]==1){tp =Translation("انتاج");}
                          attach1 = attach1 + '<option data-subtext="'+tp+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';

                          if(response[i][2]==1){
                            attach = attach + '<li><a  href="index.php?p=stock_detail&id='+response[i][0]+'"><i class="icon-scissors text-success"></i> <span id="stocks_filter_link_'+response[i][0]+'">'+response[i][1]+'</span></a></li>';
                          }else{
                            attach = attach + '<li><a  href="index.php?p=stock_detail&id='+response[i][0]+'"><i class="icon-store text-info"></i> <span id="stocks_filter_link_'+response[i][0]+'">'+response[i][1]+'</span></a></li>';
                          }
                           
                          
                        }
                        $("#stock_filter").html(attach);
                        $("#stock_id").html(attach1);

                        change_filter_btn_text();
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                         get_Products();
                  }

            }); // submit ajax

    }


    function get_Products(){

            $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option class="text-black text-danger-800" selected="selected" value="">'+Translation('جميع المواد')+'</option>';
                      // var attach ='';
                      
                        for(var i=response.length-1 ; i >= 0;i--){
                          var tp =response[i][2];
                          
                            attach = attach + '<option class="text-black text-danger-800" data-subtext="'+Translation('الرمز الاجنبي')+' : '+response[i][2]+' || '+Translation('الرمز التسلسلي')+' : '+response[i][3]+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          
                           
                          
                        }
                        $("#product_id_search").html(attach);
                        $('#product_id_search').selectpicker('refresh');
                        change_status_btn_text();
                        
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);

                  }

            }); // submit ajax

    }

    function change_filter_btn_text(){

      var id = getQueryVariable("id");

      if(id != 'not'){
        var text_btn = $("#stocks_filter_link_"+id).text();
        $("#stock_btn").text(text_btn);
      }else{
        var text_btn = $("#stocks_filter_link_0").text();
        $("#stock_btn").text(text_btn);

      }
      
    }

      var id_  ='';
      var pid_ ='';
      var sid_ ='';

    function change_status_btn_text(){

      var sid   = getQueryVariable("sid");
      var id    = getQueryVariable("id");
      var pid   = getQueryVariable("pid");

      

      if(id != 'not'){
        id_ = '&id='+id;
      }

      if(sid != 'not'){
        sid_ = '&sid='+sid;
      }

      if(pid != 'not'){
        pid_ = '&pid='+pid;
        $("#product_id_search").val(pid).selectpicker('refresh');

      }


     


      var attach ='';

      attach = `  <li><a  href="index.php?p=stock_detail`+id_+pid_+`"><i class="icon-close2 text-danger-800 text-black"></i><span id="status_filter_link">`+Translation('ازالة الفلتر')+`</span></a></li>
                  <li><a  href="index.php?p=stock_detail`+id_+pid_+`&sid=0"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_0">`+Translation('متوفر في مخزن الخزن من دون تالف')+`</span></a></li>
                  <li><a  href="index.php?p=stock_detail`+id_+pid_+`&sid=1"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_1">`+Translation('مباع بالكامل')+`</span></a></li>
                  <li><a  href="index.php?p=stock_detail`+id_+pid_+`&sid=2"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_2">`+Translation('متوفر في مخزن الانتاج /غير مستخدم من دون تالف')+`</span></a></li>
                  <li><a  href="index.php?p=stock_detail`+id_+pid_+`&sid=3"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_3">`+Translation('استخدم في الانتاج')+`</span></a></li>
                  <li><a  href="index.php?p=stock_detail`+id_+pid_+`&sid=4"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_4">`+Translation('تم الانتاج وانتهت المادة')+`</span></a></li>
                  <li><a  href="index.php?p=stock_detail`+id_+pid_+`&sid=5"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_5">`+Translation('مباع بالتجزئة')+`</span></a></li>
                  <li><a  href="index.php?p=stock_detail`+id_+pid_+`&sid=6"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_6">`+Translation('تالف بالكامل')+`</span></a></li>
                  <li><a  href="index.php?p=stock_detail`+id_+pid_+`&sid=7"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_7">`+Translation('مسترجع')+`</span></a></li>
                  <li><a  href="index.php?p=stock_detail`+id_+pid_+`&sid=8"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_8">`+Translation('متوفر في مخزن الخزن ويحوي تالف')+`</span></a></li>
                  <li><a  href="index.php?p=stock_detail`+id_+pid_+`&sid=9"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_9">`+Translation('مباع بالتجزئة ومستخدم في الانتاج')+`</span></a></li>
                  <li><a  href="index.php?p=stock_detail`+id_+pid_+`&sid=10"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_10">`+Translation('استخدم كليا (مباع بالتجزئة و مستخدم في الانتاج)')+`</span></a></li>
                  <li><a  href="index.php?p=stock_detail`+id_+pid_+`&sid=11"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_11">`+Translation('متوفر في مخزن الانتاج /غير مستخدم ويحتوي تالف')+`</span></a></li>
                  `;
      
      $("#status_filter").html(attach);

      if(sid != 'not'){       
        var text_btn = $("#status_filter_link_"+sid).text();
        $("#status_btn").text(text_btn);
        $("#status_color").removeClass('bg-danger-400');
        $("#status_color").addClass('bg-success-400');

      }
      
    }

    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
          var pair = vars[i].split("=");
          if (pair[0] == variable) {
            return pair[1];
          }
        }
        return 'not';
    }

    function select_all(){
        $('#product_id_search').selectpicker('selectAll');

    }

    function deselect_all(){
        $('#product_id_search').selectpicker('deselectAll');

        window.location="index.php?p=stock_detail"+id_+sid_;


    }

$(document).ready(function() {

  // Select all method
    



    

    $('#add_form').submit(function(event) {
            event.preventDefault();
            // block

            block = $(this).parent();
            // \block

            var name          = $("#objname").val();
            var stock_type    = $("#stock_type").val();
            var stock_note    = $("#stock_note").val();

            var Check1 = true;
            var Check2 = true;

            if(name =='') {
               $("#objname").closest('.form-group').removeClass('has-success');
               $("#objname").closest('.form-group').addClass('has-error');
               Check1 = false;
               noty({
                        width: 200,
                        text: "Please Enter the Category Name",
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'top',
                  });
            }else{
               $("#objname").closest('.form-group').removeClass('has-error');
               $("#objname").closest('.form-group').addClass('has-success');
            }

            if(stock_type =='') {
               $("#stock_type").closest('.form-group').removeClass('has-success');
               $("#stock_type").closest('.form-group').addClass('has-error');
               Check2 = false;
               noty({
                        width: 200,
                        text: "الرجاء قم بتحديد نوع المخزن",
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'top',
                  });
            }else{
               $("#stock_type").closest('.form-group').removeClass('has-error');
               $("#stock_type").closest('.form-group').addClass('has-success');
            }
          

            if(Check1 && Check2){
              $("#submit_add_btn").attr('disabled',true);
                $.ajax({
                    url: "models/crul_stock.php",
                    type:"POST",
                    dataType : "JSON",
                    data : {name:name,stock_type:stock_type,stock_note:stock_note,type:'create'}
                })
                .done(function(res) {
                  //alert(res);
                  if(res.is_success == true){
                      $("#add_form")[0].reset();
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                      $("#add-form-cont").collapse('hide');
                      noty({
                                      width: 200,
                                      text: res.data,
                                      type: 'success',
                                      dismissQueue: true,
                                      timeout: 3000,
                                      layout: 'topRight',
                                });
                  }else{
                      swal({
                          title: "خطأ",
                          text: res.data,
                          confirmButtonColor: "#66BB6A",
                          type: "error"
                      });
                  }
                  $("#submit_add_btn").attr('disabled',false);
                })
                .fail(function(err) {
                   swal({
                      title: "Error",
                      text: "Detail:"+err,
                      confirmButtonColor: "#66BB6A",
                      type: "error"
                    });
                   $("#submit_add_btn").attr('disabled',false);
                })
                .always(function() {
                    console.log("complete");
                });
            }

    });


    
  $('#edit_form').submit(function(event) {
            event.preventDefault();
            // block
            block = $(this).parent();
            // \block

            var stock_id      = $("#stock_id").val();
            var catId         = $("#edit_objid").val();
           
            var Check1 = true;
            var Check2 = true;

            if(stock_id =='') {
               $("#stock_id").closest('.form-group').removeClass('has-success');
               $("#stock_id").closest('.form-group').addClass('has-error');
               Check1 = false;
               noty({
                        width: 200,
                        text: Translation("الرجاء قم بتحديد المخزن"),
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'top',
                  });
            }else{
               $("#stock_id").closest('.form-group').removeClass('has-error');
               $("#stock_id").closest('.form-group').addClass('has-success');
            }

            

           

            if(Check1 && Check2 ){
                $.ajax({
                    url: "models/crul_stock_detail.php",
                    type:"POST",
                    dataType : "JSON",
                    data : {stock_id:stock_id,obj_id:catId,type:'transfer_stock'},
                    complete:function(){
                      //hideLoader();
                    },
                    beforeSend:function(){
                      //showLoader("Updating Category");
                    },
                    success: function(res) {
                      if(res.is_success == false){
                          $("#edit-form-cont").collapse('hide');
                          $('#edit_form_cont').modal('toggle');
                          $("#edit_form")[0].reset();
                          swal({
                              title: Translation("خطأ"),
                              text: Translation(res.data),
                              confirmButtonColor: "#66BB6A",
                              type: "warning"
                          });
                      
                      }else{

                          $("#edit_form")[0].reset();
                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);

                          $('#edit_form_cont').modal('toggle');
                          noty({
                                  width: 200,
                                  text: Translation(res.data), //'Product Successfully Update',
                                  type: 'success',
                                  dismissQueue: true,
                                  timeout: 3000,
                                  layout: 'topRight',
                                });
                      }
                    }
                });
              }
    });

  $('#add_damage_form').submit(function(event) {
            event.preventDefault();
            // block
            block = $(this).parent();
            // \block

            var itemid        = $("#id_damage").val();
            var length_m      = $("#damage_length").val();
           
            var Check1 = true;
            var Check2 = true;

            if(length_m =='') {
               $("#damage_length").closest('.form-group').removeClass('has-success');
               $("#damage_length").closest('.form-group').addClass('has-error');
               Check1 = false;
               noty({
                        width: 200,
                        text: Translation("الرجاء قم بادخال الطول التالف بالمتر"),
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'top',
                  });
            }else{
               $("#damage_length").closest('.form-group').removeClass('has-error');
               $("#damage_length").closest('.form-group').addClass('has-success');
            }

            

           

            if(Check1 && Check2 ){

              $.ajax({
                      url: "models/crul_stock_detail.php",
                      type:"POST",
                      dataType : "JSON",
                      data: {"type":"add_damage","obj_id":itemid,length_m:length_m} ,
                      complete:function(){
                       // hideLoader();
                      },
                      beforeSend:function(){
                       // showLoader("Deleting Category");
                      },
                      success: function(res) {

                        if(res.is_success == true){
                          $('#add_damage_form_cont').modal('toggle');
                          $("#add_damage_form")[0].reset();
                          noty({
                                        width: 200,
                                        text: Translation(res.data), //'Product Successfully Update',
                                        type: 'success',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'topRight',
                                      });
                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                        }else{
                          noty({
                                        width: 200,
                                        text: Translation(res.data), //'Product Successfully Update',
                                        type: 'error',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'topRight',
                                      });
                        }
                      }
                  });

               
              }
    });

  $('#production_form').submit(function(event) {
            event.preventDefault();
            // block
            block = $(this).parent();
            // \block

            var itemid        = $("#id_production").val();
            var length_m      = $("#used_length").val();
           
            var Check1 = true;
            var Check2 = true;

            if(length_m =='') {
               $("#used_length").closest('.form-group').removeClass('has-success');
               $("#used_length").closest('.form-group').addClass('has-error');
               Check1 = false;
               noty({
                        width: 200,
                        text: Translation("الرجاء قم بادخال الطول المستخدم في الانتاج بالمتر"),
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'top',
                  });
            }else{
               $("#used_length").closest('.form-group').removeClass('has-error');
               $("#used_length").closest('.form-group').addClass('has-success');
            }

            

           

            if(Check1 && Check2 ){

                  $.ajax({
                        url: "models/crul_stock_detail.php",
                        type:"POST",
                        dataType : "JSON",
                        data: {"type":"used_product","obj_id":itemid,length_m:length_m} ,
                        complete:function(){
                         // hideLoader();
                        },
                        beforeSend:function(){
                         // showLoader("Deleting Category");
                        },
                        success: function(res) {

                          if(res.is_success == true){
                            $('#production_form_cont').modal('toggle');
                            $("#production_form")[0].reset();
                            noty({
                                          width: 200,
                                          text: Translation(res.data), //'Product Successfully Update',
                                          type: 'success',
                                          dismissQueue: true,
                                          timeout: 3000,
                                          layout: 'topRight',
                                        });
                            $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                          }else{
                            noty({
                                          width: 200,
                                          text: Translation(res.data), //'Product Successfully Update',
                                          type: 'error',
                                          dismissQueue: true,
                                          timeout: 3000,
                                          layout: 'topRight',
                                        });
                          }
                        }
                    });
            
               
            }
    });
    
    

});


  var product_id = $("#product_id_search").val();

    function search_Product(){
        product_id = $("#product_id_search").val();
        // $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
        if(product_id >0){
          window.location="index.php?p=stock_detail&pid="+product_id+id_+sid_;
        }else{
          window.location="index.php?p=stock_detail"+id_+sid_;
        }
    }

    function show_detail_page(){
        product_id = $("#product_id_search").val();
        console.log(product_id)
        if(product_id !=null){
          window.location="index.php?p=stock_detail&pid="+product_id;
        }else{
          noty({
                  width: 200,
                  text: Translation('قم باختيار مادة'), //'Product Successfully Update',
                  type: 'error',
                  dismissQueue: true,
                  timeout: 3000,
                  layout: 'topRight',
                });
        }
    }



$(function() {
//var singleSelect = $('.datatable-column-search-inputs').DataTable();
    




   // Setting datatable defaults
    $.extend( $.fn.dataTable.defaults, {
        autoWidth: false,
        columnDefs: [{ 
            orderable: false,
            width: '100px',
            targets: [ 4 ]
        }],
        dom: '<"datatable-header"fBl><"datatable-scroll"t><"datatable-footer"ip>',
        language: {
            search: '<span>'+Translation('بحث')+':</span> _INPUT_',
            searchPlaceholder: Translation('بحث عن')+'...',
            lengthMenu: '<span>'+Translation('عرض')+':</span> _MENU_',
            paginate: { 'first': 'First', 'last': 'Last', 'next': '&larr;', 'previous': '&rarr;' }
        },
        drawCallback: function () {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
        },
        preDrawCallback: function() {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
        }
    });

    

    // Individual column searching with text inputs
    $('.datatable-column-search-inputs tfoot td').not(':last-child').each(function () {
        var title = $('.datatable-column-search-inputs thead th').eq($(this).index()).text();
        $(this).html('<input type="text" class="form-control input-sm" placeholder="'+Translation('بحث عن')+' '+title+'" />');
    });
    
    
   var query_id = getQueryVariable("id");
   var query_pid = getQueryVariable("pid");
   var query_sid = getQueryVariable("sid");
   
   var table = $('.datatable-column-search-inputs').DataTable({
        buttons: {            
            buttons: [
                {
                    extend: 'copyHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: [ 0, ':visible' ]
                    }
                },
                {
                    extend: 'excelHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'pdfHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'print',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'colvis',
                    text: '<i class="icon-three-bars"></i> <span class="caret"></span>',
                    className: 'btn bg-blue btn-icon'
                }
                
            ]
        },
        lengthMenu: [
            [  10, 25, 50, 100 ],
            [  '10', '25', '50', '100' ]
        ],
        "processing": true,
        "serverSide": true,
        "ajax": {
        "url" : "models/crul_stock_detail.php",
        "data": function(d){
          d.type = "load";
          if(query_id !='not'){
            d.id =query_id ;
          }
          if(query_pid !='not'){
            d.pid =query_pid ;
          }
          if(query_sid !='not'){
            d.sid =query_sid ;
          }

          if((product_id > 0 && product_id !=null && product_id !=undefined && product_id !='') ){
            d.pid =product_id ;
          }
        }
        },
        drawCallback: function() {
                  $('[data-popup=tooltip]').tooltip();
                  $('[data-popup=popover-custom]').popover({
                    template: '<div class="popover  border-teal-400"><div class="arrow"></div><h3 class="popover-title bg-teal-400"></h3><div class="popover-content"></div></div>'
                  });

            },
        "columnDefs": [
          {
              "targets": 13,
              "data": null,
              "render": function (data,type,row) {

                            var btns='';

                          

                                if(row[12]==3 || row[12]==2 || row[12]==11){
                                  btns=btns+`
                                        <li class='text-teal-600'>
                                            <a  class='text-teal-400' onclick="finish_product(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('تم استخدامه كليا')+`'>
                                                <i class='icon-bookmark4'></i>
                                            </a>
                                        </li>
                                  `;
                                }

                                if(row[12]==0 || row[12]==2 || row[12]==7 || row[12]==8 || row[12]==11){
                                  btns=btns+`
                                        <li class='text-primary-600'>
                                            <a  class='text-orange-400' onclick="fully_damages(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('المنتج تالف كليا')+`'>
                                                <i class='icon-blocked'></i>
                                            </a>
                                        </li>
                                  `;
                                }

                                if(row[12]==0 || row[12]==2 || row[12]==3 || row[12]==5 || row[12]==8 || row[12]==9 || row[12]==11){
                                  btns=btns+`
                                        <li class='text-primary-600'>
                                            <a  class='text-primary-400' onclick="add_damage(`+row[0]+`,'`+escapeHtml(row[1])+`','`+escapeHtml(row[3])+`','`+escapeHtml(row[4])+`','`+(row[6])+`')" data-popup='tooltip' data-original-title='`+Translation('اضافة تالف')+`'>
                                                <i class='icon-pagebreak'></i>
                                            </a>
                                        </li>
                                  `;
                                }

                                if(row[12]==2 || row[12]==3 || row[12]==5 || row[12]==9 || row[12]==11 ){
                                  btns=btns+`
                                        <li class='text-primary-600'>
                                            <a  class='text-primary-400' onclick="used_in_production(`+row[0]+`,'`+escapeHtml(row[1])+`','`+escapeHtml(row[3])+`','`+escapeHtml(row[4])+`','`+(row[6])+`')" data-popup='tooltip' data-original-title='`+Translation('اضافة الطول المستخدم في الانتاج')+`'>
                                                <i class='icon-scissors'></i>
                                            </a>
                                        </li>
                                  `;
                                }
                              
                            

                            return  `<ul class='icons-list pull-right'>
                                      
                                        <li class='text-primary-600'>
                                            <a  class='text-primary-400' onclick="transfer_stock(`+row[0]+`,'`+escapeHtml(row[1])+`','`+escapeHtml(row[3])+`','`+escapeHtml(row[4])+`','`+(row[6])+`')" data-popup='tooltip' data-original-title='`+Translation('نقل الى مخزن اخر')+`'>
                                                <i class='icon-transmission'></i>
                                            </a>
                                        </li>
                                        
                                        `
                                        +btns+
                                        `
                                        

                                    </ul>`;
                        }
          },

          {
             "render": function(data, type, row){


                      return  `<a href='index.php?p=stock_detail&id=`+row[13]+`'  data-popup='tooltip' data-original-title='`+Translation('عرض جميع المواد التابعة لهذا المخزن')+`'>`+data+`</a>`;


             },
             "targets": 1
          },

          {
                "render": function(data, type, row){
                    var status ='';

                    if(data ==1){
                        status = '<span class="label label-success btn-block "><i class="icon-scissors"></i>'+Translation('انتاج')+'   </span>';
                    }else{
                        status = '<span class="label label-info btn-block "><i class="icon-store"></i> '+Translation('خزن')+'  </span>';
                    }
                    return status;
                },
                "targets": 2
            },

            {
             "render": function(data, type, row){


                      return  `<a href='index.php?p=stock_detail&pid=`+row[14]+`'  data-popup='tooltip' data-original-title='`+Translation('عرض تفاصيل هذه المادة في كل المخازن')+`'>`+data+`</a>`;


             },
             "targets": 3
          },

            {
                "render": function(data, type, row){
                    var status ='';

                    if(data ==0){
                        status = '<span class="btn-block text-center bg-success" style="word-wrap: break-word; border-radius: 6px;">'+Translation('متوفر في مخزن الخزن من دون تالف')+'  </span>';
                    }else if(data ==1){
                        status = '<span class="btn-block text-center bg-warning" style="word-wrap: break-word; border-radius: 6px;">'+Translation('مباع بالكامل')+'  </span>';
                    }else if(data ==2){
                        status = '<span class="btn-block text-center bg-info" style="word-wrap: break-word; border-radius: 6px;">'+Translation('متوفر في مخزن الانتاج /غير مستخدم من دون تالف')+' </span>';
                    }else if(data ==3){
                        status = '<span class="btn-block text-center bg-primary" style="word-wrap: break-word; border-radius: 6px;">'+Translation('استخدم في الانتاج')+'  </span>';
                    }else if(data ==4){
                        status = '<span class="btn-block text-center bg-teal-400" style="word-wrap: break-word; border-radius: 6px;">'+Translation('تم الانتاج وانتهت المادة')+'  </span>';
                    }else if(data ==5){
                        status = '<span class="btn-block text-center bg-orange-400" style="word-wrap: break-word; border-radius: 6px;">'+Translation('مباع بالتجزئة')+'  </span>';
                    }else if(data ==6){
                        status = '<span class="btn-block text-center bg-grey-400" style="word-wrap: break-word; border-radius: 6px;">'+Translation('تالف بالكامل')+'  </span>';
                    }else if(data ==7){
                        status = '<span class="btn-block text-center bg-slate-400" style="word-wrap: break-word; border-radius: 6px;">'+Translation('مسترجع')+'  </span>';
                    }else if(data ==8){
                        status = '<span class="btn-block text-center bg-pink-400" style="word-wrap: break-word; border-radius: 6px;">'+Translation('متوفر في مخزن الخزن ويحوي تالف')+'  </span>';
                    }else if(data ==9){
                        status = '<span class="btn-block text-center bg-brown-400" style="word-wrap: break-word; border-radius: 6px;">'+Translation('مباع بالتجزئة ومستخدم في الانتاج')+'  </span>';
                    }else if(data ==10){
                        status = '<span class="btn-block text-center bg-indigo-400" style="word-wrap: break-word; border-radius: 6px;">'+Translation('استخدم كليا (مباع بالتجزئة و مستخدم في الانتاج)')+'  </span>';
                    }else if(data ==11){
                        status = '<span class="btn-block text-center bg-purple-400" style="word-wrap: break-word; border-radius: 6px;">'+Translation('متوفر في مخزن الانتاج /غير مستخدم ويحتوي تالف')+'  </span>';
                    }
                    return status;
                },
                "targets": 12
            },
            
           
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {

            $("#total_cnt").text((aData[16]))
            $("#total_length").text((aData[15] - aData[20]) + " م")
            $("#total_used").text((aData[17]) + " م")
            $("#total_sold").text((aData[18]) + " م")
            $("#total_damages").text((aData[19]) + " م")
            var tot_rem = (aData[15] - aData[20] - aData[19] - aData[18] - aData[17] );
            $("#total_remaind").text( tot_rem.toFixed(2) + " م")
            


            if(   aData[4] == 0 ){
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('warning-active');
                });
            }
        },
        "order": [[0,'desc']],
                "displayLength": 25,
 

        initComplete: function () {
         
        // $("div.datatable-header").append(`<a  style="margin-left:15px;" class="btn bg-info-400"  id="headerBtn" onclick="add_item()"> <i class="icon-file-pdf position-right"></i> Add Category </a>`);   
         // $("div.datatable-header").append(`<a data-toggle="collapse"
         //                              style="margin-right:10px;"
         //                              data-target="#add-form-cont"
         //                              href="javascript:;"
         //                              aria-controls="add-form-cont"
         //                              aria-expanded="false"
         //                              class="btn btn-primary"
         //                              id="add_Item_Btn">
         //                                <i class="`+CURRENT_BTN_ICON+`"></i> `+CURRENT_BTN+`
         //                            </a>`); 
         $("div.datatable-header").append(`&nbsp;<div class="btn-group">
                                          <button type="button" 
                                          class="btn bg-teal-400 btn-labeled dropdown-toggle" 
                                          data-toggle="dropdown"><b><i class="icon-filter4">
                                          </i></b><span id="stock_btn">`+Translation('المخازن')+`</span>  <span class="caret"></span></button>
                                          <ul class="dropdown-menu dropdown-menu-right" id="stock_filter">
                                          </ul>
                                          </div>`); 

         $("div.datatable-header").append(`&nbsp;<div class="btn-group">
                                          <button type="button" id="status_color"
                                          class="btn bg-danger-400 btn-labeled dropdown-toggle" 
                                          data-toggle="dropdown"><b><i class="icon-filter4">
                                          </i></b><span id="status_btn">`+Translation('فلتر الحالة')+`</span>  <span class="caret"></span></button>
                                          <ul class="dropdown-menu dropdown-menu-right" id="status_filter">
                                          </ul>
                                          </div>`);

         $("div.datatable-header").append(` <div class="form-group">

                                                  <div class="col-sm-6">
                                                    <div class="input-group">
                                                      <label class="input-group-addon text-black text-danger-800">`+Translation('بحث عن مادة في جميع المخازن')+`</label>
                                                      <select onchange="search_Product();"  class="form-control  multi_lang" data-live-search="true" name="product_id_search" id="product_id_search" data-width="100%" placeholder="اسم المادة">
                                                    
                                                      </select>
                                                    </div>
                                                  </div>

                                                  <div class="input-group-btn">
                                                    <!--<button type="button" class="btn btn-info" onclick="select_all();" id="select-all-values">Select all</button> -->
                                                    <!--<button type="button" class="btn btn-default" onclick="deselect_all();" id="deselect-all-values">Deselect all</button>-->
                                                  

                                                    <button type="button" class="btn bg-pink-400 btn-labeled " onclick="show_detail_page();">
                                                      <b><i class="icon-search4"></i></b>
                                                      `+Translation('عرض تفاصيل هذه المادة في جميع المخازن')+`
                                                    </button>
                                                  </div>


                                            </div>`); 

            this.api().columns().every( function() {
                var column = this;
                // change_filter_btn_text();   

            });

                get_Stock(); 

        }
    });

    
    table.columns().every( function () {
        var that = this;
        $('input', this.footer()).on('keyup change', function () {
            that.search(this.value).draw();
        });
    });


    // Single row selection
    
    $('.datatable-column-search-inputs tbody').on('click', 'tr', function() {
        if ($(this).hasClass('success')) {
            $(this).removeClass('success');
        }
        else {
            table.$('tr.success').removeClass('success');
            $(this).addClass('success');
        }
    });


         // change filter to top
    $('.datatable-column-search-inputs tfoot tr').insertAfter($('.datatable-column-search-inputs thead tr'))


    $('.dataTables_length select').select2({
        minimumResultsForSearch: Infinity,
        width: 'auto'
    });


});



