

   

    function edit_items(itemid){
      
      
      $("#edit_objid").val(itemid);
      get_Zone();
      
      get_Sub_Zone();
      get_Quarter();
      get_Street();
      
      $.ajax({
          url: "models/crul_user.php",
          type:"POST",
          dataType : "JSON",
          data: {"type":"get_edit","obj_id":itemid} ,
          complete:function(){
            //hideLoader();
          },
          beforeSend:function(){
            //showLoader("Deleting Product");
          },
          success: function(res) {

            if(res.is_success == true){
                // console.log(res.data[0].product_name)
                $("#edit_city_id_fk").val(res.data[0].city_id_fk).selectpicker('refresh');
                $("#edit_zone_id_fk").val(res.data[0].zone_id_fk).selectpicker('refresh');
                $("#edit_team_leader_id_fk").val(res.data[0].team_leader_id_fk).selectpicker('refresh');
                $("#edit_supervisor_id_fk").val(res.data[0].supervisor_id_fk).selectpicker('refresh');

                $("#edit_username").val(res.data[0].username);
                $("#edit_full_name").val(res.data[0].full_name);
                $("#edit_email").val(res.data[0].email);
                $("#edit_phone_number").val(res.data[0].phone_number);
                $("#edit_supervisor_id_fk").val(res.data[0].supervisor_id_fk);
                $("#edit_team_leader_id_fk").val(res.data[0].team_leader_id_fk);
                $("#edit_zone_id_fk").val(res.data[0].zone_id_fk);
                $("#edit_city_id_fk").val(res.data[0].city_id_fk);
                $("#edit_sub_zone_id_fk").val(res.data[0].sub_zone_id_fk).selectpicker('refresh');
                $("#edit_quarter_id_fk").val(res.data[0].quarter_id_fk).selectpicker('refresh');
                $("#edit_street_id_fk").val(res.data[0].street_id_fk).selectpicker('refresh');
                

                $('#edit_form_cont').modal('toggle');

            }else{

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

            }
            
          }
      });
      

    }

    function get_City(){

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

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

                }); // submit ajax

    }

    function get_Zone(id=0){

      $.ajax({
                      url : 'models/crul_zone.php',
                      type : 'POST',
                      data : {

                            id:id,
                            type:'get_with_id'},
                      dataType : 'json',
                      success : function(response) {
                        console.log(response)
                          var attach ='<option value="" selected="selected">'+Translation('Select Zone')+'</option>';
                          
                            for(var i=response.length-1 ; i >= 0;i--){
                              
                              attach = attach + '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                             

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

                }); // submit ajax

    }

    function get_Sub_Zone(id=0){

      $.ajax({
                      url : 'models/crul_sub_zone.php',
                      type : 'POST',
                      data : {

                              id:id,
                              type:'get_with_id'},
                      dataType : 'json',
                      success : function(response) {
                        console.log(response)
                          var attach ='<option value="" selected="selected">'+Translation('Select Sub Zone')+'</option>';
                          
                            for(var i=response.length-1 ; i >= 0;i--){
                              
                              attach = attach + '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                             

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

                }); // submit ajax

    }

    function get_Quarter(id=0){

      $.ajax({
                      url : 'models/crul_quarter.php',
                      type : 'POST',
                      data : {

                              id:id,
                              type:'get_with_id'},
                      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>';
                             

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

                }); // submit ajax

    }

    function get_Street(id=0){

      $.ajax({
                      url : 'models/crul_street.php',
                      type : 'POST',
                      data : {

                              id:id,
                              type:'get_with_id'},
                      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>';
                             

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

                }); // submit ajax

    }

    function get_Team_leader(){

      $.ajax({
                      url : 'models/crul_user.php',
                      type : 'POST',
                      data : {type:'get_team_leader'},
                      dataType : 'json',
                      success : function(response) {
                        console.log(response)
                          var attach ='<option value="" selected="selected">'+Translation('Select Teamleader')+'</option>';
                          
                            for(var i=response.length-1 ; i >= 0;i--){
                              
                              attach = attach + `<option data-subtext="City: ${response[i].city_name} | Zone: ${response[i].zone_name}" value="${response[i].staff_id}">${response[i].full_name}</option>`;
                             

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

                }); // submit ajax

    }

    function get_Supervisor(){

      $.ajax({
              url : 'models/crul_user.php',
              type : 'POST',
              data : {type:'get_supervisor'},
              dataType : 'json',
              success : function(response) {
                console.log(response)
                  var attach ='<option value="" selected="selected">'+Translation('Select Supervisor')+'</option>';
                  
                    for(var i=response.length-1 ; i >= 0;i--){
                      
                      attach = attach + `<option data-subtext="City: ${response[i].city_name} | Zone: ${response[i].zone_name}" value="${response[i].staff_id}">${response[i].full_name}</option>`;
                     

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

            }); // submit ajax

    }

$(document).ready(function() {
    
  get_City();
  // get_Zone();
  get_Team_leader();
  get_Supervisor();

  $("#city_id_fk").on('change',function(e){    
      var ID   = $(this).val();
      get_Zone(ID);
  });

  $("#zone_id_fk").on('change',function(e){    
      var ID   = $(this).val();
      get_Sub_Zone(ID);
  });

  $("#sub_zone_id_fk").on('change',function(e){    
      var ID   = $(this).val();
      get_Quarter(ID);
  });

  $("#quarter_id_fk").on('change',function(e){    
      var ID   = $(this).val();
      get_Street(ID);
  });


  $("#edit_city_id_fk").on('change',function(e){    
      var ID   = $(this).val();
      get_Zone(ID);
  });

  $("#edit_zone_id_fk").on('change',function(e){    
      var ID   = $(this).val();
      get_Sub_Zone(ID);
  });

  $("#edit_sub_zone_id_fk").on('change',function(e){    
      var ID   = $(this).val();
      get_Quarter(ID);
  });

  $("#edit_quarter_id_fk").on('change',function(e){    
      var ID   = $(this).val();
      get_Street(ID);
  });
         
  $('#add_form').on('submit', function(e){
         e.preventDefault();

         
         var username           = $("#username").val();
         var full_name          = $("#full_name").val();
         var email              = $("#email").val();
         var password           = $("#password").val();
         var repassword         = $("#repassword").val();
         var phone_number       = $("#phone_number").val();
         var role_id            = 0; // $("#role_id").val();
         var city_id_fk         = $("#city_id_fk").val();
         var zone_id_fk         = $("#zone_id_fk").val();
         var sub_zone_id_fk     = $("#sub_zone_id_fk").val();
         var quarter_id_fk      = $("#quarter_id_fk").val();
         var street_id_fk       = $("#street_id_fk").val();
         var team_leader_id_fk  = $("#team_leader_id_fk").val();
         var supervisor_id_fk   = $("#supervisor_id_fk").val();

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

         Check1 = Checks('username');
         Check2 = Checks('full_name');
         Check3 = Checks('email');
         Check4 = Checks('password');
         Check5 = Checks('phone_number');
         // Check6 = Checks('branch_id_fk');

         if(password != repassword ){
            noty({
                     width: 200,
                     text: Translation('Passwords Does Not Matches!!'),
                     type: 'error',
                     dismissQueue: true,
                     timeout: 3000,
                     layout: 'top',
                  });
            Check4 = false;
         }

         if(password.length <6){
            noty({
                     width: 200,
                     text: Translation('Passwords Should Be at least 6 Characters!!'),
                     type: 'error',
                     dismissQueue: true,
                     timeout: 3000,
                     layout: 'top',
                  });
            Check4 = false;
         }

         if(username.length <3){
            noty({
                     width: 200,
                     text: Translation('UserName Should Be at least 3 Characters!!'),
                     type: 'error',
                     dismissQueue: true,
                     timeout: 3000,
                     layout: 'top',
                  });
            Check1 = false;
         }

         if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6 ){
              $("#submit_add_btn").attr('disabled',true);
               $.ajax({
                    url  : "models/crul_teamleader.php",
                    type : "POST",
                    dataType: "JSON",
                    data : {  username      :username,
                              full_name     :full_name,
                              email         :email,
                              password      :password,
                              phone_number  :phone_number,
                              role_id       :role_id,
                              city_id_fk    :city_id_fk,
                              zone_id_fk    :zone_id_fk,
                              sub_zone_id_fk:sub_zone_id_fk,
                              quarter_id_fk :quarter_id_fk,
                              street_id_fk    :street_id_fk,
                              team_leader_id_fk    :team_leader_id_fk,
                              supervisor_id_fk    :supervisor_id_fk,
                              repassword    :repassword,
                              type          :'create'}
                })
                .done(function(res) {
                  console.log(res);
                  if(res.is_success == false){
                      swal({
                          title: Translation("خطأ"),
                          text: Translation(res.data),
                          confirmButtonColor: "#66BB6A",
                          type: "warning"
                      });
                      $("#add-form-cont").collapse('hide');
                  }else{
                      $("#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',
                                });
                  }
                  $("#submit_add_btn").attr('disabled',false);
                })
                .fail(function(err) {
                   swal({
                      title: Translation("خطأ"),
                      text: (err),
                      confirmButtonColor: "#66BB6A",
                      type: "error"
                    });
                   $("#submit_add_btn").attr('disabled',false);
                })
                .always(function() {
                    console.log("complete");
                });

         }else{
               noty({
                                       width: 200,
                                       text: Translation('Enter Required Fields!!'),
                                       type: 'error',
                                       dismissQueue: true,
                                       timeout: 3000,
                                       layout: 'top',
                                 });
         } // if check
         
  });


  $('#edit_form').on('submit', function(e){
         
         e.preventDefault();

         var username      = $("#edit_username").val();
         var full_name     = $("#edit_full_name").val();
         var email         = $("#edit_email").val();
         var phone_number  = $("#edit_phone_number").val();
         var city_id_fk    = $("#edit_city_id_fk").val();

         var sub_zone_id_fk     = $("#edit_sub_zone_id_fk").val();
         var quarter_id_fk      = $("#edit_quarter_id_fk").val();
         var street_id_fk       = $("#edit_street_id_fk").val();

         var zone_id_fk         = $("#edit_zone_id_fk").val();
         var team_leader_id_fk  = $("#edit_team_leader_id_fk").val();
         var supervisor_id_fk   = $("#edit_supervisor_id_fk").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_username');
         Check2 = Checks('edit_full_name');
         Check3 = Checks('edit_email');
         Check5 = Checks('edit_phone_number');
         // Check6 = Checks('edit_branch_id_fk');
         
         if(username.length <3){
            noty({
                     width: 200,
                     text: Translation('UserName Should Be at least 3 Characters!!'),
                     type: 'error',
                     dismissQueue: true,
                     timeout: 3000,
                     layout: 'top',
                  });
            Check1 = false;
         }

         
         

         if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
     
               $.ajax({
                    url  : "models/crul_user.php",
                    type : "POST",
                    dataType: "JSON",
                    data : {username        :username,
                            full_name       :full_name,
                            email           :email,
                            phone_number    :phone_number,
                            
                            city_id_fk    :city_id_fk,
                            zone_id_fk    :zone_id_fk,
                            sub_zone_id_fk:sub_zone_id_fk,
                            quarter_id_fk :quarter_id_fk,
                            street_id_fk    :street_id_fk,

                            team_leader_id_fk    :team_leader_id_fk,
                            supervisor_id_fk    :supervisor_id_fk,
                            obj_id          :catId,
                            type            :'update'}
               })
                .done(function(res) {
                  console.log(res);
                  if(res.is_success == false){
                      swal({
                          title: Translation("خطأ"),
                          text: Translation(res.data),
                          confirmButtonColor: "#66BB6A",
                          type: "warning"
                      });
                      $("#edit_form_cont").modal('toggle');
                  }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),
                                      type: 'success',
                                      dismissQueue: true,
                                      timeout: 3000,
                                      layout: 'topRight',
                                });
                  }
                })
                .fail(function(err) {
                   swal({
                      title: Translation("خطأ"),
                      text: (err),
                      confirmButtonColor: "#66BB6A",
                      type: "error"
                    });
                })
                .always(function() {
                    console.log("complete");
                });
         }else{
               noty({
                                       width: 200,
                                       text: Translation('Enter Required Fields!!'),
                                       type: 'error',
                                       dismissQueue: true,
                                       timeout: 3000,
                                       layout: 'top',
                                 });
         }
         
  });




   $('#edit_formPass').on('submit', function(e){
         
         e.preventDefault();

         
         var password      = $("#edit_password").val();
         var repassword    = $("#edit_repassword").val();
         
         var catId         = $("#edit_objidPass").val();
         
         var Check1 = true;
         var Check2 = true;
         var Check3 = true;
         

         
         
         if(password !=repassword) {
            $("#edit_password").closest('.form-group').addClass('has-error');
            $("#edit_password").closest('.form-group').removeClass('has-success');
            $("#edit_repassword").closest('.form-group').addClass('has-error');
            $("#edit_repassword").closest('.form-group').removeClass('has-success');
            
            noty({
                     width: 200,
                     text: Translation("Passwords Does Not Match"),
                     type: 'error',
                     dismissQueue: true,
                     timeout: 3000,
                     layout: 'top',
               });
            Check3 = false;
         }else{
            $("#edit_password").closest('.form-group').removeClass('has-error');
            $("#edit_password").closest('.form-group').addClass('has-success');
            $("#edit_repassword").closest('.form-group').removeClass('has-error');
            $("#edit_repassword").closest('.form-group').addClass('has-success');

            Check3 = true;
         }

         Check1 = Checks('edit_password');
         Check2 = Checks('edit_repassword');

         if(password.length <6) {
            $("#edit_password").closest('.form-group').addClass('has-error');
            $("#edit_password").closest('.form-group').removeClass('has-success');
            $("#edit_repassword").closest('.form-group').addClass('has-error');
            $("#edit_repassword").closest('.form-group').removeClass('has-success');
            
            noty({
                     width: 200,
                     text: Translation("Passwords Length should be at least 6 Characters!!"),
                     type: 'error',
                     dismissQueue: true,
                     timeout: 3000,
                     layout: 'top',
               });
            Check3 = false;
         }

         
         

         if(Check1 && Check2  && Check3){
               
               $.ajax({
                    url  : "models/crul_user.php",
                    type : "POST",
                    dataType: "JSON",
                    data : {password:password,repassword:repassword,obj_id:catId,type:'change_password'}
                })
                .done(function(res) {
                  console.log(res);
                  if(res.is_success == false){
                      noty({
                                      width: 200,
                                      text: Translation(res.data),
                                      type: 'error',
                                      dismissQueue: true,
                                      timeout: 3000,
                                      layout: 'topRight',
                                });
                      $("#edit_form_cont1").modal('toggle');
                  }else{
                      $("#edit_formPass")[0].reset();
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                      $("#edit_form_cont1").modal('toggle');
                      noty({
                                      width: 200,
                                      text: Translation(res.data),
                                      type: 'success',
                                      dismissQueue: true,
                                      timeout: 3000,
                                      layout: 'topRight',
                                });
                  }
                })
                .fail(function(err) {
                   swal({
                      title: Translation("خطأ"),
                      text: Translation(err),
                      confirmButtonColor: "#66BB6A",
                      type: "error"
                    });
                })
                .always(function() {
                    console.log("complete");
                });


              
         }else{
               noty({
                                       width: 200,
                                       text: Translation('Check Your Credentials!!'),
                                       type: 'error',
                                       dismissQueue: true,
                                       timeout: 3000,
                                       layout: 'top',
                                 });
         }
         
   });


   $('#edit_form_profile').on('submit', function(e){
         
         e.preventDefault();

         
         var profile_type      = $("#profile_type").val();
         var is_view           = $("#permission_type").val();
         
         var catId             = $("#edit_objidProfile").val();
         
         var Check1 = true;
         


         Check1 = Checks('profile_type');
        
         
         

         if(Check1){
               
                $.ajax({
                    url  : "models/crul_user.php",
                    type : "POST",
                    dataType: "JSON",
                    data : {profile_type:profile_type,
                            is_view:is_view,
                            obj_id:catId,
                            type:'change_profile_type'}
                })
                .done(function(res) {
                  console.log(res);
                  if(res.is_success == false){
                      noty({
                                      width: 200,
                                      text: Translation(res.data),
                                      type: 'error',
                                      dismissQueue: true,
                                      timeout: 3000,
                                      layout: 'topRight',
                                });
                      $("#edit_profile").modal('toggle');
                  }else{
                      $("#edit_form_profile")[0].reset();
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                      $("#edit_profile").modal('toggle');
                      noty({
                                      width: 200,
                                      text: Translation(res.data),
                                      type: 'success',
                                      dismissQueue: true,
                                      timeout: 3000,
                                      layout: 'topRight',
                                });
                  }
                })
                .fail(function(err) {
                   swal({
                      title: Translation("خطأ"),
                      text: Translation(err),
                      confirmButtonColor: "#66BB6A",
                      type: "error"
                    });
                })
                .always(function() {
                    console.log("complete");
                });


              
         }else{
               noty({
                                       width: 200,
                                       text: Translation('Check Your Credentials!!'),
                                       type: 'error',
                                       dismissQueue: true,
                                       timeout: 3000,
                                       layout: 'top',
                                 });
         }
         
   });


   $('#edit_form_role').on('submit', function(e){
         
         e.preventDefault();

         
         var user_roles       = [];
         
         var catId             = $("#edit_objidrole").val();
         
         var Check1 = true;

         var items = $("select#user_role option");
         var i =0;
         $.each(items, function(index, elem){
            if ($(elem).is(":selected")){
                       user_roles[i] =$(elem).val();
                       i = +i + +1;
            }
         });

         console.log(user_roles);
        
         //return false;

        
         if(Check1){
               
                $.ajax({
                    url  : "models/crul_user.php",
                    type : "POST",
                    dataType: "JSON",
                    data : {user_roles:user_roles,obj_id:catId,type:'change_user_role'}
                })
                .done(function(res) {
                  console.log(res);
                  if(res.is_success == false){
                      noty({
                                      width: 200,
                                      text: Translation(res.data),
                                      type: 'error',
                                      dismissQueue: true,
                                      timeout: 3000,
                                      layout: 'topRight',
                                });
                      $("#edit_role").modal('toggle');
                  }else{
                      $("#edit_form_role")[0].reset();
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                      $("#edit_role").modal('toggle');
                      noty({
                                      width: 200,
                                      text: Translation(res.data),
                                      type: 'success',
                                      dismissQueue: true,
                                      timeout: 3000,
                                      layout: 'topRight',
                                });
                  }
                })
                .fail(function(err) {
                   swal({
                      title: Translation("خطأ"),
                      text: Translation(err),
                      confirmButtonColor: "#66BB6A",
                      type: "error"
                    });
                })
                .always(function() {
                    console.log("complete");
                });


              
         }else{
               noty({
                                       width: 200,
                                       text: Translation('Check Your Credentials!!'),
                                       type: 'error',
                                       dismissQueue: true,
                                       timeout: 3000,
                                       layout: 'top',
                                 });
         }
         
   });

});


   function Checks(id){
      var name = $("#"+id).val();
      if(name =='') {
            $("#"+id).closest('.form-group').removeClass('has-success');
            $("#"+id).closest('.form-group').addClass('has-error');
            
            noty({
                     width: 200,
                     text: Translation("Please Enter the Required Fields"),
                     type: 'error',
                     dismissQueue: true,
                     timeout: 3000,
                     layout: 'top',
               });
            return false;
         }else{
            $("#"+id).closest('.form-group').removeClass('has-error');
            $("#"+id).closest('.form-group').addClass('has-success');
            return true;
         }

   }

   function edit_items_old(itemid,itemName,fulname,email,phone,branch_id){
      itemName = decodeURIComponent(itemName);
      fulname = decodeURIComponent(fulname);
      email = decodeURIComponent(email);
      phone = decodeURIComponent(phone);

      $('#edit_branch_id_fk').val(branch_id).selectpicker('refresh');


      $("#edit_objid").val(itemid);
      $("#edit_username").val(itemName);
      $("#edit_full_name").val(fulname);
      $("#edit_email").val(email);
      $("#edit_phone_number").val(phone);

      $('#edit_form_cont').modal('toggle');
   }

   


   function change_password(itemid,itemName){
      
      $("#edit_objidPass").val(itemid);

      $('#edit_form_cont1').modal('toggle');
   }


   function deactive_items(itemid) {
      block = $("#list_of_items_tbl");
         // bootstrap modal confirmation box
           swal({
               title: Translation("هل انت متأكد؟!"),
               text: Translation("You will deactivate this user!"),
               type: "warning",
               showCancelButton: true,
               confirmButtonColor: "#EF5350",
               confirmButtonText: Translation("Yes, De-Activate it!"),
               cancelButtonText: Translation("الغاء الامر"),
               closeOnConfirm: false,
               closeOnCancel: true
           },
           function(isConfirm){
               if (isConfirm) {
                 $.ajax({
                   url: "models/crul_user.php",
                   type:"POST",
                   dataType: "JSON",
                   data: {"type":"deactive","obj_id":itemid} ,
                   complete:function(){
                    // hideLoader();
                   },
                   beforeSend:function(){
                    // showLoader("Deleting Category");
                   },
                   success: function(res) {

                      if(res.is_success == true){
                       
                       $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                          swal({
                                   title: Translation("تمت العملية"),
                                   text: Translation(res.data),
                                   confirmButtonColor: "#2196F3",
                                   type: "success"
                               });
                      }else{
                          swal({
                                   title: Translation("خطأ"),
                                   text: Translation(res.data),
                                   confirmButtonColor: "#2196F3",
                                   type: "error"
                               });
                      }
                     
                   }
               });
               }
           }); // /confirm
   }


   function active_items(itemid) {
      block = $("#list_of_items_tbl");
         // bootstrap modal confirmation box
           swal({
               title: Translation("هل انت متأكد؟!"),
               text: Translation("You will Activate this user!"),
               type: "warning",
               showCancelButton: true,
               confirmButtonColor: "#EF5350",
               confirmButtonText: Translation("Yes, Activate it!"),
               cancelButtonText: Translation("الغاء الامر"),
               closeOnConfirm: false,
               closeOnCancel: true
           },
           function(isConfirm){
               if (isConfirm) {
                 $.ajax({
                   url: "models/crul_user.php",
                   type:"POST",
                   dataType: "JSON",
                   data: {"type":"active","obj_id":itemid} ,
                   complete:function(){
                    // hideLoader();
                   },
                   beforeSend:function(){
                    // showLoader("Deleting Category");
                   },
                   success: function(res) {
                     if(res.is_success == true){
                       
                       $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                          swal({
                                   title: Translation("تمت العملية"),
                                   text: Translation(res.data),
                                   confirmButtonColor: "#2196F3",
                                   type: "success"
                               });
                      }else{
                          swal({
                                   title: Translation("خطأ"),
                                   text: Translation(res.data),
                                   confirmButtonColor: "#2196F3",
                                   type: "error"
                               });
                      }
                   }
               });
               }
           }); // /confirm
   }

   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_user.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){
                       
                       $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                       swal({
                                   title: Translation("تم الحذف"),
                                   text: Translation(res.data),
                                   confirmButtonColor: "#2196F3",
                                   type: "success"
                               });
                     }else{
                       swal({
                                   title: Translation("خطأ"),
                                   text: Translation(res.data),
                                   confirmButtonColor: "#2196F3",
                                   type: "error"
                               });
                     }
                   }
               });
               }
           }); // /confirm
   }


   function set_admin(itemid,prof,perm) {
     $("#edit_objidProfile").val(itemid);
     $("#profile_type").val(prof);
     $("#permission_type").val(perm);


     $('#edit_profile').modal('toggle');
   }

   function change_roles(itemid) {
         $("#edit_objidrole").val(itemid);
     
         $.ajax({
                   url: "models/crul_user.php",
                   type:"POST",
                   dataType : "JSON",
                   data: {"type":"get_roles","obj_id":itemid} ,
                   complete:function(){
                    // hideLoader();
                   },
                   beforeSend:function(){
                    // showLoader("Deleting Category");
                   },
                   success: function(res) {
                     if(res == 0){
                       noty({
                              width: 200,
                              text: Translation('can not get roles.'),
                              type: 'error',
                              dismissQueue: true,
                              timeout: 3000,
                              layout: 'topRight',
                           });
                       
                     }else{
                        console.log(res)
                        $.ajax({
                                  url: "models/crul_user.php",
                                  type:"POST",
                                  dataType : "JSON",
                                  data: {"type":"get_user_roles","obj_id":itemid} ,
                                  success: function(res1) {
                                    if(res1 == 'Not'){
                                      noty({
                                             width: 200,
                                             text: Translation('Can not get User roles.'),
                                             type: 'error',
                                             dismissQueue: true,
                                             timeout: 3000,
                                             layout: 'topRight',
                                          });
                                      
                                    }else{
                                       // console.log(res1)
                                       var role_opt ='';
                                       if(res1.length == 0){
                                          for(var i=0 ; i< res.length; i++){
                                                role_opt = role_opt + `<option value="`+res[i][0]+`">`+Translation(res[i][1])+`</option>`;
                                          }
                                       }else{
                                          
                                          for(var i=0 ; i< res.length; i++){
                                             
                                             var role = res[i][0];
                                             var OK = 'Not';
                                             for(var j=0 ; j< res1.length; j++){
                                                var userRole = res1[j][2];
                                                if(role == userRole){
                                                   OK = 'ok';
                                                }

                                             }

                                             if(OK == 'ok'){
                                                role_opt = role_opt + `<option value="`+res[i][0]+`" selected="selected">`+Translation(res[i][1])+`</option>`;
                                             }else{
                                                role_opt = role_opt + `<option value="`+res[i][0]+`">`+Translation(res[i][1])+`</option>`;
                                             }

                                          }

                                       }
                                       

                                      $("#user_role").html(role_opt);
                                      $('.listbox-no-selection').bootstrapDualListbox({
                                            preserveSelectionOnMove: 'moved',
                                            moveOnSelect: false
                                        });
                                      $('.listbox-no-selection').bootstrapDualListbox('refresh', true);
                                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                                    }
                                  }
                              });
                       
                     }
                   }
         });

         $('#edit_role').modal('toggle');
   }

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




   // 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': '&rarr;', 'previous': '&larr;' }
        },
        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 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_teamleader.php",
        "data": function(d){
          d.type = "load";
        }
        },
        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": 11,
                             "data": null,
                             "render": function (data,type,row) {
                                    
                                  if(IS_VIEW ==0){


                                    var status=  `<ul class="icons-list">
                                                    <li class="dropdown">
                                                      <a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                        <i class="icon-menu9"></i>
                                                      </a>

                                                      
                                                   


                                                    <ul class='dropdown-menu dropdown-menu-right'>
                                                      <li class='text-primary-600'>
                                                          <a  class='text-primary-400' onclick="edit_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('تعديل')+`'>
                                                              <i class='icon-pencil7 icon-2x'></i>`+Translation('تعديل')+`
                                                          </a>
                                                      </li>
                                                      <li class='text-danger-600'>
                                                          <a  class='text-info-400' onclick="change_password(`+row[0]+`,'`+row[1]+`')" data-popup='tooltip' data-original-title='Change Password' title='`+Translation('Change Password')+`'>
                                                              <i class='icon-key icon-2x'></i>`+Translation('Change Password')+`
                                                          </a>
                                                      </li>
                                                     
                                                      <li class='text-danger-600'>
                                                          <a  class='text-danger' onclick="delete_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('Delete User')+`'>
                                                              <i class='icon-trash icon-2x'></i> `+Translation('Delete User')+`
                                                          </a>
                                                      </li>`;

                                    // if(row[10]==0){
                                    //    status= status + `<li class='text-danger-600'>
                                    //                       <a  class='text-warning' onclick="deactive_items(`+row[0]+`,'`+row[1]+`')" data-popup='tooltip' data-original-title='`+Translation('De-Activate User')+`'>
                                    //                           <i class='icon-user-block icon-2x'></i>`+Translation('De-Activate User')+`
                                    //                       </a>
                                    //                   </li>`;
                                    // }else{
                                    //    status=status +`<li class='text-danger-600'>
                                    //                       <a  class='text-info-400' onclick="active_items(`+row[0]+`,'`+row[1]+`')" data-popup='tooltip' data-original-title='`+Translation('Activate User')+`'>
                                    //                           <i class='icon-user-check icon-2x'></i>`+Translation('Activate User')+`
                                    //                       </a>
                                    //                   </li>`;
                                    // }

                                    
                                   
                                    status = status + `</ul>
                                                       </li>
                                                  </ul>`;

                                  }else{
                                    
                                    var status = "";
                                  }

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

                        //          if(data==0){
                        //             return  `<span class="bg-green btn-block btn-xs">`+Translation('Active')+`</span>`;
                        //          }else{
                        //             return  `<span class="bg-danger-600 btn-block btn-xs">`+Translation('De-active')+`</span>`;
                        //          }

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

                                 if(data==5){
                                    return  `<span class="bg-teal btn-block btn-xs"> Super Admin  </span>`;
                                 }else if(data==4){
                                    return  `<span class="bg-success btn-block btn-xs">Admin</span>`;
                                 }else if(data==3){
                                    return  `<span class="bg-pink btn-block btn-xs">Supervisor</span>`;
                                 }else if(data==2){
                                    return  `<span class="bg-blue btn-block btn-xs">Teamleader</span>`;
                                 }else if(data==1){
                                    return  `<span class="bg-purple btn-block btn-xs">SaleMan</span>`;
                                 }else if(data==0){
                                    return  `<span class="bg-orange-600 btn-block btn-xs">Staff</span>`;
                                 
                                 }else{
                                    return  `<span class="bg-gray-600 btn-block btn-xs"> un-known  </span>`;
                                 }

                           },
                           "targets": 4
                        },

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

                        //          if(data==1){
                        //             return  `<span class="bg-info btn-block btn-xs"> Just View  </span>`;
                        //          }else{
                        //             return  `<span class="bg-success-600 btn-block btn-xs"> Add, Edit, Delete  </span>`;
                        //          }

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

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


            if(   aData[8] == 1 ){
                $(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>`);
                }  


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


});



