$(".getselectmultiple").select2({
    allowClear: true,
    // minimumInputLength: 2,
    multiple: true,
    quietMillis: 100,
    ajax: {
        url: 'visitsajax.php?do=getselectjoin',
            dataType: 'json',
            type: "POST",
            data: function (term) {
                var itr = $(this).attr('data-itr');
                var parentcol = $(this).attr('data-parent');
                var parentid = $('#'+parentcol+itr).val();
                var placeholder = $('#'+parentcol+itr).attr('data-placeholder'); 
                if (parentcol != '' && parentid == '') {
                    alert(placeholder+'اولآ');
                    return false;
                }
                return {
                    searchTerms: term,
                    tablesearch: $(this).attr("data-search"), 
                    table: $(this).attr('data-table'),
                    tableid: $(this).attr('data-tableid'),
                    join: $(this).attr('data-join'),
                    filter: $(this).attr('data-filter'),
                    parentid: parentid,
                    parentcol : parentcol,
                };
            },
        results: function (data) {
            return {results: data};
        }
    },
    formatResult: function (data) {
        return  '<span>' + data.text + '</span >';

    },
    initSelection: function (element, callback) {
        var item = element.val().split(':');
         var data = {id: item[0], text: item[1]};
        callback(data);
    },
    //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
});

getselectjoin();
function getselectjoin(){
$(".getselectjoin").select2({
    allowClear: true,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: 'visitsajax.php?do=getselectjoin',
            dataType: 'json',
            type: "POST",
            data: function (term) {
                var itr = $(this).attr('data-itr');
                var parentcol = $(this).attr('data-parent');
                var parentid = $('#'+parentcol+itr).val();
                var placeholder = $('#'+parentcol+itr).attr('data-placeholder'); 
                if (parentcol != '' && parentid == '') {
                    alert(placeholder+'اولآ');
                    return false;
                }
                return {
                    searchTerms: term,
                    tablesearch: $(this).attr("data-search"), 
                    table: $(this).attr('data-table'),
                    tableid: $(this).attr('data-tableid'),
                    join: $(this).attr('data-join'),
                    filter: $(this).attr('data-filter'),
                    parentid: parentid,
                    parentcol : parentcol,
                };
            },
        results: function (data) {
            return {results: data};
        }
    },
    formatResult: function (data) {
        return  '<span>' + data.text + '</span >';

    },
    initSelection: function (element, callback) {
        var item = element.val().split(':');
         var data = {id: item[0], text: item[1]};
        callback(data);
    },
});
}


$('body').on('change', '.gettabledata', function () {
     var table = $(this).attr('data-table');
     var tableval = $.trim($(this).val());
     var tableid = $(this).attr('data-tableid');
     var join = $(this).attr('data-join');
      $.post('visitsajax.php?do=gettabledata', {table: table ,join: join, tableval: tableval, 
        tableid: tableid}, function (result) {
            var data = jQuery.parseJSON(result);
            $.each(data, function(key, value){
                $("input[name="+key+"]").val(value);
            });
            selectedit();

      });
     
});

$('body').on('change', '.checkcolumn', function () {
     var table = $(this).attr('data-table');
     var filter = $(this).attr('data-filter');
     var tablecolval = $.trim($(this).val());
     var tableid = $(this).attr('data-tableid');
     var parentid = $(this).attr('data-parentid');
     var parentcol = $(this).attr('data-parentcol');
     var thisinput = $(this);
      $.post('visitsajax.php?do=checkcolumn', {table: table ,filter: filter, tablecolval: tablecolval, 
        tableid: tableid, parentid: parentid ,parentcol: parentcol}, function (result) {
          var placeholder = $(thisinput).attr('placeholder');  
          if (result == 1) {
              alert( placeholder + ' مضاف من قبل  ');          
              $(thisinput).val("");                       
          }
      });
     
});



$(".floats" ).on("keypress", function(event) {    
    if (event.which != 46 && (event.which < 47 || event.which > 59))
    {
        event.preventDefault();
        if ((event.which == 46) && ($(this).indexOf('.') != -1)) {
            event.preventDefault();
        }
    }
});

$(".nummbers").keypress(function (e) {
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            event.preventDefault();
    }  
});

