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

    function save_items(itemid,lang_id,lang_keyword_id){
      
      var translated_word          = $("#translated_"+itemid).val();
      var key_word                 = $("#key_word_"+itemid).val();
      var key_word_original        = $("#key_word_"+itemid).attr('data-original-keyword');
     
      var Check1 = true;
      var Check2 = true;

      Check1 =Checks('translated_'+itemid);
      Check2 =Checks('key_word_'+itemid);

      if(Check1 && Check2){


            $.ajax({
                url: "models/crul_translation.php",
                type:"POST",
                dataType : "JSON",
                data : {keyword_id:itemid,lang_id:lang_id,translated_word:translated_word,
                        key_word:key_word,key_word_original:key_word_original,lang_keyword_id:lang_keyword_id,type:'save_single'}
                
            })
            .done(function(res) {
                //alert(res);
                if(res.is_success == true){

                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                   
                    noty({
                                    width: 200,
                                    text:  Translation(res.data),
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 3000,
                                    layout: 'topRight',
                              });
                }else{
                    swal({
                        title: Translation("خطأ"),
                        text:  Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                }
            })
            .fail(function(err) {
                 swal({
                    title: Translation("خطأ"),
                    text: Translation(err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
            })
            .always(function() {
                console.log("complete");
            });

      }

    }

   


    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: true,
            closeOnCancel: true
        },
        function(isConfirm){
            if (isConfirm) {
              $.ajax({
                url: "models/crul_translation.php",
                type:"POST",
                dataType : "JSON",
                data: {"type":"delete","obj_id":itemid} ,
                complete:function(){
                  //hideLoader();
                },
                beforeSend:function(){
                  //showLoader("Deleting Product");
            },
                success: function(res) {
                  if(res.is_success == true){
                    swal({
                                title: Translation("تم الحذف!"),
                                text: Translation(res.data),
                                confirmButtonColor: "#66BB6A",
                                type: "success"
                            });
                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                  }else{
                    swal({
                                title: Translation("خطأ"),
                                text: Translation(res.data),
                                confirmButtonColor: "#2196F3",
                                type: "error"
                            });
                  }
                }
            });
            }
        }); // /confirm
    }



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

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

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

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

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

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

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

              }

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

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

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

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

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

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

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

              }

        }
    }

    

  

     function get_Language(){

            $.ajax({
                  url : 'models/crul_languages.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='';
                        for(var i=response.length-1 ; i >= 0;i--){
                          
                          
                            attach = attach + '<li><a href="index.php?p=translation&id='+response[i][0]+'"><i class="icon-earth  text-success"></i> '+response[i][1]+'</a></li>';
                          
                           
                          
                        }
                        $("#languages_filter").html(attach);
                        
                        
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

    }

    function getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
          return pair[1];
        }
      }
      return 'not';
    }


$(document).ready(function() {
  
    // get_Profile_price();

   

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

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

      var keyword          = $("#keyword").val();
     
     



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

      Check1 = Checks('keyword');
      

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

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

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

                    

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

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

    });



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

              var profile_name          = $("#edit_profile_name").val();
              var profile_description   = $("#edit_profile_description").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_profile_name');
              Check2 = Checks('edit_profile_description');
              // Check3 = Checks('edit_is_have_purchase');
              // Check4 = Checks('edit_is_other');
              // // Check5 = Checks('edit_expenses_currency');

            

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

                  $.ajax({
                      url: "models/crul_profile_price.php",
                      type:"POST",
                      dataType : "JSON",
                      data : {profile_name:profile_name,profile_description:profile_description,
                              obj_id:catId,type:'update'},
                      complete:function(){
                        //hideLoader();
                      },
                      beforeSend:function(){
                        //showLoader("Updating Product");
                      },
                      success: function(res) {
                        if(res.is_success == false){
                          $("#edit-form-cont").collapse('hide');
                          $('#edit_form_cont').modal('toggle');
                          $("#edit_form")[0].reset();
                          swal({
                              title:"Not Success",
                              text: res.data,
                              confirmButtonColor: "#66BB6A",
                              type: "warning"
                          });
                        }else{
                          $("#edit_form")[0].reset();
                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);

                          $('#edit_form_cont').modal('toggle');
                          noty({
                                          width: 200,
                                          text: res.data, //'Product Successfully Update',
                                          type: 'success',
                                          dismissQueue: true,
                                          timeout: 3000,
                                          layout: 'topRight',
                                    });
                        }
                      }
                  });
                }
      });

});


