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

       $("#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) {

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

    function return_to_original(itemid) {
      
             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_return.php",
                              type:"POST",
                              dataType : "JSON",
                              data: {"type":"return_to_original","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) {

       $("#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>';
                      
                        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';
    }

$(document).ready(function() {

    

    $('#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();
            

            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_return.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_return&pid="+product_id+id_+sid_;
        }else{
          window.location="index.php?p=stock_return"+id_+sid_;
        }
    }

    function show_detail_page(){
        product_id = $("#product_id_search").val();
        if(product_id >0){
          window.location="index.php?p=stock_return&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_return.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": 8,
              "data": null,
              "render": function (data,type,row) {

                            var btns='';

                          

                                if(row[11]==1 ){
                                  btns=btns+`
                                        <li class='text-teal-600'>
                                            <a href='#' class='text-danger-400' onclick="return_to_original(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('اعادته الى نفس الطوب')+`'>
                                                <i class='icon-history'></i>
                                            </a>
                                        </li>
                                  `;
                                }

                                
                              
                            

                            return  `<ul class='icons-list pull-right'>
                                      
                                        <li class='text-primary-600'>
                                            <a href='#' class='text-primary-400' onclick="transfer_stock(`+row[0]+`)" 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[8]+`'  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[9]+`'  data-popup='tooltip' data-original-title='`+Translation('عرض تفاصيل هذه المادة في كل المخازن')+`'>`+data+`</a>`;


             },
             "targets": 3
          },

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

                    
                        status = '<span class="label label-info  ">'+Translation('مسترجع من الطوب ذو ID=')+data+' وطوله الكلي هو : ('+row[12]+') م  </span>';
                    
                    return status;
                },
                "targets": 6
            },

            {
                "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": 7
            },
            
           
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {


            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>
                                                  <button type="button" class="btn bg-purple-400 btn-labeled " onclick="show_detail_page();">
                                                    <b><i class="icon-search4"></i></b>
                                                    `+Translation('بحث عن هذه المادة في مخزن الاسترجاع')+`
                                                  </button>

                                            </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'
    });


});