$('body').on('click', '.checkalls', function () {
   if ($(this).is(':checked')) {
    $(".chcheckalls").prop( "checked", true );

   }else{
    $(".chcheckalls").prop( "checked", false );

   }
});


$('body').on('click', '.saveformajax', function () {
    var forms = $(this).attr('data-form');
    if ($("#"+forms).valid() === true) {
        $('[data-form="'+forms+'"]').prop('disabled',true);
        $('[data-form="'+forms+'"]').css('background','red');
        saveformajax(forms);
        $("#"+forms).submit();
    } else {
        $('[data-form="'+forms+'"]').prop('disabled',false);
    }
});
function saveformajax(saveformajax = 'saveformajax'){ 
$('form#'+saveformajax).submit(function (e) {

e.preventDefault();
    var action = $('#'+saveformajax).attr('action');
    var dosave = $('#'+saveformajax).attr('data-dosave');
    var direction = $('#'+saveformajax).attr('data-direction');
    var formData = new FormData(this);
    $.ajax({
        url: action+dosave,
        type: 'POST',
        dataType: 'json',
        data: formData,
        success: function (data) {
            if (data != 0)
            {
                 $('[data-form="'+saveformajax+'"]').prop('disabled',false);
                 $('[data-form="'+saveformajax+'"]').css('background','#428bca');
                  
                if(direction) {
                     window.location = direction;  
                }else{
                    $("#Modal"+data.selectname).modal('hide');
                    $("#"+data.selectid).attr("data-id", data.id);
                    $("#"+data.selectid).val(data.text);
                    $("."+data.selectid).select2("data", {id: data.id, text: data.text});
                   

                }

               
            } else { 
                alert('حذث خطأ اثناء التنفيذ ');
                window.location = action;
            } 
            $("#"+saveformajax)[0].reset();                  
        },
        cache: false,
        contentType: false,
        processData: false
    });

});

}




fetch_data($('#start_date').val(),$('#end_date').val(),'',$("input[name=data1]").val(),$("input[name=data2]").val(),$("#data3").val(),$("#data4").val(),$("#data5").val());
 function fetch_data(start_date='', end_date='' , del='' , data1='', data2='', data3='', data4='', data5='')
 {
  var linkcon = $("#getajaxdata").attr('data-controll');
  var table = $('#getajaxdata');
  var dataTable = $('#getajaxdata').DataTable({
      "processing": true,
        "serverSide": true,
   "lengthMenu" : [[100, 200, 300, 400, 500, -1],[100, 200, 300, 400, 500, "All"] ],
   "language": {
            "emptyTable": "لا يوجد بيانات متاحه",
            "infoEmpty": "لا يوجد بيانات متاحه",
            "infoFiltered": "(filtered1 from _MAX_ total records)",
            "lengthMenu": "العدد _MENU_",
            "search": "بحث:",
            "zeroRecords": "No matching records found",
            "paginate": {
                "previous": "السابق",
                "next": "التالى",
                "last": "الاخير",
                "first": "الاول"
            }
        },
        dom: 'Bfrtip',
        buttons: [
            {
                extend: 'copyHtml5',
                exportOptions: {
                     columns: [ 1, 2, 3, 4, 5, 6 , 7 ]
                }
            },
            {
                extend: 'csvHtml5',
                exportOptions: {
                     columns: [ 1, 2, 3, 4, 5, 6 , 7 ]
                }
            },
            {
                extend: 'print',
                exportOptions: {
                     columns: [ 1, 2, 3, 4, 5, 6 , 7 ]
                }
            },
            {
                extend: 'excelHtml5',
                exportOptions: {
                     columns: [ 1, 2, 3, 4, 5, 6 , 7 ]
                }
            },
            {
                extend: 'pdfHtml5',
                exportOptions: {
                    columns: [ 1, 2, 3, 4, 5, 6 , 7 ]
                }
            },
            'colvis'
        ],
   "dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>" ,
   "order": [[0, "desc"]],
   "displayLength": 100,
   "columnDefs": [
        {"className": "dt-center", "targets": "_all"}
      ],
   "ajax" : {url:linkcon,
    type:"POST",
    data:{
     start_date:start_date, 
     end_date:end_date,
     del:del, 
     data1:data1, 
     data2:data2,
     data3:data3,
     data4:data4,
     data5:data5,
    }
   },
   "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
            if ( aData[0] == "" )
            {
            $('td', nRow).css('background-color', '#fbb6ff');
            }
            else if ( aData[7] == null )
            {
            $('td', nRow).css('background-color', '#fd9b9b');
            }
            // else if ( aData[3] == "3" )
            // {
            // $('td', nRow).css('background-color', 'Blue');
            // }
        }
  });
   setTimeout(function () {getselectjoin2(); selectedit2();}, 900);
 }

 $('body').on('change', '.searchdata', function () {
  var start_date = $('#start_date').val();
  var end_date = $('#end_date').val();
  var del = $("#del").attr("checked") ? 1 : '';
  var data1 = $("input[name=data1]").val();
  var data2 =$("input[name=data2]").val();
  var data3 = $("#data3").val();  
  var data4 = $("#data4").val();  
  var data5 = $("#data5").val();  
   $('#getajaxdata').DataTable().destroy();
   fetch_data(start_date, end_date, del, data1, data2, data3, data4, data5);

  
 }); 



 $('body').on('click', '.changestatus', function () {
  var start_date = $('#start_date').val();
  var end_date = $('#end_date').val();
  var del = $("#del").attr("checked") ? 1 : '';
  var data1 = $("input[name=data1]").val();
  var data2 =$("input[name=data2]").val();
  var data3 = $("#data3").val();  
  var data4 = $("#data4").val();  
  var data5 = $(this).attr('data-id');
  $("#data5").val(data5); 
   $('#getajaxdata').DataTable().destroy();
   fetch_data(start_date, end_date, del, data1, data2, data3, data4, data5);
  
 }); 


