  var table 

 
  function edit_items(itemid){
    
    
    $("#edit_objid").val(itemid);
    

    $.ajax({
        url: "models/crul_branch.php",
        type:"POST",
        dataType : "JSON",
        data: {"type":"get_edit","obj_id":itemid} ,
        complete:function(){
        
        },
        beforeSend:function(){
         
        },
        success: function(res) {

          if(res.is_success == true){
              $("#edit_branch_name").val(res.data[0].branch_name);
              $("#edit_location").val(res.data[0].location);
              $("#edit_branch_address").val(res.data[0].branch_address);
              $("#edit_branch_phone").val(res.data[0].branch_phone);
              $("#edit_branch_email").val(res.data[0].branch_email);
             
              $('#edit_form_cont').modal('toggle');

          }else{

            swal({
                    title: Translation("خطأ"),
                    text: Translation(res.data),
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });

          }
          
        }
    });
    

  }





  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_branch.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
  }





   


  

$(document).ready(function() {
  
   




   

    $('#add_form').submit(function(event) {
      event.preventDefault();
            
      var branch_name              = $("#branch_name").val();
      var branch_phone             = $("#branch_phone").val();
      var branch_email             = $("#branch_email").val();
      var location                 = $("#location").val();
      var branch_address           = $("#branch_address").val();     
     


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

      

      
      Check2 = Checks('branch_name');
      Check3 = Checks('branch_phone');
      Check4 = Checks('location');
      Check5 = Checks('branch_address');
      
      var formData = new FormData(this);

      
      formData.append("type", 'create');



      if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_branch.php",
                type:"POST",
                dataType : "JSON",
                data:formData,
                cache:false,
                contentType: false,
                processData: false
            })
            .done(function(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: Translation("خطأ"),
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                    //$("#add-form-cont").collapse('hide');
                }
                $("#submit_add_btn").attr('disabled',false);
            })
            .fail(function(err) {
                $("#submit_add_btn").attr('disabled',false);
                 swal({
                    title: Translation("خطأ"),
                    text: (err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                
            })
            .always(function() {
                console.log("complete");
            });
        }

    });



    // submit editable Visa Application form
    $('#edit_form').submit(function(event) {
      event.preventDefault();
    

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

    
      Check2 = Checks('edit_branch_name');
      Check3 = Checks('edit_branch_phone');
      Check4 = Checks('edit_location');
      Check5 = Checks('edit_branch_address');
      

      var formData = new FormData(this);

              
      formData.append("type", 'update');


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

          $.ajax({
              url: "models/crul_branch.php",
              type:"POST",
              dataType : "JSON",
              data:formData,
              cache:false,
              contentType: false,
              processData: false,
              complete:function(){
                
              },
              beforeSend:function(){
                
              },
              success: function(res) {
                if(res.is_success == false){
                  
                  $('#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() {




    // 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': '&'+Left_Arraw+'arr;', 'previous': '&'+Right_Arraw+'arr;' }
        },
        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_tp = getQueryVariable("tp");
   
  var table = $('.datatable-column-search-inputs').DataTable({
        // rowReorder: {
        //     selector: 'tr'
        // },

        // fixedHeader: true,
        keys: {
            className: 'focus focus-success'
        },

        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_branch.php",
        "data": function(d){
          d.type = "load";
          if(query_id !='not'){
            d.id =query_id ;
          }
          if(query_tp !='not'){
            d.tp =query_tp ;
          }
        }
        },
        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: 0, visible: false }, // this is for original id and we will hide it and show noraml sequence
          
          // {     "targets": 1,
          //       "className":      'details-control',
          //       "orderable":      false,
          //       "data":           null,
          //       "defaultContent": '',
          //       "render": function(data, type, row){
                     
          //               return `<i class="icon-add text-success"></i>`; 
                   
          //       },
          //   },
          { 
              "targets": 7,
              "data": null,
              "render": function (data,type,row) {

                          if(IS_VIEW==0){
                          
                            return  `<ul class='icons-list text-center'>
                                        

                                        <li class='text-primary-600'>
                                            <a href='#' class='text-primary-400' onclick="edit_items(`+row[0]+`)" 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>`;
                        }else{
                          return '';
                        }
                    }
          },

            
        ],
        "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>`);   
          if(IS_VIEW==0){
            
            $("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>`); 
          }
        
 
          //   invoce_filter_btn_label(); 


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

    // high light row and column
    var lastIdx = null;
     
    $('.datatable-highlight tbody').on('mouseover', 'td', function() {
        var chk_inx =table.cell(this).index();
        if(chk_inx != undefined && chk_inx !=null && chk_inx !='' ){ // because child row
          var colIdx = table.cell(this).index().column;

          if (colIdx !== lastIdx) {
              $(table.cells().nodes()).removeClass('active');
              $(table.column(colIdx).nodes()).addClass('active');
          }
        }
        
    }).on('mouseleave', function() {
        $(table.cells().nodes()).removeClass('active');
    });

    // end highlight row and column

    //child row
    // Add event listener for opening and closing details
    $('.datatable-column-search-inputs tbody').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        
        var row = table.row( tr );
 
        if ( row.child.isShown() ) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
            $(this).html('<i class="icon-add text-success"></i>');
        }
        else {
            // Open this row
            row.child( format(row.data()) ).show();
            tr.addClass('shown');
            $(this).html('<i class="icon-subtract text-danger"></i>');

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


});