$('#add_new_category_form').on('submit', function(e){

      e.preventDefault();

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

      var name                 = $("#objname").val();
      var group_description    = $("#group_description").val();

      var Check1 = true;
      var Check2 = true;

      if(name =='') {
         $("#objname").closest('.form-group').removeClass('has-success');
         $("#objname").closest('.form-group').addClass('has-error');
         Check1 = false;
         noty({
                  width: 200,
                  text: "Please Enter the Category Name",
                  type: 'error',
                  dismissQueue: true,
                  timeout: 3000,
                  layout: 'top',
            });
      }else{
         $("#objname").closest('.form-group').removeClass('has-error');
         $("#objname").closest('.form-group').addClass('has-success');
      }

    

      if(Check1 && Check2){
        $("#submit_add_cat_btn").attr('disabled',true);
          $.ajax({
              url: "models/crul_expenses_group.php",
              type:"POST",
              dataType:"JSON",
              data : {name:name,group_description:group_description,type:'create'}
          })
          .done(function(res) {
              //alert(res);
              if(res.is_success == true){
                  get_Expenses_Group();
                  noty({
                                  width: 200,
                                  text: res.data,
                                  type: 'success',
                                  dismissQueue: true,
                                  timeout: 3000,
                                  layout: 'topRight',
                            });
                  $('#add_new_category').modal('toggle');
              }else{
                  swal({
                      title: "Error",
                      text: "Detail:"+res.data,
                      confirmButtonColor: "#66BB6A",
                      type: "error"
                  });
              }
              $("#submit_add_cat_btn").attr('disabled',false);
          })
          .fail(function(err) {
               swal({
                  title: "Error",
                  text: "Detail:"+err,
                  confirmButtonColor: "#66BB6A",
                  type: "error"
              });
               $("#submit_add_cat_btn").attr('disabled',false);
          })
          .always(function() {
              console.log("complete");
          });
      }

});