$('body').on('click', '.removeteble', function () {
    var id = $(this).attr('data-id');
    var table = $(this).attr('data-table');
    var tableid = $(this).attr('data-tableid');
    if (confirm('هل انت متاكد من الحذف ؟')) {
        var thisis = $(this);
        $.post('visitsajax.php?do=removeteble', {id: id, table: table, tableid: tableid}, function (data) {
            if (data == 1) {
                thisis.parent().parent().remove();
            }else{
               alert('حدث خطأ أثناء التنفيذ');
            }
        });
    } else {
    alert('لماذا ضغطت إلغاء؟ يجب أن تكون قد أكدت');
    }
});

selectedit();
function selectedit(){
    $(".selectedit").each(function( ) {

          var table = $(this).attr('data-table');
          var tableid =  $(this).attr('data-tableid');
          var tableidname =  $(this).attr('data-tableidname');
          var search = $(this).attr('data-search');
          var tableval = Number($(this).val());
          var join = $(this).attr('data-join');
          var itr = $(this).attr('data-itr');  
          if (tableval) {
              $.post('visitsajax.php?do=getselectdata', {table: table, search: search, join: join, tableval: tableval, 
                tableid: tableid, itr: itr, tableidname: tableidname}, function (result) {
                var data = jQuery.parseJSON(result);
                $("#"+tableidname+itr).select2("data", {id: tableval, text: data.texts});
                });  
         }     
          
    });
    $(".selecteditm").each(function( ) {
         var table = $(this).attr('data-table');
          var tableid =  $(this).attr('data-tableid');
          var tableidname =  $(this).attr('data-tableidname');
          var search = $(this).attr('data-search');
          var tableval = $(this).val();
          var join = $(this).attr('data-join');
          var itr = $(this).attr('data-itr');  
          if (tableval) {
            $.post('visitsajax.php?do=getselectdatam', {table: table, search: search, join: join, tableval: tableval, 
                tableid: tableid, itr: itr, tableidname: tableidname}, function (result) {
                var data = jQuery.parseJSON(result);
                 $("#"+tableidname+itr).select2("data", data);     
            });  
         }    
            
    });
}


$('body').on('click', '.adddatamodal', function () {
     var form = $(this).attr('data-formt');
     var tableid = $(this).attr('data-tableid');
     var selectitr = $(this).attr('data-selectitr');
     var table = $(this).attr('data-table');
     $("#"+form)[0].reset();  
     $("#itr"+table).val(selectitr);
     $('[data-form="'+form+'"]').text('حفظ');
     $("#Modal"+tableid+"Label").text('الاضافه');
     $("input[name="+tableid+"]").val('');
     $("#productCatParent").val('').trigger("change");
      $("select[name=goverareaid]").val("").trigger("change");
      $('.hideshow').show();
});




