

    function get_Branch(){

                $.ajax({
                      url : 'models/crul_branch.php',
                      type : 'POST',
                      data : {type:'get'},
                      dataType : 'json',
                      success : function(response) {
                          var attach ='<option class="text-black text-danger-800" selected="selected" value="">'+Translation('اختيار الفرع')+'</option>';
                          
                          for(var i=response.length-1 ; i >= 0;i--){

                            var tp =response[i][2];
                              
                            attach = attach + '<option class="text-black text-danger-800" data-subtext="'+Translation('الموقع')+' : '+response[i]['location']+'" value="'+response[i]['branch_id']+'">'+response[i]['branch_name']+'</option>';
                              
                               
                              
                          }
                          $("#branch_id_fk").html(attach);
                          $('#branch_id_fk').selectpicker('refresh');

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

                }); // submit ajax

    }

$(document).ready(function() {
    
  get_Branch();
  $("#sub_role_id_fk").selectpicker('refresh')

         
   $('#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 branch_id_fk  = $("#branch_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_user.php",
                    type : "POST",
                    dataType: "JSON",
                    data : {  username      :username,
                              full_name     :full_name,
                              email         :email,
                              password      :password,
                              phone_number  :phone_number,
                              role_id       :role_id,
                              branch_id_fk  :branch_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 branch_id_fk  = $("#edit_branch_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,
                            branch_id_fk    :branch_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',
                                 });
         }
         
   });

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

         
         var user_roles       = $("#sub_role_id_fk").val();
         
         var catId             = $("#user_id").val();
         
         var Check1 = true;

       

        
         if(Check1){
               
                $.ajax({
                    url  : "models/crul_user.php",
                    type : "POST",
                    dataType: "JSON",
                    data : {user_roles:user_roles,
                            obj_id:catId,
                            type:'change_user_sub_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_sub_role").modal('toggle');
                  }else{
                      $("#edit_form_sub_role")[0].reset();
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                      $("#edit_sub_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(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 change_sub_roles(itemid) {

        $("#sub_role_id_fk").val('').selectpicker('refresh')

        $("#user_id").val(itemid);
     
        $.ajax({
                   url: "models/crul_user.php",
                   type:"POST",
                   dataType : "JSON",
                   data: {"type":"get_user_sub_roles","obj_id":itemid} ,
                   complete:function(){
                   },
                   beforeSend:function(){
                   },
                   success: function(res) {
                     if(res == 0){
                       noty({
                              width: 200,
                              text: Translation('can not get User Sub Roles.'),
                              type: 'error',
                              dismissQueue: true,
                              timeout: 3000,
                              layout: 'topRight',
                           });
                       
                     }else{

                      var ids =['','','','','','','','','','','','','','','','','','','','','','','','',
                          '','','','','','','','','','','','','','','','','','','','','','','',
                          '','','','','','','','','','','','','','','','','','','','','','','',
                          '','','','','','','','','','','','','','','','','','','','','','','',
                          '','','','','','','','','','','','','','','','','','','','','','','',
                          '','','','','','','','','','','','','','','','','','','','','','',''];

                        for(var i=0; i<res.length; i++){
                          ids[i] =  res[i][3];
                        }

                        $("#sub_role_id_fk").selectpicker('val',[ids[0],ids[1],ids[2],ids[3],ids[4],ids[5],ids[6],ids[7],ids[8],ids[9],               ids[10],                                                            ids[11],                                                            ids[12],                                                            ids[13],                                                            ids[14],                                                            ids[15],                                                            ids[16],                                                            ids[17],                                                            ids[18],                                                            ids[19],                                                            ids[20],                                                            ids[21],                                                            ids[22],                                                            ids[23],                                                            ids[24],                                                            ids[25],                                                            ids[26],                                                            ids[27],                                                            ids[28],                                                            ids[29],                                                            ids[30],                                                            ids[31],                                                            ids[32],                                                            ids[33],                                                            ids[34],                                                            ids[35],                                                            ids[36],                                                            ids[37],                                                            ids[38],                                                            ids[39],                                                            ids[40],                                                            ids[41],                                                            ids[42],                                                            ids[43],                                                            ids[44],                                                            ids[45],                                                            ids[46],                                                            ids[47],                                                            ids[48],                                                            ids[49],                                                            ids[50],                                                           ]);

                        $("#sub_role_id_fk").selectpicker('refresh')
                        
                       
                     }
                   }
        });
        
        $('#edit_sub_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_user.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": 10,
                             "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 icon-2x"></i>
                                                      </a>

                                                      
                                                   


                                                    <ul class='dropdown-menu dropdown-menu-right'>

                                                      <li class='text-primary-600'>
                                                          <a  class='text-primary-400' onclick="edit_items(`+row[0]+`,'`+escape(row[1])+`','`+escape(row[2])+`','`+escape(row[3])+`','`+escape(row[4])+`','`+row[10]+`')" data-popup='tooltip' data-original-title='`+Translation('تعديل')+`'>
                                                              <i class='icon-pencil7 icon-2x'></i>${Translation('Edit')}
                                                          </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-success' onclick="set_admin(`+row[0]+`,`+row[5]+`,`+row[7]+`)" data-popup='tooltip' data-original-title='`+Translation('Change Profile Type')+`'>
                                                              <i class=' icon-person icon-2x'></i>${Translation('Change Profile Type')}
                                                          </a>
                                                      </li>
                                                      <li class='text-danger-600'>
                                                          <a  class='text-primary' onclick="change_roles(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('Change Roles')+`'>
                                                              <i class='icon-tab icon-2x'></i>${Translation('Change Roles')}
                                                          </a>
                                                      </li>

                                                      <li class='text-danger-600'>
                                                          <a  class='text-teal' onclick="change_sub_roles(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('Change Report Roles')+`'>
                                                              <i class='icon-tab icon-2x'></i>`+Translation('Change Report Roles')+`
                                                          </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[8]==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": 8
                        },
                        {
                           "render": function(data, type, row){

                                 if(data==2){
                                    return  `<span class="bg-teal btn-block btn-xs"> Super Admin  </span>`;
                                 }else if(data==1){
                                    return  `<span class="bg-purple btn-block btn-xs"> Admin  </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": 5
                        },

                        {
                           "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": 7
                        },
                        
                        

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


});



