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

    function edit_items(itemid,itemName,dec,price,notes){
      //$("#edit_category_id").html($("#category_id").html());
      itemName = decodeURIComponent_back(itemName);
      dec     = decodeURIComponent_back(dec);
      price = decodeURIComponent_back(price);
      notes = decodeURIComponent_back(notes);
      
      
      $("#edit_objid").val(itemid);
      $("#edit_other_name").val(itemName);
      
      $("#edit_other_description").val(dec);
      $("#edit_other_buy_price_per_unit").val(price);
      $("#edit_other_note").val(notes);
      
      $('#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_others.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 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 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 other_name                = $("#other_name").val();
      var other_description         = $("#other_description").val();
      var other_buy_price_per_unit  = $("#other_buy_price_per_unit").val();
      var other_note                = $("#other_note").val();
      

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

      Check1 = Checks('other_name');
      Check2 = Checks('other_buy_price_per_unit');
      
      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_others.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();

                    

                    $(".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:"Error",
                        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 other_name                = $("#edit_other_name").val();
              var other_description         = $("#edit_other_description").val();
              var other_buy_price_per_unit  = $("#edit_other_buy_price_per_unit").val();
              var other_note                = $("#edit_other_note").val();
              

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

              Check1 = Checks('edit_other_name');
              Check2 = Checks('edit_other_buy_price_per_unit');

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

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

             

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

                  $.ajax({
                      url: "models/crul_others.php",
                      type:"POST",
                      dataType : "JSON",
                      data : {other_name:other_name,
                              other_description:other_description,
                              other_buy_price_per_unit:other_buy_price_per_unit,
                              other_note:other_note,
                              obj_id:catId,type:'update'},
                      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',
                                    });
                        }
                      }
                  });
                }
      });

});






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

    $(".touchspin-basic").TouchSpin({
        min: 1,
        max: 1000000,
        step: 1
    });

  $('.daterange-single').daterangepicker({ 
        singleDatePicker: true,
        locale: {
            format: 'YYYY-MM-DD'
        }
    });

   // for image uploader

  



    //
    // AJAX upload
    //





   // 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 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_others.php",
        "data": function(d){
          d.type = "load";
          if(query_id !='not'){
            d.id =query_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": 5,
              "data": null,
              "render": function (data,type,row) {

                            return  `<ul class='icons-list pull-right'>
                                        

                                        <li class='text-primary-600'>
                                            <a href='#' class='text-primary-400' onclick="edit_items(`+row[0]+`,'`+escapeHtml(row[1])+`','`+escapeHtml(row[2])+`','`+escapeHtml(row[3])+`','`+escapeHtml(row[4])+`')" data-popup='tooltip' data-original-title='`+Translation('تحرير')+`'>
                                                <i class='icon-pencil7'></i>
                                            </a>
                                        </li>

                                        <li class='text-danger-600'>
                                            <a href='#' 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  currency_format_display(data);
                        

               },
               "targets": 3
            },

           
            
           
            
            
           
            
            
        ],
        "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-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> `+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'
    });


});



