var table ,  block = $(".content-wrapper").parent();

    function edit_items(itemid,itemName,erbilcode,turcode,barcode,notes,min_noty,cat){
      //$("#edit_category_id").html($("#category_id").html());
      itemName = decodeURIComponent_back(itemName);
      erbilcode = decodeURIComponent_back(erbilcode);
      turcode = decodeURIComponent_back(turcode);
      barcode = decodeURIComponent_back(barcode);
      notes = decodeURIComponent_back(notes);
      min_noty = decodeURIComponent_back(min_noty);
      
      
      $("#edit_objid").val(itemid);
      // $("#edit_category_id").val(cat);
      //$('#edit_category_id option[value='+cat+']').attr('selected','selected');
      // $('#edit_category_id').selectpicker('val',cat);
      // $('#edit_category_id').selectpicker('refresh');
      $("#edit_item_type_id").val(itemName);
      $("#edit_erbil_code").val(erbilcode);
      $("#edit_turkish_code").val(turcode);
      $("#edit_barcode").val(barcode);
      $("#edit_product_min_notification").val(min_noty);
      $("#edit_product_note").val(notes);
      
      $('#edit_form_cont').modal('toggle');

    }

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


              $.ajax({
                url: "models/crul_product.php",
                type:"POST",
                dataType : "JSON",
                data: {"type":"show_files","obj_id":itemid} ,
                complete:function(){
                  //hideLoader();
                },
                beforeSend:function(){
                  //showLoader("Deleting Product");
            },
                success: function(res) {
                  var attach =''             ;
                    for(var i=0 ; i < res.length;i++){

                      attach = attach + `
                      <div id="img_`+res[i][0]+`" >
                      <div class="col-lg-3 col-sm-6" >
                        <div class="thumbnail">
                          <div class="thumb">
                            <img src="`+res[i][1]+`" alt="">
                            <div class="caption-overflow">
                              <span>
                                <a href="`+res[i][1]+`" data-popup="lightbox" class="btn border-white text-white btn-flat btn-icon btn-rounded"><i class="icon-plus3"></i></a>
                                
                              </span>
                            </div>
                          </div>

                          <div class="caption">
                            <h6 class="no-margin"><a href="#" class="text-default">`+Translation('رقم الملف')+` : `+i+`</a> <a href="#" onclick="remove_image(`+res[i][0]+`,'`+res[i][1]+`');" class="text-muted"><i class="icon-trash text-danger pull-right"></i></a></h6>
                          </div>
                        </div>
                      </div>
                      </div>` ;


                    }
                    $("#file_attach").html(attach);
                    $('#show_files').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_product.php",
                type:"POST",
                dataType : "JSON",
                data: {"type":"delete","obj_id":itemid} ,
                complete:function(){
                  //hideLoader();
                },
                beforeSend:function(){
                  //showLoader("Deleting Product");
            },
                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
    }





    function remove_image(itemid,path) {
     
        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_product.php",
                type:"POST",
                dataType : "JSON",
                data: {"type":"remove_image","obj_id":itemid,img_path:path} ,
                complete:function(){
                  //hideLoader();
                },
                beforeSend:function(){
                  //showLoader("Deleting Product");
            },
                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);
                    $("#img_"+itemid).html('')
                  }else{
                    swal({
                                title: Translation("خطأ"),
                                text: Translation(res.data),
                                confirmButtonColor: "#2196F3",
                                type: "error"
                            });
                  }
                }
            });
            }
        }); // /confirm
    }



    function Checks(id,types=null,min=null,max=null){
        var name = $("#"+id).val();
        if(types == null){  // it mean string

              if(min !=null && max !=null){
                  if(name =='' || name.length < min || name.length > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter the Required Field with minimum length of "+ min + " and maximum length " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min !=null && max ==null){
                  if(name ==''  || name.length < min ){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter the Required Field with minimum length of "+ min ,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min ==null && max !=null){
                  if(name ==''  ||  name.length > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter the Required Field with  maximum length of " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else{

                  if(name ==''){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Field should not be empty",
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }

              }

        }else if(types == 'No'){  // it mean numbers

              if(min !=null && max !=null){
                  if(name !='' && isNaN(name) || name < min || name > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter Numeric Value between "+ min + " and " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min !=null && max ==null){
                  if(name !='' && isNaN(name) || name < min ){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter Numeric Value Greater than "+ min,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min ==null && max !=null){
                  if(name !='' && isNaN(name) ||  name > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter Numeric Value Less than " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else{

                  if(name !='' && isNaN(name)){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter Numeric Value",
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }

              }

        }
    }

    
    function hide_show_itm(itm,vals){

      $.ajax({
                      url : 'models/crul_product.php',
                      type : 'POST',
                      data : {
                              type:'hide_show_itm',
                              id  :itm,
                              vals:vals,

                              },
                      dataType : 'json',
                      success : function(res) {
                        if(res.is_success == true){
                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);

                         noty({
                                          width: 200,
                                          text: Translation(res.data), //'Product Successfully Update',
                                          type: 'success',
                                          dismissQueue: true,
                                          timeout: 3000,
                                          layout: 'topRight',
                                    });  
                          
                        }else{
                          swal({
                                      title: Translation("خطأ"),
                                      text: Translation(res.data),
                                      confirmButtonColor: "#2196F3",
                                      type: "error"
                                  });
                        }
                      },
                      complete: function() {
                             //  me.data('requestRunning', false);
                      }

                }); // submit ajax

    }
  

    function get_Category(){

      $.ajax({
                      url : 'models/crul_category.php',
                      type : 'POST',
                      data : {type:'get'},
                      dataType : 'json',
                      success : function(response) {
                        console.log(response)
                          var attach ='<option value="" selected="selected">'+Translation('اسم الفئة')+'</option>';
                          
                            for(var i=response.length-1 ; i >= 0;i--){
                              
                              attach = attach + '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                             

                            }
                            $("#category_id").html(attach);
                            $("#edit_category_id").html(attach);
                            $('#category_id').selectpicker('refresh');
                            // $("#edit_category_id").selectpicker('refresh');
                      },
                      complete: function() {
                             //  me.data('requestRunning', false);
                      }

                }); // submit ajax

    }


    function get_Items(){

      $.ajax({
                      url : 'models/crul_items.php',
                      type : 'POST',
                      data : {type:'get'},
                      dataType : 'json',
                      success : function(response) {
                        console.log(response)
                          var attach ='<option value="" selected="selected">'+Translation('اختيار الصنف')+'</option>';
                          
                            for(var i=response.length-1 ; i >= 0;i--){
                              
                              attach = attach + '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                             

                            }
                            $("#item_type_id").html(attach);
                            $("#edit_item_type_id").html(attach);
                            
                      },
                      complete: function() {
                             //  me.data('requestRunning', false);
                      }

                }); // submit ajax

    }

    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() {
  
    // get_Category();
    get_Items();

    $("#barcode").on("keypress", function (e) {
        if (e.keyCode == 13) {
          e.preventDefault();
          $("#product_min_notification").focus();
        }
    });


    $("#edit_barcode").on("keypress", function (e) {
        if (e.keyCode == 13) {
          e.preventDefault();
          $("#edit_product_min_notification").focus();
        }
    });


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

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

      // var category_id               = $("#category_id").val();
      var category_id               = 0;
      var item_type_id              = $("#item_type_id").val();
      var erbil_code                = $("#erbil_code").val();
      var turkish_code              = $("#turkish_code").val();
      var barcode                   = $("#barcode").val();
      var product_note              = $("#product_note").val();
      var product_min_notification  = $("#product_min_notification").val();



      var Check1 = true;
      var Check2 = true;
      var Check3 = true;
      var Check4 = true;
      var Check5 = true;
      var Check6 = true;

      // Check1 = Checks('category_id');
      Check2 = Checks('item_type_id');
      Check3 = Checks('erbil_code');
      Check4 = Checks('turkish_code');

      var formData = new FormData(this);
      formData.append("type", 'create');


      //Check5 = Checks('sell_price');
      //Check6 = Checks('sell_price_percentage');




      if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_product.php",
                type:"POST",
                dataType : "JSON",
                data:formData,
                cache:false,
                contentType: false,
                processData: false
                // data : {category_id:category_id,product_name:product_name,erbil_code:erbil_code,turkish_code:turkish_code,
                //   barcode:barcode,product_note:product_note,product_min_notification:product_min_notification,type:'create'}
            })
            .done(function(res) {
                //alert(res);
                if(res.is_success == true){

                    //$("#add_form")[0].reset();

                    // $("#product_name").val('');
                    $("#erbil_code").val('');
                    $("#turkish_code").val('');
                    $("#barcode").val('');
                    $("#product_note").val('');
                    $(".fileinput-remove-button").trigger('click');

                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    //$("#add-form-cont").collapse('hide');
                    noty({
                                    width: 200,
                                    text: Translation(res.data),
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 3000,
                                    layout: 'topRight',
                              });

                    
               
                }else{
                    swal({
                        title: Translation("خطأ"),
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                    //$("#add-form-cont").collapse('hide');
                }
                $("#submit_add_btn").attr('disabled',false);
            })
            .fail(function(err) {
                 swal({
                    title: Translation("خطأ"),
                    text: Translation(err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                $("#submit_add_btn").attr('disabled',false);
            })
            .always(function() {
                console.log("complete");
            });
        }

    });



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

              // var category_id               = $("#edit_category_id").val();
              var item_type_id              = $("#edit_item_type_id").val();
              var erbil_code                = $("#edit_erbil_code").val();
              var turkish_code              = $("#edit_turkish_code").val();
              var barcode                   = $("#edit_barcode").val();
              var product_min_notification  = $("#edit_product_min_notification").val();
              var product_note              = $("#edit_product_note").val();


              var catId    = $("#edit_objid").val();

              var Check1 = true;
              var Check2 = true;
              var Check3 = true;
              var Check4 = true;
              var Check5 = true;
              var Check6 = true;

              // Check1 = Checks('edit_category_id');
              Check2 = Checks('edit_item_type_id');
              Check3 = Checks('edit_erbil_code');
              Check4 = Checks('edit_turkish_code');

              if(product_min_notification !='' && isNaN(product_min_notification)){
                Check5=false;
                $("#edit_product_min_notification").closest('.form-group').removeClass('has-success');
                $("#edit_product_min_notification").closest('.form-group').addClass('has-error');

                 noty({
                          width: 200,
                          text: Translation("الرجاء قم بادخال قيمة عددية"),
                          type: 'error',
                          dismissQueue: true,
                          timeout: 3000,
                          layout: 'top',
                    });
              }else{
                $("#edit_product_min_notification").closest('.form-group').addClass('has-success');
                $("#edit_product_min_notification").closest('.form-group').removeClass('has-error');
              }

             
              //Check5 = Checks('sell_price');
              //Check6 = Checks('sell_price_percentage');

              var formData = new FormData(this);
              formData.append("type", 'update');


              if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){

                  $.ajax({
                      // url: "models/crul_product.php",
                      // type:"POST",
                      // dataType : "JSON",
                      // data : {category_id:0,item_type_id:item_type_id,erbil_code:erbil_code,turkish_code:turkish_code,
                      //   barcode:barcode,
                      //   product_min_notification:product_min_notification,
                      //   product_note:product_note,obj_id:catId,type:'update'}
                      url: "models/crul_product.php",
                      type:"POST",
                      dataType : "JSON",
                      data:formData,
                      cache:false,
                      contentType: false,
                      processData: false,
                      complete:function(){
                        //hideLoader();
                      },
                      beforeSend:function(){
                        //showLoader("Updating Product");
                      },
                      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_new_category_form').on('submit', function(e){

    e.preventDefault();

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

   var name        = $("#objname").val();
    var cat_desc    = $("#category_description").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: Translation("الرجاء قم بادخال اسم الفئة"),
                type: 'error',
                dismissQueue: true,
                timeout: 3000,
                layout: 'top',
          });
    }else{
       $("#objname").closest('.form-group').removeClass('has-error');
       $("#objname").closest('.form-group').addClass('has-success');
    }

  

    if(Check1 && Check2){
      $("#submit_add_cat_btn").attr('disabled',true);
        $.ajax({
            url: "models/crul_category.php",
            type:"POST",
            dataType : "JSON",
            data : {name:name,category_description:cat_desc,type:'create'}
        })
        .done(function(res) {
          //alert(res);
          if(res.is_success == true){
                  $("#add_new_category_form")[0].reset();
                  $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                  $('#add_new_category').modal('toggle');
                  $('#category_id').selectpicker('refresh');
                  get_Category();
              noty({
                              width: 200,
                              text: Translation(res.data),
                              type: 'success',
                              dismissQueue: true,
                              timeout: 3000,
                              layout: 'topRight',
                        });
          }else{
              swal({
                  title: Translation("خطأ"),
                  text: Translation(res.data),
                  confirmButtonColor: "#66BB6A",
                  type: "error"
              });
          }
          $("#submit_add_cat_btn").attr('disabled',false);
        })
        .fail(function(err) {
           swal({
              title:  Translation("خطأ"),
              text:   Translation(err),
              confirmButtonColor: "#66BB6A",
              type: "error"
            });
           $("#submit_add_cat_btn").attr('disabled',false);
        })
        .always(function() {
            console.log("complete");
        });
    }


});




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

   // Modal template
    var modalTemplate = '<div class="modal-dialog modal-lg" role="document">\n' +
        '  <div class="modal-content">\n' +
        '    <div class="modal-header">\n' +
        '      <div class="kv-zoom-actions btn-group">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
        '      <h6 class="modal-title">{heading} <small><span class="kv-zoom-title"></span></small></h6>\n' +
        '    </div>\n' +
        '    <div class="modal-body">\n' +
        '      <div class="floating-buttons btn-group"></div>\n' +
        '      <div class="kv-zoom-body file-zoom-content"></div>\n' + '{prev} {next}\n' +
        '    </div>\n' +
        '  </div>\n' +
        '</div>\n';

    // Buttons inside zoom modal
    var previewZoomButtonClasses = {
        toggleheader: 'btn btn-default btn-icon btn-xs btn-header-toggle',
        fullscreen: 'btn btn-default btn-icon btn-xs',
        borderless: 'btn btn-default btn-icon btn-xs',
        close: 'btn btn-default btn-icon btn-xs'
    };

    // Icons inside zoom modal classes
    var previewZoomButtonIcons = {
        prev: '<i class="icon-arrow-left32"></i>',
        next: '<i class="icon-arrow-right32"></i>',
        toggleheader: '<i class="icon-menu-open"></i>',
        fullscreen: '<i class="icon-screen-full"></i>',
        borderless: '<i class="icon-alignment-unalign"></i>',
        close: '<i class="icon-cross3"></i>'
    };

    // File actions
    var fileActionSettings = {
        zoomClass: 'btn btn-link btn-xs btn-icon',
        zoomIcon: '<i class="icon-zoomin3"></i>',
        dragClass: 'btn btn-link btn-xs btn-icon',
        dragIcon: '<i class="icon-three-bars"></i>',
        removeClass: 'btn btn-link btn-icon btn-xs',
        removeIcon: '<i class="icon-trash"></i>',
        indicatorNew: '<i class="icon-file-plus text-slate"></i>',
        indicatorSuccess: '<i class="icon-checkmark3 file-icon-large text-success"></i>',
        indicatorError: '<i class="icon-cross2 text-danger"></i>',
        indicatorLoading: '<i class="icon-spinner2 spinner text-muted"></i>'
    };




    //
    // AJAX upload
    //

    $(".file-input-ajax").fileinput({
        uploadUrl: "http://localhost", // server upload action
        uploadAsync: true,
        maxFileCount: 8,
        allowedFileExtensions: ["jpg", "gif", "png", "jpeg"],
          maxFileSize: 35000,
        initialPreview: [],
        fileActionSettings: {
            removeIcon: '<i class="icon-bin"></i>',
            removeClass: 'btn btn-link btn-xs btn-icon',
            uploadIcon: '<i class="icon-upload"></i>',
            uploadClass: 'btn btn-link btn-xs btn-icon',
            zoomIcon: '<i class="icon-zoomin3"></i>',
            zoomClass: 'btn btn-link btn-xs btn-icon',
            indicatorNew: '<i class="icon-file-plus text-slate"></i>',
            indicatorSuccess: '<i class="icon-checkmark3 file-icon-large text-success"></i>',
            indicatorError: '<i class="icon-cross2 text-danger"></i>',
            indicatorLoading: '<i class="icon-spinner2 spinner text-muted"></i>',
        },
        layoutTemplates: {
            icon: '<i class="icon-file-check"></i>',
            modal: modalTemplate
        },
        initialCaption: "No file selected",
        previewZoomButtonClasses: previewZoomButtonClasses,
        previewZoomButtonIcons: previewZoomButtonIcons
    });





   // end image uploader



   // Setting datatable defaults
    $.extend( $.fn.dataTable.defaults, {
        autoWidth: false,
        columnDefs: [{ 
            orderable: false,
            width: '100px',
            targets: [ 10 ]
        }],
        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_it = getQueryVariable("it");
   
  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,-1 ],
            [  '10', '25', '50', '100','All' ]
        ],

        "processing": true,
        "serverSide": true,
        "ajax": {
        "url" : "models/crul_product.php",
        "data": function(d){
          d.type = "load";
          if(query_id !='not'){
            d.id =query_id ;
          }
          if(query_it !='not'){
            d.it =query_it ;
          }
        }
        },
        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 btn =``;

                    if(row[6] == 1){
                      btn =`<li class='text-pink-600'>
                                <a  onclick="hide_show_itm('`+row[0]+`',${0})" class='text-danger-400' data-popup='tooltip' data-original-title='`+Translation('جعل المادة مرئية وتظهر في القوائم')+`'>
                                    <i class='icon-eye '></i>
                                </a>
                            </li>`;
                    }else{

                      btn =`<li class='text-pink-600'>
                                <a  onclick="hide_show_itm('`+row[0]+`',${1})" class='text-success-400' data-popup='tooltip' data-original-title='`+Translation('اخفاء المادة وعدم ضهورها في القوائم')+`'>
                                    <i class='icon-eye-blocked '></i>
                                </a>
                            </li>`;

                    }

                            return  `<ul class='icons-list pull-right'>
                                        <li class='text-pink-600'>
                                            <a  onclick="show_files('`+row[0]+`')" class='text-teal-400' data-popup='tooltip' data-original-title='`+Translation('عرض صور المادة')+`'>
                                                <i class='icon-images2 '></i>
                                            </a>
                                        </li>
                                        ${btn}
                                        <li class='text-primary-600'>
                                            <a  class='text-primary-400' onclick="edit_items(`+row[0]+`,'`+escapeHtml(row[9])+`','`+escapeHtml(row[2])+`','`+escapeHtml(row[3])+`','`+escapeHtml(row[4])+`','`+escapeHtml(row[5])+`','`+escapeHtml(row[10])+`','`+row[8]+`')" data-popup='tooltip' data-original-title='`+Translation('تعديل')+`'>
                                                <i class='icon-pencil7 '></i>
                                            </a>
                                        </li>

                                        <li class='text-danger-600'>
                                            <a  class='text-danger-400' onclick="delete_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('حذف')+`'>
                                                <i class='icon-trash '></i>
                                            </a>
                                        </li>

                                    </ul>`;
                        }
          },


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


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


            //    },
            //    "targets": 6
            // },

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


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


               },
               "targets": 1
            },
            
           
            
            
            {
                "render": function(data, type, row){
                   
                      if(data==1){
                          status = '<span class="label label-danger  btn-block btn-xs"> '+Translation('مخفي')+'</span>';
                      }else{
                          status = '<span class="label label-primary btn-block btn-xs"> '+Translation('مرئي')+'</span>';
                      }

                      return status;
                },
                "targets": 6
            },
            {
                "render": function(data, type, row){

                      if(data == null || data ==''){
                        
                        return  ` <img src="assets/images/placeholder.jpg" class="img-rounded img-lg">   </i>`;
                      }else{
                        return  ` <img src="`+data +`" class="img-rounded img-lg">   </i>`;

                      }
                   
                      
                   
                },
                "targets": 7
            }
            
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {


            if(   aData[9] == 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-left: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> `+Translation(CURRENT_BTN)+`
                                    </a>`);  


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

            });
        }
    });

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


});