$('body').on('click', '.editdatamodal', function () {
     var table = $(this).attr('data-table');
     var model = $(this).attr('data-model');
     var selectitr = $(this).attr('data-selectitr');
     var name = $(this).attr('data-name');
     var tableval = $.trim($("#"+name+selectitr).val());
     if (tableval > 0) {
     var tableid = $(this).attr('data-tableid');
     $("#pop"+table).val(tableval);
     var form = $(this).attr('data-formt');
     var join = $(this).attr('data-join');
      $.post('visitsajax.php?do=gettabledata', {table: table ,join: join, tableval: tableval, 
        tableid: tableid, model: model, form: form, selectitr: selectitr, name: name}, function (result) {
            var data = jQuery.parseJSON(result);
              $(model).modal('show');
              $('[data-form="'+form+'"]').text('تعديل');
              $("#Modal"+name+"Label").text('تعديل');
              $("#itr"+table).val(selectitr);
            $.each(data, function(key, value){
                $("input[name="+key+"]").val(value);
            });
            selectedit();
            $('.hideshow').hide();
      });
   }
     
});

selectRefresh2();
function selectRefresh2(){
    $('select.selectnew').select2({
        width:'100%'
    });
}
 


$('body').on('change', '.changecenter', function () {
    var id = $(this).attr('data-id');
    var maintenancecenterid = $(this).val();
    $.post('maintenances.php?do=changecenter', {id: id ,maintenancecenterid: maintenancecenterid});
});




$('body').on('change', '.maintenancecase', function () {
    var maintenancecaseid = $(this).val();
    $("#data5").val(maintenancecaseid);
    $("li").removeClass("active");
    $('#li'+maintenancecaseid).addClass('active'); 
    if ($('.checkboxes:checked').length == 0) {
       alert('يجب اختيار عنصر على الاقل');
    } else {
        $('.checkboxes:checked').each(function () {
            var myid = $(this).val();
            $.post('maintenances.php?do=changecase', {maintenancecaseid: maintenancecaseid, myid: myid});
        });
        $('#getajaxdata').DataTable().destroy();
        fetch_data($('#start_date').val(),$('#end_date').val(),'',$("input[name=data1]").val(),$("input[name=data2]").val(),$("#data3").val(),$("#data4").val(),$("#data5").val());
    }
});


$(document).on("click", ".add_append", function () {
        var controll = $(this).attr('data-controll');
        var appendname = $(this).attr('data-appendname');
        var itr = Number($('#itr_'+appendname).val()) + 1;
        $.post(controll+'.php?do='+appendname, {itr: itr, appendname: appendname}, function (data) {
            $('#container_'+appendname).append(data);
            $('#itr_'+appendname).val(itr);
    });
});

$('body').on('change', '.maintorguar', function () {
    var maintorguar = $(this).val();
    if (maintorguar == 1) {
        $('#hidecenter').show();
    }else{
        $('#hidecenter').hide();
    }
});
$('body').on('change', '#shippingvalue', function () {
      shippingvalue(); 
});
$('body').on('click', '.policycheck', function () {
    // var  dataupdate  = $(this).attr('data-update');
    // var  maintenanceid = $(this).val();
    // if (!$(this).is(':checked') && dataupdate == 1) {
    //     $('#shipprice_'+maintenanceid).val('');
    //     $('#shipcharge_'+maintenanceid).val('');
    //     $('#shipnumber_'+maintenanceid).val('');
    //     $.post('maintenancesends.php?do=changecondition', {maintenancecaseid: 1, maintenanceid: maintenanceid, maintenancepolicyid: 0});
    // }else if ($(this).is(':checked') && dataupdate == 1) {
    //     $.post('maintenancesends.php?do=changecondition', {maintenancecaseid: 2, maintenanceid: maintenanceid, maintenancepolicyid: $('#maintenancepolicyid').val()});
    // }
    shippingvalue(); 
});
function shippingvalue(){
    var shippingvalue = Number($('#shippingvalue').val());
    var forms = $('#shippingvalue').attr('data-forms');
    var count = $('.policycheck:checked').length;
    if (count > 0) {
        $('[data-form="'+forms+'"]').prop('disabled',false);
        var shipping = shippingvalue / count;
        $('.policycheck').each(function () {
            var myid = $(this).val();
            if (!$(this).is(':checked')) {
                 $('#shipcharge_'+myid).val('');
            }else{
                $('#shipcharge_'+myid).val(shipping.toFixed(3));
            }
            
        });
    }else{
        $('[data-form="'+forms+'"]').prop('disabled',true);

    }
}

