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

    var HTML_VIEW_PAY = '';
    var print_page =  `
                        <script>
                          window.print();
                          window.onload = function() { window.print(); }
                        </script>
                        `;
    var HTML_Table = `
                      <!DOCTYPE html>
                      <html lang="ar" dir="rtl">
                      <head>
                        <meta charset="utf-8">
                        <meta http-equiv="X-UA-Compatible" content="IE=edge">
                        <style>

                          .print {  
                            -webkit-print-color-adjust: exact;
                          }
                          
                          .table0_td {
                            
                            border:none;
                            padding:0in 0pt 0in 0pt;
                            height:9.95pt
                            
                          }
                          
                          .table0_td1 {
                            
                            border:none;
                            border-bottom:solid #984806 1.0pt;
                            padding:0in 0pt 0in 0pt;
                            height:9.95pt
                            
                          }
                          
                          
                          
                          .table1_td {
                            
                            border:solid #984806 1.0pt;
                            border-left-color: white;
                            background:#984806;
                            padding:0pt 0pt 0pt 0pt;
                            height:.1in
                            
                          }
                          
                          .last_td {
                            border-left-color: #984806 !important;
                          }
                          
                          .table1_td1 {
                            
                            border:solid #984806 1.0pt;
                            border-top:none;
                            background:white;
                            padding:0pt 0pt 0pt 0pt;
                            height:.1in
                            
                          }
                          
                          .table2_td {
                            
                            border:solid #984806 1.0pt;
                            border-left-color: white;
                            background:#984806;
                            padding:0pt 0pt 0pt 0pt;
                            height:.1in;
                            
                          }
                          
                          .td_head {
                            text-align: center;
                            
                            color : white;
                            height: .3in;
                          }
                          
                          .td_body {
                            text-align: center;
                            
                            color : black;
                            height: .2in;
                            border:solid #984806 1.0pt;
                          }
                          
                          #inv_table tr:nth-child(odd) {
                            background-color: #FDE9D9;
                          }
                          
                          @font-face {
                            font-family: "Noto Kufi Arabic";
                            src: url(assets/custom_font/NotoKufiArabic-Regular.ttf) format("truetype");
                            }
                          
                          .badge {
                            display: inline-block;
                            min-width: 10px;
                            padding: 3px 7px;
                            font-size: 12px;
                            font-weight: 500;
                            color: #fff;
                            line-height: 1.5384616;
                            vertical-align: middle;
                            white-space: nowrap;
                            text-align: center;
                            background-color: #999999;
                            border-radius: 10px;
                          } 

                          .label {
                              display: inline-block;
                              font-weight: 500;
                              padding: 2px 5px 1px 5px;
                              line-height: 1.5384616;
                              border: 1px solid transparent;
                              text-transform: uppercase;
                              text-align: center;

                              font-size: 10px;
                              letter-spacing: 0.1px;
                              border-radius: 2px;
                          }
                          
                          .badge {
                            padding: 1px 1px 1px 1px;
                            font-size: 10px;
                            letter-spacing: 0px;
                            vertical-align: baseline;
                            
                            
                            
                          }
                          
                          .bg-orange-400 {
                            background-color: #FFA726;
                            border-color: #FFA726;
                            color: #fff;
                          }

                          .bg-success-400 {
                            background-color: #4CAF50;
                            border-color: #4CAF50;
                            color: #fff;
                          }

                          

                        </style>

                      </head>

                      <body class="print" style=" font-family: 'Noto Kufi Arabic', Times, serif;">
                        <div align=center>
                      `;


    function show_bills(itemid,cust_name,no_,amount,date_,trans_,notes,printing=null){
          
          notes       = decodeURIComponent_back(notes);
          // staff_anme  = decodeURIComponent_back(staff_anme);
          cust_name   = decodeURIComponent_back(cust_name);

          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";

          var bill_title        = "وصل قبض";
          
          var bill_paragraph    = Translation('استلم من السيد')+` : (<span style='font-weight:bold;'>` + cust_name + `) </span>`+Translation('مبلغا قدره')+` : (`+currency_format_display(amount)+`) `+Translation('وذلك كدفعه عن حسابه');

          if(trans_ == 'Discount'){
            bill_title        = "وصل خصم من الحساب";
            bill_paragraph    = Translation('تم خصم من حساب السيد')+` : (<span style='font-weight:bold;'>` + cust_name + `) </span>`+Translation('مبلغا قدره')+` : (`+currency_format_display(amount)+`) `+Translation('وذلك عن')+` ................................................................................................................`;

          }else if(trans_ =="Return"){
            bill_title        = "وصل استرجاع مبلغ";
            bill_paragraph    = Translation('تم تسليم السيد')+` : (<span style='font-weight:bold;'>` + cust_name + `) </span>`+Translation('مبلغ مسترجع من حسابة المدفوع قدره')+` : (`+currency_format_display(amount)+`) `+Translation('وذلك عن')+` ................................................................................................................`;
          }

           headers =`

                      <table  dir=rtl border=1 cellspacing=0 cellpadding=0
                         style='background:white;border-collapse:collapse;border:none; font-weight:bold;'>
                         <tr>
                          <td width=590 colspan=6 style='width:6.15in;border:none;padding:0in 5.4pt 0in 5.4pt'>       
                            <span style="float: left; font-size: 20px;" id="inv_slogan">`+COMPANY_NAME+`</span>
                          </td>
                         </tr>
                         <tr style='height:9.95pt'>
                          <td width=295 colspan=3 style='width:221.4pt;' class="table0_td">
                          <span id="inv_address"> `+Translation(COMPANY_ADDRESS)+` </span>
                          </td>
                          <td width=295 colspan=3 rowspan=2 style='width:221.4pt;' class="table0_td">
                          <span id="inv_logo">  </span>
                          </td>
                         </tr>

                         
                         
                         <tr style='height:9.95pt'>
                          <td width=295 colspan=3 style='width:221.4pt;' class="table0_td">
                         `+Translation('موبايل')+`  : <span dir="ltr" id="inv_phone"> `+COMPANY_PHONE+` </span>
                          <br>
                         `+Translation('البريد الالكتروني')+`  : <span dir="ltr" id="inv_email"> `+COMPANY_EMAIL+` </span>
                          </td>
                         </tr>
                         
                         <tr style='height:9.95pt'>
                          <td width=118 style='width:88.55pt;' class="table0_td1">
                         `+Translation('رقم الوصل')+`  :
                          </td>
                          <td width=139 style='width:1.45in;' class="table0_td1">
                          <span id="inv_num" style="color:red;">`+no_+`</span>
                          </td>
                          <td width=77 colspan=2 style='width:.8in;' class="table0_td1">
                          
                          </td>
                          <td width=116 style='width:87.3pt;' class="table0_td1">
                         `+Translation('التــــــــــــاريخ')+`  :     
                          </td>
                          <td width=140 style='width:104.95pt;' class="table0_td1">
                          <span id="inv_date">`+date_+`</span>
                          </td>
                         </tr>
                         
                         
                        </table>
                        <br>
                            `;

          customer_details = `

                                      <table  dir=rtl border=1 cellspacing=0 cellpadding=0
                                       style='background:white;border-collapse:collapse;border:none; font-weight:bold;'>
                                       
                                       <tr>
                                        <td width=590 colspan=6 style='width:6.15in; text-align:center; border:none;padding:0in 5.4pt 0in 5.4pt'>       
                                          <span style="float: center;  font-size: 18px;" id="inv_slogan">`

                                          +Translation(bill_title)+` </span>
                                        </td>
                                       </tr>

                                       <tr>
                                        <td width=590 colspan=6 style='width:6.15in;border:none;padding:0in 5.4pt 0in 5.4pt'>       
                                          <span style="float: center; font-size: 16px;" id="inv_slogan">
                                          `+bill_paragraph+`
                                          </span>
                                        </td>
                                       </tr>
                                       
                                      
                                       
                                      </table>
                                      <br>
                                            `;
         

           attach =  `
                                  <table id="inv_table"  dir=rtl border=1 cellspacing=0 cellpadding=0 width=591 style='width:443.5pt;border-collapse:collapse;border:#000000; '>
                                   <tr style='page-break-inside:avoid;' class="td_head">
                                    <td width=23 style='width:14.4pt;' class="table2_td">
                                   `+Translation('ت')+` 
                                    </td>
                                    <td width=68 style='width:50.7pt; text-align:center;' class="table2_td">
                                   `+Translation('المبلغ')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt; text-align:center;' class="table2_td">
                                   `+Translation('التاريخ')+` 
                                    </td>
                                    
                                    <td width=74 style='width:55.5pt; text-align:center;' class="table2_td last_td">
                                   `+Translation('الملاحظات')+` 
                                    </td>
                                   </tr>

                                   <tr style='page-break-inside:avoid;' >
                                    <td width=23 style='width:14.4pt;' >
                                    1 
                                    </td>
                                    <td width=68 style='width:50.7pt; text-align:center;' >
                                   `+currency_format_display(amount)+` 
                                    </td>
                                    <td width=64 style='width:48.3pt; text-align:center;' >
                                   `+date_+` 
                                    </td>
                                    
                                    <td width=74 style='width:55.5pt; text-align:center;' class=" last_td">
                                   `+notes+` 
                                    </td>
                                   </tr>
                                   `;

          if(printing != null){
            print_attach = `
                            <script>
                              window.print();
                              window.onload = function() { window.print(); }
                            </script>
                            `;
          }else{
            print_attach = "";
          }


          footers =`
                                 
                     <tr style='page-break-inside:avoid;height:.3in'>
                     
                      <td width=517 colspan=4  style='width:388.0pt;border:none;background:white;
                        padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                        <span id="inv_note"> `+Translation('ملاحظة')+` :  </span>
                      </td>
                     </tr>
                     
                     <tr style='page-break-inside:avoid;height:.1in; background-color: white'>
                      <td width=258 colspan=2  style='width:194.0pt;border:none;
                      padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                      `+Translation('توقيع المُسلم')+`
                      </td>
                      <td width=258 colspan=2 style='width:194.5pt;border:none;padding:2.15pt .15in 2.15pt .15in;
                      height:.1in'>
                     `+Translation('توقيع المستلم')+` 
                      </td>
                     </tr>
                    </table>

                    </div>




                    </body>

                    `+print_attach+`

                    </html>`;

          HTML_VIEW_PAY = HTML_Table + headers + customer_details + attach + attach_other + footers;
                       
          $("#bills_show").html(HTML_VIEW_PAY);
          $("#bill_id").val(itemid);

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


    }



    function edit_items(itemid,amount,date_,notes,cust_id,tans_){
      
      notes = decodeURIComponent_back(notes);
      
      
      $("#edit_objid").val(itemid);
      $("#edit_loaner_id_fk").val(cust_id);
      $("#edit_loaner_id_fk").val(cust_id).selectpicker('refresh');
      
      $("#edit_payment_withdraw_amount").val(amount);
      $("#edit_payment_withdraw_amount").attr('data-value',amount);

      
      $("#edit_payment_withdraw_date").val(date_);
      $("#edit_payment_withdraw_note").val(notes);
      $("#transaction_").val(tans_);

      $("#transaction_type").text(tans_);

      if(tans_ == 'Loan'){
        $("#transaction_type_alert").removeClass('alert-primary');
        $("#transaction_type_alert").removeClass('alert-danger');
        $("#transaction_type_alert").removeClass('alert-warning');
        $("#transaction_type_alert").addClass('alert-success');

      }else if(tans_=="Refund"){
        $("#transaction_type_alert").removeClass('alert-primary');
        $("#transaction_type_alert").removeClass('alert-danger');
        $("#transaction_type_alert").removeClass('alert-success');
        $("#transaction_type_alert").addClass('alert-warning');
      }
       load_customer_account_details(cust_id);
      $('#edit_form_cont').modal('toggle');

    }

  



    function delete_items(itemid) {
     
        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_loan.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_Loaner(){

      $.ajax({
                      url : 'models/crul_loaner.php',
                      type : 'POST',
                      data : {type:'get'},
                      dataType : 'json',
                      success : function(res) {
                          
                          if(res!= 0){
                            
                            var attach ='<option value="" selected="selected">'+Translation('Loaner Name')+'</option>';
                          
                            for(var i=res.length-1 ; i >= 0;i--){
                              
                              attach = attach + '<option value="'+res[i][0]+'">'+res[i][1]+'</option>';
                             

                            }
                            $("#loaner_id_fk").html(attach);
                            $("#loaner_id_fk1").html(attach);
                            $("#edit_loaner_id_fk").html(attach);
                            $('#loaner_id_fk').selectpicker('refresh');
                            $('#loaner_id_fk1').selectpicker('refresh');
                            $("#edit_loaner_id_fk").selectpicker('refresh');

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

                            
                      },
                      complete: function() {
                             //  me.data('requestRunning', false);
                      }

                }); // submit ajax

    }

  

    function print_invoice(typ,payment=null){
      if(typ=='Print'){
        window.open().document.write(HTML_VIEW_PAY+print_page);
      }else if(typ=='PDF'){
        var nn = $("#inv_numb").val();
        pdf_generator(HTML_VIEW_PAY,nn,'pay')
      }else{
        window.open().document.write(HTML_VIEW_PAY);
      }
    }

    function pdf_generator(HTML,INV_NO,payment){

                $.ajax({
                      url : 'models/crul_invoice.php',

                      type : 'POST',
                      data : {type:'PDF',html:HTML,inv_no:INV_NO,pay:payment},
                      dataType : 'json',
                      success : function(response) {
                            console.log(response)
                            if(response.is_success == true) {

                                    noty({
                                        width: 200,
                                        text: Translation('تم توليد ملف الـ PDF بنجاح'),
                                        type: 'success',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'top',
                                    });
                                    var LINKS = '<a class="btn btn-labeled btn-labeled-left heading-btn btn-info" href="'+response.data+'" target="_blank" style="float: right;"> '+Translation('تحميل')+' <b><i class="icon-file-download"></i></b> </a>';
                                    if(payment !=null){
                                      $("#link_pdf_pay").append(LINKS);
                                    }else{
                                      $("#link_pdf").append(LINKS);
                                    }

                                  
                                  $("#pdf").attr('disabled',false);
                                  $("#pdf_pay").attr('disabled',false);
                                  $("#print").attr('disabled',false);
                                  $("#print_pay").attr('disabled',false);
                            } else {

                               noty({
                                     width: 200,
                                     text: Translation(response.message),
                                     type: 'error',
                                     dismissQueue: true,
                                     timeout: 3000,
                                     layout: 'top',
                               });

                                  $("#pdf").attr('disabled',false);
                                  $("#pdf_pay").attr('disabled',false);
                                  $("#print").attr('disabled',false);
                                  $("#print_pay").attr('disabled',false);
                            }
                      },
                      complete: function() {
                            //   me.data('requestRunning', false);
                      }

                }); // submit ajax
    }


    function compute_remain_price(val,idd){

        // var val = $("#payment_withdraw_amount").val();

        if(val !="" &&  !isNaN(val) && val !=null && val !=undefined ){
          val = val;
        }else{
          val = 0;
        }

        var old_remain   = $("#total_customer_remaind").attr('data-original-amount');
        
        if(old_remain   == null || old_remain   == undefined || old_remain   == '' || isNaN(old_remain)){old_remain=0; }
       
        var new_remaind = old_remain - val;
       
        // if(new_remaind < 0){

        //    noty({
        //           width: 200,
        //           text: Translation("الرجاء التأكد من القيمة المدخلة لان المدفوعات اصبحت اكبر من السعر الكلي المتبقي"),
        //           type: 'error',
        //           dismissQueue: true,
        //           timeout: 4000,
        //           layout: 'topRight',
        //         });

         
        //   $("#"+idd).val('');
          
        // }


    }


    function compute_return_price(val,idd){

        // var val = $("#payment_withdraw_amount").val();

        if(val !="" &&  !isNaN(val) && val !=null && val !=undefined ){
          val = val;
        }else{
          val = 0;
        }
        // var real_price = $("#product_row_total_"+row_num).attr('data-actual-row-price'); 
        var old_remain   = $("#return_total_customer_paid").attr('data-original-amount');
        // var old_remain   = $("#"+idd).attr('data-original-amount');
        
          // alert("old_remain="+old_remain)

        // if(real_price == null || real_price == undefined || isNaN(real_price)){real_price=0;}
        if(old_remain   == null || old_remain   == undefined || old_remain   == '' || isNaN(old_remain)){old_remain=0; }
       
        var new_remaind = old_remain - val;
          // alert("new_remaind="+new_remaind)

       
        if(new_remaind < 0){

           noty({
                  width: 200,
                  text: Translation("الرجاء التأكد من القيمة المدخلة لان المبلغ المسترجع اصبحت اكبر من المبلغ الكلي المدفوع للزبون"),
                  type: 'error',
                  dismissQueue: true,
                  timeout: 4000,
                  layout: 'topRight',
                });

          
          // $("#payment_withdraw_amount").val('');
          $("#"+idd).val('');
          
        }


    }

    function edit_compute_remain_price(){

        var val     = $("#edit_payment_withdraw_amount").val();
        var trans_  = $("#transaction_").val();

      
        var curnt_edit_amount = $("#edit_payment_withdraw_amount").attr('data-value'); // we should exculde it from remaind because its by default were add and computed but now we will edit it

        if(val !="" &&  !isNaN(val) && val !=null && val !=undefined ){
          val = val;
        }else{
          val = 0;
        }
        // var real_price = $("#product_row_total_"+row_num).attr('data-actual-row-price');
        if(trans_ == 'Return'){
          var old_remain   = $("#edit_total_customer_paid").attr('data-original-amount');
        }else{
          var old_remain   = $("#edit_total_customer_remaind").attr('data-original-amount');
        } 
        
        
          // alert("old_remain="+old_remain)

        // if(real_price == null || real_price == undefined || isNaN(real_price)){real_price=0;}
        if(old_remain   == null || old_remain   == undefined || old_remain   == '' || isNaN(old_remain)){old_remain=0; }
       
        var new_remaind = old_remain - val + +curnt_edit_amount;

          // alert("new_remaind="+new_remaind)
       
        if(new_remaind < 0){

           noty({
                  width: 200,
                  text: Translation("الرجاء التأكد من القيمة المدخلة لان المدفوعات اصبحت اكبر من السعر الكلي المتبقي"),
                  type: 'error',
                  dismissQueue: true,
                  timeout: 4000,
                  layout: 'topRight',
                });

          // $("#inv_row_remaind_price_"+row_num).val('');
          $("#edit_payment_withdraw_amount").val(curnt_edit_amount);
          
        }


    }

    function load_customer_account_details (cust_id){

              $.ajax({
                      url : 'models/crul_loan.php',
                      type : 'POST',
                      data : {type:'show_payments_for_add',id:cust_id},
                      dataType : 'json',
                      success : function(response) {
                          
                          if(response != 0){
                            
                            
                             

                            $('span[id$="total_customer_account"]').html(currency_format_display(response.invoice[0].total_loan));
                            $('span[id$="total_customer_account"]').attr('data-original-amount',(response.invoice[0].total_loan));
                            
                            
                            $('span[id$="total_customer_paid"]').html(currency_format_display(response.invoice[0].total_refund));
                            $('span[id$="total_customer_paid"]').attr('data-original-amount',(response.invoice[0].total_refund));
                         
                            $('span[id$="total_customer_remaind"]').html(currency_format_display(response.invoice[0].total_remained));
                            $('span[id$="total_customer_remaind"]').attr('data-original-amount',(response.invoice[0].total_remained));
                         

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

                            
                      },
                      complete: function() {
                             //  me.data('requestRunning', false);
                      }

                }); // submit ajax
    }


    function add_discount(){
      $('#discount_form_cont').modal('toggle');

    }

    function add_return(){
      $('#return_form_cont').modal('toggle');

    }

    function get_Branch(){

        $.ajax({
              url : 'models/crul_branch.php',
              type : 'POST',
              data : {type:'get',branch_id:BRANCH_ID},
              dataType : 'json',
              success : function(response) {
                  var attach ='<option class="text-black text-danger-800" selected="selected" value="">'+Translation('Select Branch Safe')+'</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_fk1").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();
    get_Loaner();

    $('select[id$="loaner_id_fk"]').change(function(e) {
                e.preventDefault();
                var cust_id = $(this).val();
                
                load_customer_account_details(cust_id);

         
    });

    $('select[id$="loaner_id_fk1"]').change(function(e) {
                e.preventDefault();
                var cust_id = $(this).val();
                
                load_customer_account_details(cust_id);

         
    });




    $('#print_pay').click(function(e) {
      e.preventDefault();
         print_invoice('Print','pay');
    });

    $('#pdf_pay').click(function(e) {
      e.preventDefault();
         print_invoice('PDF','pay');
    });

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


      var cust_id           = $("#loaner_id_fk").val();

      var pay_notes_array                  =[];
      var pay_price_array                  =[];


      pay_price_array[0]   = $("#payment_withdraw_amount").val();
      var paid_date        = $("#paid_date").val();
      var paper_number     = $("#paper_number").val();
      var branch_id_fk     = $("#branch_id_fk").val();
      pay_notes_array[0]   = $("#payment_note").val();
      


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

      Check1 = Checks('loaner_id_fk');
      Check2 = Checks('payment_withdraw_amount');
      Check3 = Checks('paid_date');
      
      

      if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_loan.php",
                type:"POST",
                dataType: "JSON",
                data : {cust_id             :cust_id,
                        row_payments        :pay_price_array,
                        notes               :pay_notes_array,
                        paid_date           :paid_date,
                        paper_number        :paper_number,
                        branch_id_fk        :branch_id_fk,

                        type                :'add_payments'}
            })
            .done(function(res) {
                //alert(res);
                if(res.is_success == true){

                    $("#add_form")[0].reset();
                    $("#payment_gived_to_id_fk").val('').selectpicker('refresh');
                    
                    // get_Customer();

                    $("#total_customer_account").html(currency_format_display(0));
                    $("#total_customer_account").attr('data-original-amount',(0));
                            
                    $("#total_customer_discount").html(currency_format_display(0));
                    $("#total_customer_discount").attr('data-original-amount',(0));
                            
                    $("#total_customer_paid").html(currency_format_display(0));
                    $("#total_customer_paid").attr('data-original-amount',(0));
                         
                    $("#total_customer_remaind").html(currency_format_display(0));
                    $("#total_customer_remaind").attr('data-original-amount',(0));
                         
                    $("#add-form-cont").collapse('hide');

                    $(".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:"Error",
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                }
                $("#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");
            });
        }

    });



    
    $('#edit_form').submit(function(event) {
              event.preventDefault();
             
              var payment_id          = $("#edit_objid").val();
              var loaner_id_fk        = $("#edit_loaner_id_fk").val();
              var paid_amount         = $("#edit_payment_withdraw_amount").val();
              var paid_date           = $("#edit_payment_withdraw_date").val();
              var payment_note        = $("#edit_payment_withdraw_note").val();
              



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

              Check1 = Checks('edit_loaner_id_fk');
              Check2 = Checks('edit_payment_withdraw_amount');
              Check3 = Checks('edit_payment_withdraw_date');
              // Check4 = Checks('edit_withdraw_date');
              
            

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

                  $.ajax({
                      url: "models/crul_loan.php",
                      type:"POST",
                      dataType : "JSON",
                      data : {payment_id:payment_id,
                              loaner_id_fk:loaner_id_fk,
                              paid_amount:paid_amount,
                              paid_date:paid_date,
                              payment_note:payment_note,
                              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: Translation("خطأ"),
                              text: Translation(res.data),
                              confirmButtonColor: "#66BB6A",
                              type: "warning"
                          });
                        }else{
                          $("#edit_form")[0].reset();
                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);

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


    $('#discount_form').submit(function(event) {
              event.preventDefault();
             
              
              var loaner_id_fk        = $("#loaner_id_fk1").val();
              var branch_id_fk        = $("#branch_id_fk1").val();
              var paid_amount         = $("#discount_payment_withdraw_amount").val();
              var paid_date           = $("#discount_payment_withdraw_date").val();
              var payment_note        = $("#discount_payment_withdraw_note").val();
              



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

              Check1 = Checks('loaner_id_fk1');
              Check2 = Checks('discount_payment_withdraw_amount');
              Check3 = Checks('discount_payment_withdraw_date');
              // Check4 = Checks('branch_id_fk1');
              
            

              if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
                  $("#discount_form_btn").attr('disabled',true);
                  $.ajax({
                      url: "models/crul_loan.php",
                      type:"POST",
                      dataType : "JSON",
                      data : {
                              loaner_id_fk:loaner_id_fk,
                              paid_amount:paid_amount,
                              paid_date:paid_date,
                              payment_note:payment_note,
                              branch_id_fk:branch_id_fk,
                              type:'refund'},
                      complete:function(){
                        $("#discount_form_btn").attr('disabled',false);
                      },
                      beforeSend:function(){
                        $("#discount_form_btn").attr('disabled',true);
                      },
                      success: function(res) {
                        if(res.is_success == false){
                          
                          $('#discount_form_cont').modal('toggle');
                          $("#discount_form")[0].reset();
                          swal({
                              title: Translation("خطأ"),
                              text: Translation(res.data),
                              confirmButtonColor: "#66BB6A",
                              type: "warning"
                          });
                        }else{
                          $("#discount_form")[0].reset();
                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);

                          $('#discount_form_cont').modal('toggle');
                          noty({
                                          width: 200,
                                          text: Translation(res.data), //'Product Successfully Update',
                                          type: 'success',
                                          dismissQueue: true,
                                          timeout: 3000,
                                          layout: 'topRight',
                                    });
                        }
                        $("#discount_form_btn").attr('disabled',false);
                      }
                  });
                }
    });


    

});





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

   // for image uploader

  



    //
    // AJAX upload
    //





   // end image uploader



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


    

    // Individual column searching with text inputs
    $('.datatable-column-search-inputs tfoot td').not(':last-child').each(function () {
        var title = $('.datatable-column-search-inputs thead th').eq($(this).index()).text();
        $(this).html('<input type="text" class="form-control input-sm" placeholder="'+Translation('بحث عن')+' '+title+'" />');
    });
    
    
  var query_id  = getQueryVariable("id");
  var query_ic = getQueryVariable("ic");
   
  var table = $('.datatable-column-search-inputs').DataTable({
        keys: {
            className: 'focus focus-success'
        },
        buttons: {            
            buttons: [
                {
                    extend: 'copyHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: [ 0, ':visible' ]
                    }
                },
                {
                    extend: 'excelHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'pdfHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'print',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'colvis',
                    text: '<i class="icon-three-bars"></i> <span class="caret"></span>',
                    className: 'btn bg-blue btn-icon'
                }
                
                
                
            ]
        },
        lengthMenu: [
            [  10, 25, 50, 100,-1 ],
            [  '10', '25', '50', '100','All' ]
        ],

        "processing": true,
        "serverSide": true,
        "ajax": {
        "url" : "models/crul_loan.php",
        "data": function(d){
          d.type = "load";
          if(query_id !='not'){
            d.id =query_id ;
          }

          if(query_ic !='not'){
            d.idc =query_ic ;
          }

          d.branch_id=BRANCH_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": 8,
              "data": null,
              "render": function (data,type,row) {

                          if(IS_VIEW==0){
                            return  `<ul class='icons-list pull-right'>
                                        
                                        <!--<li class='text-primary-600'>
                                            <a href='#' class='text-purple-400' onclick="show_bills(`+row[0]+`,'`+escapeHtml(row[1])+`','`+row[2]+`','`+row[3]+`','`+row[4]+`','`+row[5]+`','`+escapeHtml(row[6])+`')" data-popup='tooltip' data-original-title='`+Translation('وصل قبض')+`'>
                                                <i class='icon-certificate'></i>
                                            </a>
                                        </li>-->

                                        <li class='text-primary-600'>
                                            <a  class='text-primary-400' onclick="edit_items(`+row[0]+`,'`+row[3]+`','`+row[4]+`','`+escapeHtml(row[6])+`',`+row[10]+`,'`+row[5]+`')" data-popup='tooltip' data-original-title='`+Translation('تحرير')+`'>
                                                <i class='icon-pencil7 icon-2x'></i>
                                            </a>
                                        </li>

                                        <li class='text-danger-600'>
                                            <a  class='text-danger-400' onclick="delete_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('حذف')+`'>
                                                <i class='icon-trash icon-2x'></i>
                                            </a>
                                        </li>

                                    </ul>`;
                          }else{
                            return '';
                          }
                        }
          },


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

                        
                          return  currency_format_display(data);
                       


               },
               "targets": 3
            },

            

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


                        return  `<a href='index.php?p=loan&id=`+row[10]+`'  data-popup='tooltip' data-original-title='`+Translation('عرض جميع دفعات القروض لهذا الزبون')+`'>`+data+`</a>`;


               },
               "targets": 1
            },

            {
                "render": function(data, type, row){
                   if(data =='Loan' ){
                     status=  `<span class="label label-success btn-block ">`+data+`</span>`;
                   }else if(data =='Refund'){
                     status = '<span class="label bg-orange-400  btn-block ">'+data+'  </span>';
                   }else if(data =='Return'){
                     status = '<span class="label bg-danger  btn-block ">'+data+'  </span>';
                   }else{
                      status = '<span class="label bg-purple  btn-block ">'+data+'  </span>';
                   }
                   return  status;
                },
                "targets": 5
            },
            
            
            
           
            
            
            
            
            
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {


            if(   aData[10] == 0 ){
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('warning-active');
                });
            }

            $("#total_amount").text(currency_format_display(aData[8]))
            $("#total_paid").text(currency_format_display(aData[9]))
            $("#total_unpaid").text(currency_format_display(aData[8] - aData[9]))
        },
        "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-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(`<a 
                                      style="margin-right:10px;"
                                      data-target="#add-form-cont"
                                      href="javascript:;"
                                      class="btn bg-orange"
                                      id="add_discount_btn" onclick="add_discount();">
                                        <i class="icon-price-tag"></i> `+Translation('Refund Amount')+`
                                    </a>`);
        }

         // $("div.datatable-header").append(`<a 
         //                              style="margin-right:10px;"
         //                              data-target="#add-form-cont"
         //                              href="javascript:;"
         //                              class="btn btn-danger"
         //                              id="add_return_btn" onclick="add_return();">
         //                                <i class="icon-reset "></i> `+Translation('ترجيع مبلغ')+`
         //                            </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();
        });
    });


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

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

    // end highlight row and column

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


});