function runScript(e,itemid,lang_id,lang_keyword_id) {
    if (e.keyCode == 13) {
        save_items(itemid,lang_id,lang_keyword_id)
        // alert('OK');
    }
}


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

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

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

   


   // Setting datatable defaults
    $.extend( $.fn.dataTable.defaults, {
        autoWidth: false,
        columnDefs: [{ 
            orderable: false,
            width: '100px',
            targets: [ 10 ]
        }],
        dom: '<"datatable-header"fBl><"datatable-scroll"t><"datatable-footer"ip>',
        language: {
            search: '<span>'+Translation('بحث')+':</span> _INPUT_',
            searchPlaceholder: Translation('بحث عن')+'...',
            lengthMenu: '<span>'+Translation('عرض')+':</span> _MENU_',
            paginate: { 'first': 'First', 'last': 'Last', 'next': '&larr;', 'previous': '&rarr;' }
        },
        drawCallback: function () {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
        },
        preDrawCallback: function() {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
        }
    });


    

    // Individual column searching with text inputs
    $('.datatable-column-search-inputs tfoot td').not(':last-child').each(function () {
        var title = $('.datatable-column-search-inputs thead th').eq($(this).index()).text();
        $(this).html('<input type="text" class="form-control input-sm" placeholder="'+Translation('بحث عن')+' '+title+'" />');
    });
    
    
  var query_id = getQueryVariable("id");

  
  var table = $('.datatable-column-search-inputs').DataTable({
        
        buttons: {            
            buttons: [
                {
                    extend: 'copyHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: [ 0, ':visible' ]
                    }
                },
                {
                    extend: 'excelHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'pdfHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'print',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'colvis',
                    text: '<i class="icon-three-bars"></i> <span class="caret"></span>',
                    className: 'btn bg-blue btn-icon'
                }
                
                
                
            ]
        },
        lengthMenu: [
            [  10, 25, 50, 100,-1 ],
            [  '10', '25', '50', '100','All' ]
        ],

        "processing": true,
        "serverSide": true,
        "ajax": {
        "url" : "models/crul_translation.php",
        "data": function(d){
          d.type = "load";
          if(query_id !='not'){
            d.id =query_id ;
          }
        }
        },
        drawCallback: function() {
                  $('[data-popup=tooltip]').tooltip();
                  $('[data-popup=popover-custom]').popover({
                    template: '<div class="popover  border-teal-400"><div class="arrow"></div><h3 class="popover-title bg-teal-400"></h3><div class="popover-content"></div></div>'
                  });

            },
        "columnDefs": [
          {
              "targets": 6,
              "data": null,
              "render": function (data,type,row) {

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

                                        <li class='text-primary-600'>
                                            <button  class='btn btn-primary' onclick="save_items(`+row[0]+`,`+row[6]+`,`+row[7]+`)" data-popup='tooltip' data-original-title='`+Translation('حفظ')+`'>
                                                <i class='icon-floppy-disk'></i>
                                                <i id="icon_`+row[0]+`" class=""></i>
                                            </button>
                                        </li>

                                        <li class='text-danger-600'>
                                             <button  class='btn btn-danger' onclick="delete_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('حذف الكلمة الدلالية')+`'>
                                                <i class='icon-trash'></i>
                                                <i id="icon_`+row[0]+`" class=""></i>
                                            </button>

                                            
                                        </li>

                                    </ul>`;
                        }
          },


           

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


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


             },
             "targets": 3
          },

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

                    if (data =='' || data ==null) {
                      class1 = 'has-warning';
                      class2 = 'icon-notification2';
                    }else if(data  < 0){
                      class1 = 'has-error';
                      class2 = 'icon-cancel-circle2';
                    }else{
                      class1 = 'has-success';
                      class2 = 'icon-checkmark-circle';
                    }

                      return  `
                                <div class="col-lg-12 `+class1+`">
                                  <div class="input-group">
                                   <!-- <input type="text" id="key_word_`+row[0]+`" name="key_word_`+row[0]+`" data-original-keyword="`+data+`" class="form-control" placeholder="`+Translation('الكلمة الدلالية')+`" value="`+data+`" readOnly> -->
                                    <textarea type="text" id="key_word_`+row[0]+`" name="key_word_`+row[0]+`" data-original-keyword="`+data+`" class="form-control" placeholder="`+Translation('الكلمة الدلالية')+`" value="`+data+`" readOnly style="height:80px;">`+data+`</textarea>
                                  </div>
                                  <div class="form-control-feedback">
                                    <i class="`+class2+`"></i>
                                  </div>
                                </div>
                      `;


             },
             "targets": 1
          },

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

                    if (data =='' || data ==null) {
                      data ='' ;
                      class1 = 'has-warning';
                      class2 = 'icon-notification2';
                    }else if(data  < 0){
                      class1 = 'has-error';
                      class2 = 'icon-cancel-circle2';
                    }else{
                      class1 = 'has-success';
                      class2 = 'icon-checkmark-circle';
                    }

                      return  `
                                <div class="col-lg-12 `+class1+`">
                                  <div class="input-group">
                                    <!-- <input type="text" id="translated_`+row[0]+`" name="translated_`+row[0]+`" class="form-control" placeholder="`+Translation('الترجمة الى')+` `+row[3]+`" value="`+data+`"> -->
                                    <textarea type="text" id="translated_`+row[0]+`" name="translated_`+row[0]+`" class="form-control" placeholder="`+Translation('الترجمة الى')+` `+row[3]+`" onkeypress="return runScript(event,`+row[0]+`,`+row[6]+`,`+row[7]+`)" value="`+data+`" style="height:80px;">`+data+`</textarea>
                                  </div>
                                  <div class="form-control-feedback">
                                    <i class="`+class2+`"></i>
                                  </div>
                                </div>
                      `;


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

                   if(data =='rtl' ){
                     status=  `<span class="label label-success btn-block ">`+Translation('من اليمين الى اليسار')+`</span>`;
                   }else{ 
                     status = '<span class="label bg-violet  btn-block ">'+Translation('من اليسار الى اليمين')+'</span>';
                   }
                      return  status;


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

            if(   aData[9] == 0 ){
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('warning-active');
                });
            }
        },
        "order": [[0,'desc']],
        "displayLength": 25,


        initComplete: function () {
         
        // $("div.datatable-header").append(`<a  style="margin-left:15px;" class="btn bg-info-400"  id="headerBtn" onclick="add_item()"> <i class="icon-file-pdf position-right"></i> Add Category </a>`);   
         $("div.datatable-header").append(`<a data-toggle="collapse"
                                      style="margin-right:10px;"
                                      data-target="#add-form-cont"
                                      href="javascript:;"
                                      aria-controls="add-form-cont"
                                      aria-expanded="false"
                                      class="btn btn-primary"
                                      id="add_Item_Btn">
                                        <i class="`+CURRENT_BTN_ICON+`"></i> `+Translation(CURRENT_BTN)+`
                                    </a>`); 

          $("div.datatable-header").append(`&nbsp;<div class="btn-group">
                                          <button id="inv_filter_btn" type="button" 
                                          class="btn bg-teal-400 btn-labeled dropdown-toggle" 
                                          data-toggle="dropdown"><b><i class="icon-filter4">
                                          </i></b><span id='inv_filter'>`+Translation('فلترة اللغة')+`</span>  <span class="caret"></span></button>
                                          <ul class="dropdown-menu dropdown-menu-right" id="languages_filter">
                                          </ul>
                                          </div>`);  


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

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


});