$(document).on("change", ".getmaintenances", function () {
        var supplierid = $(this).val();
        $.post('maintenancesends.php?do=getmaintenances', {supplierid: supplierid}, function (data) {
            $('#getmaintenances').html(data);
         });
});


$(document).on("change", ".maintenancepolicyget", function () {
        var maintenancepolicyid = $(this).val();
        $.post('maintenancereceipts.php?do=maintenancepolicyget', {maintenancepolicyid: maintenancepolicyid}, function (data) {
            $('#maintenancepolicyget').html(data);
            setTimeout(function () {getselectjoin2(); selectedit2();}, 900);

         });
});

function selectedit2(){
    $(".selectedit2").each(function( ) {
          var table = $(this).attr('data-table');
          var tableid =  $(this).attr('data-tableid');
          var tableidname =  $(this).attr('data-tableidname');
          var search = $(this).attr('data-search');
          var tableval = Number($(this).val());
          var join = $(this).attr('data-join');
          var itr = $(this).attr('data-itr');  
          if (tableval) {
              $.post('visitsajax.php?do=getselectdata', {table: table, search: search, join: join, tableval: tableval, 
                tableid: tableid, itr: itr, tableidname: tableidname}, function (result) {
                var data = jQuery.parseJSON(result);
                $("#"+tableidname+itr).select2("data", {id: tableval, text: data.texts});
                });  
         }     
          
    });
}


function getselectjoin2(){
$(".getselectjoin2").select2({
    allowClear: true,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: 'visitsajax.php?do=getselectjoin',
            dataType: 'json',
            type: "POST",
            data: function (term) {
                var itr = $(this).attr('data-itr');
                var parentcol = $(this).attr('data-parent');
                var parentid = $('#'+parentcol+itr).val();
                var placeholder = $('#'+parentcol+itr).attr('data-placeholder'); 
                if (parentcol != '' && parentid == '') {
                    alert(placeholder+'اولآ');
                    return false;
                }
                return {
                    searchTerms: term,
                    tablesearch: $(this).attr("data-search"), 
                    table: $(this).attr('data-table'),
                    tableid: $(this).attr('data-tableid'),
                    join: $(this).attr('data-join'),
                    filter: $(this).attr('data-filter'),
                    parentid: parentid,
                    parentcol : parentcol,
                };
            },
        results: function (data) {
            return {results: data};
        }
    },
    formatResult: function (data) {
        return  '<span>' + data.text + '</span >';

    },
    initSelection: function (element, callback) {
        var item = element.val().split(':');
         var data = {id: item[0], text: item[1]};
        callback(data);
    },
});
}

function residual(){
        var prepaid = Number($('#prepaid').val());
        var shipcharge = Number($('#shipcharge').val());
        var bshipcharge = Number($('#bshipcharge').val());
        var maintenancecost = Number($('#maintenancecost').val());
        var paidlater = Number($('#paidlater').val());
        var sums = (shipcharge + bshipcharge + maintenancecost).toFixed(3);
        
        $('#totalcost').val(sums);
        $('#requiredcustomer').val(sums - prepaid);
        $('#paidall').val(( paidlater + prepaid).toFixed(3));
        $('#residual').val((sums - (paidlater + prepaid)).toFixed(3));
}

$(document).on("change", ".totals", function () {
 residual();     
});


$('body').on('change', '.maintenancecomments', function () {
    var values = $(this).val();
    var maintenanceid = $(this).attr('data-maintenanceid');
    var myid = $(this).attr('data-id');
    $.post('maintenances.php?do=updatecomment', {values: values, myid: myid, maintenanceid: maintenanceid});
       
});