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;
                          } 
                          
                          .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;
                          }
                          
                          .col-sm-4 {
                            width: 33.33333333%;
                          }
                          
                          .col-sm-3 {
                            width: 25%;
                          }

                        </style>

                      </head>

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

    



    var product_list_temp;
    var other_list_temp;


    function edit_items(itemid){
        var footers           =``;
        var attach            =  ``;
        var attach_other      =  ``;
        var total_rows_both   =0;
        var resp;

        
        
        $("#loaders").attr('style','');
        $("#cont_table").attr('style','display : none;');

        $("#edit_purchase_item_body").html('');



        $.ajax({
                url : 'models/crul_invoice.php',
                type : 'POST',
                data : {type:'get_edit_invoice', id : itemid},
                dataType : 'json',
                success : function(response) {
                  // console.log(response)
                  resp = response;

                  
                  $("#edit_invoice_id").val(response.invoice[0].invoice_id);
                  $("#edit_invoice_type").val(response.invoice[0].invoice_type);
                  $("#edit_is_single").val(response.invoice[0].is_single);
                  
                  total_rows_both = +response.invoice[0].total_product_cnt + +response.invoice[0].total_other_cnt;
                  $("#edit_total_rows").val(total_rows_both);
                  $("#edit_total_rows_other").val(total_rows_both);
                  

                  $("#edit_customer_id_fk").val(response.invoice[0].customer_full_name);
                  $("#edit_customer_id_fk").attr('data-fk',response.invoice[0].customer_id_fk);

                  $("#edit_pay_term").val(response.invoice[0].pay_terms);
                  $("#edit_invoice_date").val(response.invoice[0].invoice_date);
                  $("#edit_invoice_note").val(response.invoice[0].invoice_note);
                  $("#edit_invoice_number").val(response.invoice[0].invoice_number);
                  
                  $("#edit_purchase_total").val(currency_format_display(response.invoice[0].invoice_total_price_actual));
                  $("#edit_total_paid").val(currency_format_display(response.invoice[0].total_paid));

                  var total_py = response.invoice[0].total_paid;

                  if(response.invoice[0].total_paid == null){
                    total_py = '';
                  }

                  footers = `
                                <tr class="bg-teal-400">
                                  <th class="multi_lang">ﻣﺠﻤﻮﻉ</th>
                                  <th></th>
                                  <th></th>
                                  <th></th>
                                  <th></th>
                                  <th></th>
                                  <th></th>
                                  <th></th>
                                  <th></th>
                                  
                                  <th >
                                    <input id="edit_purchase_total" name="edit_purchase_total" type="text" value="`+currency_format_display(response.invoice[0].invoice_total_price_actual)+`" class="form-control text-center" readonly >
                                  </th>
                                  <th></th>
                                  <!--<th>
                                    <input id="edit_total_paid" name="edit_total_paid" type="text" value="`+currency_format_display(response.invoice[0].total_paid)+`" class="form-control text-center" readonly >
                                  </th> -->
                                  <th><i  class="icon-sigma "></i></th>
                                </tr>

                                <tr class="alpha-info">
                                  <th class="multi_lang">اﻟﺪﻓﻌﻪ</th>
                                  <th></th>
                                  <th></th>
                                  <th></th>
                                  <th></th>
                                  <th></th>
                                  <th></th>
                                  <th></th>
                                  <th></th>
                                  
                                  <th>
                                    <input data-payment_id="`+response.invoice[0].payment_id+`" id="edit_total_paid" name="edit_total_paid" type="text" value="`+(total_py)+`" class="form-control text-center" onchange="edit_calc_payments();" >
                                  </th>
                                  <th></th>
                                  
                                  <th><i  class="icon-cash "></i></th>
                                </tr>

                                `;  

                  attach      =  ``;
                  attach_other =  ``;
                     
                  // show sell item details                       
                  for(var i=0 ; i < response.invoice.length;i++){

                    // compute and format discount
                    var disss = 0;
                    if(response.invoice[i].sell_discount != '0.00'){
                      if(response.invoice[i].sell_discount_type == 0){
                      var disss = response.invoice[i].sell_discount + " %";
                      }else{
                        var disss = (response.invoice[i].sell_discount);
                      }
                    }

                    // compute total row price

                    var total_row_price = 0;

                    if(response.invoice[i].other_id_fk > 0){
                      total_row_price = response.invoice[i].sell_item_quantity * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                      total_row_price = currency_format_display(total_row_price);
                    
                    }else{
                      total_row_price = response.invoice[i].total_length * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                      total_row_price = currency_format_display(total_row_price);
                    }

                    // payment null make it 0
                    var row_payments = response.invoice[i].paid_amount
                    if(row_payments == null ){
                      row_payments = '';
                    }


                    if(response.invoice[i].product_id_fk > 0){

                       // display sell item details
                    
                      var Det = '';
                    

                      for(var j=0 ; j < response.details.length;j++){
                        var sell_id = response.invoice[i].sell_item_id;

                        if(sell_id == response.details[j].sell_item_id_fk){

                          var original_roll_length  = response.details[j].item_length;
                          var roll_id_fk            = response.details[j].purchase_item_detail_id_fk;
                          var roll_status           = response.details[j].item_status;
                          var remained_length       = response.details[j].remained_length; 
             
                          Det = Det + ` <input types="text" data-item-status="`+roll_status+`" data-remained-length="`+remained_length+`"  data-roll-id-fk="`+roll_id_fk+`" data-roll-length="`+original_roll_length+`" id="edit_row_`+i+`_roll_`+j+`" data-sell-item-id="`+sell_id+`" data-detail-id="`+response.details[j].sell_item_detail_id+`" data-purchase-id="`+response.details[j].purchase_item_detail_id_fk+`" class="badge bg-orange-400 col-sm-6" value="`+response.details[j].sell_item_detail_height+`" readonly> `;
                        }
                      }
               


                      attach = attach + `
                                            <tr  id="edit_item_row_`+i+`" data-sell-item-id="`+sell_id+`" >
                                                <td width="5%" id="edit_num_`+i+`">`+(+i + +1)+`</td>
                                                <td width="10%">
                                                 <!-- <input id="edit_product_id_fk_`+i+`" name="edit_product_id_fk_`+i+`" data-product-id="`+response.invoice[i].product_id_fk+`" data-sell-id="`+response.invoice[i].sell_item_id+`" type="text" class="form-control multi_lang" value="`+response.invoice[i].product_name+`" placeholder="ﺭﻣﺰ اﻟﻤﺎﺩﺓ" onchange="edit_load_products(this.value,this.id);" data-live-search="true" > -->

                                                  <select name="edit_product_id_fk_`+i+`" id="edit_product_id_fk_`+i+`" data-product-id="`+response.invoice[i].product_id_fk+`" data-sell-id="`+response.invoice[i].sell_item_id+`" data-width="100%" placeholder="رمز المادة" class="form-control multi_lang stop_enter" onchange="edit_load_products(this.value,this.id);" data-live-search="true">
                                                  `+product_list_temp+`
                                                  </select>

                                                  
                                                  <input id="edit_item_type_id_`+i+`" name="edit_item_type_id_`+i+`" value="`+response.invoice[i].item_type_id_fk+`" type="hidden" placeholder="ﺭﻣﺰ اﻟﻤﺎﺩﺓ">
                                                </td>
                                                <td width="10%" id="edit_forign_id_`+i+`">`+response.invoice[i].turkish_code+`</td>
                                                <td width="6%">
                                                  <input type="number" id="edit_purchase_quantity_`+i+`" name="edit_purchase_quantity_`+i+`"  class="form-control text-center multi_lang" placeholder="اﻟﻌﺪﺩ" value="`+response.invoice[i].sell_item_quantity+`"  onchange="edit_add_qty_input_fields(this.value,this.id);">
                                                </td>
                                                <td id="edit_products_`+i+`">
                                                `+Det+`
                                                </td>
                                                <td width="7%" >
                                                  <input id="edit_total_length_`+i+`" name="edit_total_length_`+i+`" value="`+response.invoice[i].total_length+`" type="text" class="form-control multi_lang" readonly placeholder="اﻟﻄﻮﻝ اﻟﻜﻠﻲ">
                                                </td>
                                                <td width="6%">
                                                  <input id="edit_last_sell_price_`+i+`" name="edit_last_sell_price_`+i+`" type="text" class="form-control multi_lang" placeholder="اﺧﺮ ﺳﻌﺮ ﺑﻴﻊ" readonly >
                                                </td>
                                                <td width="8%">
                                                  <input id="edit_buy_price_per_meter_`+i+`" name="edit_buy_price_per_meter_`+i+`" value="`+response.invoice[i].item_sell_price_per_meter+`" type="text" class="form-control multi_lang" placeholder="ﺳﻌﺮ ﺑﻴﻊ اﻟﻤﺘﺮ" onchange="edit_calc_total_item_cost(this.id,`+i+`);" >
                                                </td>
                                                <td width="8%">
                                                  <input id="edit_sell_discount_`+i+`" name="edit_sell_discount_`+i+`" value="`+response.invoice[i].sell_discount+`" data-discount-type="`+response.invoice[i].sell_discount_type+`" data-discount-actual="`+response.invoice[i].actual_discount+`" type="text" class="form-control multi_lang" placeholder="ﺗﻨﺰﻳﻼﺕ"  onchange="edit_calc_total_item_cost(this.id,`+i+`);" >
                                                </td>
                                                <td width="9%" >
                                                  <input id="edit_total_item_cost_`+i+`" name="edit_total_item_cost_`+i+`" value="`+total_row_price+`" type="text"  class="form-control text-center" readonly >
                                                </td>
                                                <td width="9%">
                                                  <input type="text" id="edit_purchase_item_note_`+i+`" name="edit_purchase_item_note_`+i+`" value="`+response.invoice[i].sell_item_notes+`" class="form-control multi_lang" placeholder="ﻣﻼﺣﻈﺎﺕ" >
                                                </td>
                                               <!-- <td width="7%" >
                                                  <input id="edit_product_pay_`+i+`" name="edit_product_pay_`+i+`" type="text" value="`+row_payments+`" data-payment-id-fk="`+response.invoice[i].invoice_payment_id+`" data-sell-id-fk="`+response.invoice[i].pay_sell_item_id_fk+`" class="form-control multi_lang text-center" placeholder="اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮﻉ" onchange="edit_calc_payments(`+i+`);">
                                                
                                                </td> -->
                                                <td width="6%">

                                                  <button class="btn btn-link btn-xs edit_btn_add_item" onclick="Add_Rows()">
                                                    <i  class="icon-add text-blue"></i>
                                                  </button>
                                                  <button class="btn btn-link btn-xs edit_btn_remove_item" id="edit_row_`+i+`" onclick="remove_rows(`+i+`);">
                                                    <i  class="icon-subtract text-danger-600"></i>
                                                  </button>
                                                  
                                                  
                                                </td>
                                              </tr>`;
                    
                    }else{ // other product

                      attach_other = attach_other + `

                                                    <tr  id="edit_item_row_other_`+i+`" >
                                                        <td width="5%" id="edit_num_`+i+`">#`+(+i + +1)+`</td>
                                                        <td width="10%" colspan="2">
                                                          <input type="text" class="form-control multi_lang" data-sell-id="`+response.invoice[i].sell_item_id+`" data-other-id="`+response.invoice[i].other_id_fk+`" value="`+response.invoice[i].product_name+`" name="edit_other_id_fk_`+i+`" id="edit_other_id_fk_`+i+`" data-width="100%" placeholder="ﻣﻮاﺩ اﺧﺮﻯ" readonly>
                                                          
                                                        </td>
                                                        
                                                        <td width="6%">
                                                          <input type="number" id="edit_other_quantity_`+i+`" name="edit_other_quantity_`+i+`" value="`+response.invoice[i].sell_item_quantity+`"  class="form-control multi_lang" placeholder="اﻟﻌﺪﺩ" onchange="edit_calc_other_cost(`+i+`);">
                                                        </td>
                                                        <td id="edit_products_other"></td>
                                                        <td width="7%" >
                                                          <input id="edit_total_length_other_`+i+`" name="edit_total_length_other_`+i+`" type="text" class="form-control" readonly >
                                                        </td>
                                                        <td width="6%">
                                                          <input id="edit_last_sell_price_other_`+i+`" name="edit_last_sell_price_other_`+i+`" type="text" class="form-control multi_lang" placeholder="اﺧﺮ ﺳﻌﺮ ﺑﻴﻊ" readonly >
                                                        </td>
                                                        <td width="8%">
                                                          <input id="edit_buy_price_per_meter_other_`+i+`" name="edit_buy_price_per_meter_other_`+i+`" value="`+response.invoice[i].item_sell_price_per_meter+`" type="text" class="form-control multi_lang" placeholder="ﺳﻌﺮ اﻟﺒﻴﻊ" onchange="edit_calc_other_cost(`+i+`);" >
                                                        </td>
                                                        <td width="8%">
                                                          <input id="edit_sell_discount_other_`+i+`" name="edit_sell_discount_other_`+i+`" value="`+response.invoice[i].sell_discount+`" data-discount-type="`+response.invoice[i].sell_discount_type+`" data-discount-actual="`+response.invoice[i].actual_discount+`" type="text" class="form-control multi_lang" placeholder="ﺗﻨﺰﻳﻼﺕ" onchange="edit_calc_other_cost(`+i+`);" >
                                                        </td>
                                                        <td width="9%" >
                                                          <input id="edit_total_item_cost_other_`+i+`" name="edit_total_item_cost_other_`+i+`" type="text" value="`+total_row_price+`" class="form-control text-center" readonly >
                                                        
                                                        </td>
                                                        <td width="9%">
                                                          <textarea type="text" id="edit_purchase_item_note_other_`+i+`" name="edit_purchase_item_note_other_`+i+`" value="`+response.invoice[i].sell_item_notes+`" class="form-control multi_lang" placeholder="ﻣﻼﺣﻈﺎﺕ" ></textarea>
                                                        </td>
                                                       <!--<td width="7%" >
                                                          <input id="edit_other_pay_`+i+`" name="edit_other_pay_`+i+`" type="text" value="`+row_payments+`" data-payment-id-fk="`+response.invoice[i].invoice_payment_id+`" data-sell-id-fk="`+response.invoice[i].pay_sell_item_id_fk+`"  class="form-control multi_lang text-center" placeholder="اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮﻉ" onchange="edit_calc_payments('other',`+i+`);" >
                                                        
                                                        </td>-->
                                                        <td width="6%">
                                                          
                                                        </td>
                                                      </tr>
                                              `;

                    }
                   
                  } // for i

                     


                      

                     
                },
                complete: function() {
                       
                      // HTML_VIEW = HTML_Table + headers + customer_details + attach + attach_other + footers;
                      $("#edit_purchase_item_body").html(attach);
                      $("#edit_purchase_item_footer").html(attach_other);
                      $("#edit_purchase_item_footer").append(footers);
                      // window.open().document.write(HTML_VIEW);

                      for(var i=0 ; i < total_rows_both;i++){ // to load product in select
                       
                        // get_products(i,resp.invoice[i].product_id_fk);

                        $("#edit_product_id_fk_"+i).val(resp.invoice[i].product_id_fk).selectpicker('refresh');

                      }

                      $("#cont_table").attr('style','');
                      $("#loaders").attr('style','display : none;')



                      // for(var i=0 ; i < total_rows_both;i++){ // to load product in select
                       
                      //   get_Others(i,resp.invoice[i].other_id_fk);
                      // }
                }

          }); // submit ajax



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

  

    function delete_items(itemid,pid) {
       
          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_invoice.php",
                  type:"POST",
                  dataType: "JSON",
                  data: {"type":"delete","obj_id":itemid} ,
                  complete:function(){
                    //hideLoader();
                  },
                  beforeSend:function(){
                    //showLoader("Deleting Purchase");
              },
                  success: function(res) {
                   
                    if(res.is_success == true){
                     
                      swal({
                                  title: "Deleted!",
                                  text: res.data,
                                  confirmButtonColor: "#66BB6A",
                                  type: "success"
                              });
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    }else{
                      swal({
                                  title: "Cancelled",
                                  text: res.data,
                                  confirmButtonColor: "#2196F3",
                                  type: "error"
                              });
                    }
                  }
              });
              }
          }); // /confirm
    }

    function Checks(id,types=null,min=null,max=null,badge=null){
        var name = $("#"+id).val();
        var placeholder = $("#"+id).attr('placeholder');
        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: Translation("اﻟﺮﺟﺎء ﻗﻢ ﺑﺎﺩﺧﺎﻝ ﻗﻴﻤﺔ ﻓﻲ اﻟﺤﻘﻞ ﻻ ﺗﻘﻞ ﻋﻦ ")+ min + Translation(" ﻭﻻ ﺗﺰﻳﺪ ﻋﻦ " + 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: Translation("اﻟﺮﺟﺎء ﻗﻢ ﺑﺎﺩﺧﺎﻝ ﻗﻴﻤﺔ ﻓﻲ اﻟﺤﻘﻞ ﻻ ﺗﻘﻞ ﻋﻦ ")+ 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: Translation("اﻟﺮﺟﺎء ﻗﻢ ﺑﺎﺩﺧﺎﻝ ﻗﻴﻤﺔ ﻓﻲ اﻟﺤﻘﻞ ﻻ ﺗﺰﻳﺪ ﻋﻦ ") + 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: Translation("ﺣﻘﻞ ") + placeholder + Translation(" ﻻ ﻳﺠﺐ اﻥ ﻳﺒﻘﻰ ﻓﺎﻍ"),
                            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: Translation("اﻟﺮﺟﺎء ﻗﻢ ﺑﺎﺩﺧﺎﻝ ﻗﻴﻤﺔ ﻋﺪﺩﻳﺔ ﺑﻴﻦ")+ min + Translation(" ﻭ ") + 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 && badge !=null){
                  if(name !='' && isNaN(name) || name < min ){
                    $("#"+id).removeClass('badge-primary');
                    $("#"+id).addClass('badge-warning');

                    noty({
                            width: 200,
                            text: Translation("اﻟﺮﺟﺎء ﻗﻢ ﺑﺎﺩﺧﺎﻝ ﻗﻴﻤﺔ ﻋﺪﺩﻳﺔ اﻛﺒﺮ ﻣﻦ ")+ min,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).removeClass('badge-warning');
                      $("#"+id).addClass('badge-primary');
                      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: Translation("اﻟﺮﺟﺎء ﻗﻢ ﺑﺎﺩﺧﺎﻝ ﻗﻴﻤﺔ ﻋﺪﺩﻳﺔ اﻛﺒﺮ اﻭ ﺗﺴﺎﻭﻱ ")+ min + Translation(" ﻓﻲ ﺣﻘﻞ ") + placeholder,
                            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: Translation("اﻟﺮﺟﺎء اﺩﺧﺎﻝ ﻗﻴﻤﺔ ﻋﺪﺩﻳﺔ اﻗﻞ ﻣﻦ ") + 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: Translation("اﻟﺮﺟﺎء اﺩﺧﺎﻝ ﻗﻴﻤﺔ ﻋﺪﺩﻳﺔ"),
                            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 show_invoice(itm,printing=null,detail_show=null){


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

          $.ajax({
                url : 'models/crul_invoice.php',
                type : 'POST',
                data : {type:'show_invoice', id : itm},
                dataType : 'json',
                success : function(response) {
                    // console.log(response)
                    
                        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">
                                        `+Translation('رقم الوصل')+`  :
                                        <span id="inv_num" style="color:red;">`+response.invoice[0].invoice_number+`</span>
                                        <br>
                                        `+Translation('التــــــــــــاريخ')+`  :  
                                        <span id="inv_date">`+response.invoice[0].invoice_date+`</span>

                                        </td>
                                        <td width=295 align="center" colspan=2 rowspan=3 style='width:221.4pt;' class="table0_td">
                                        <span id="inv_logo"> 
                                        <img src="`+COMPANY_LOGO+`" height="150px" align="left">
                                         </span>
                                        </td>
                                       </tr>
                                       
                                       <tr style='height:9.95pt'>
                                        <td width=295 colspan=4 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 colspan=6 width=118 style='width:88.55pt;' class="table0_td1">
                                            <span id="inv_address"> `+Translation(COMPANY_ADDRESS)+` </span>
                                          
                                        </td>
                                       </tr>
                                       
                                       
                                      </table>
                                      <br>
                                          `;
                        
                      customer_details = `

                                            <table  dir=rtl border=1 cellspacing=0 cellpadding=0  width=595 style='width:6.2in;border-collapse:collapse;border:none'>
                                             <tr style='page-break-inside:avoid;' class="td_head">
                                              <td width=307 style='width:3.2in;' class="table1_td">
                                              `+Translation('اﺳﻢ اﻟﺰﺑﻮﻥ')+`
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td">
                                              `+Translation('ﺭﻗﻢ اﻟﻬﺎﺗﻒ')+`
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td last_td">
                                              `+Translation('اﻟﻌﻨﻮاﻥ')+`
                                              </td>
                                             </tr>
                                             <tr style='page-break-inside:avoid;' class="td_body">
                                              <td width=307 style='width:3.2in;' class="table1_td1">
                                              <span  id="inv_customer_name"> `+response.invoice[0].customer_full_name+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_phone"> `+response.invoice[0].customer_phone+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_address"> `+response.invoice[0].customer_address+` </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;' class="table2_td">
                                   `+Translation('اﻟﻤﺎﺩﺓ')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td">
                                   `+Translation('اﻟﻜﻤﻴﺔ')+` 
                                    </td>
                                    <td width=114 style='width:85.5pt;' class="table2_td">
                                   `+Translation('اﻟﺘﻔﺎﺻﻴﻞ')+` 
                                    </td>
                                    <td width=87 style='width:65.25pt;' class="table2_td">
                                   `+Translation('اﻟﻄﻮﻝ اﻟﻜﻠﻲ')+` 
                                    </td>
                                    <td width=73 style='width:54.9pt;' class="table2_td">
                                   `+Translation('ﺳﻌﺮ اﻟﻮﺣﺪﺓ')+` 
                                    </td>
                                    <td width=79 style='width:58.95pt;' class="table2_td">
                                   `+Translation('ملاحظات')+` 
                                    </td>
                                    <td width=74 style='width:55.5pt;' class="table2_td last_td">
                                   `+Translation('اﻟﻤﺠﻤﻮﻉ')+` 
                                    </td>
                                   </tr>`;
                     
                      // show sell item details                       
                      for(var i=0 ; i < response.invoice.length;i++){

                        // compute and format discount
                        var disss = 0;
                        if(response.invoice[i].sell_discount != '0.00'){
                          if(response.invoice[i].sell_discount_type == 0){
                          var disss = response.invoice[i].sell_discount + " %";
                          }else{
                            var disss = currency_format_display(response.invoice[i].sell_discount);
                          }
                        }

                        // compute total row price

                        var total_row_price = 0;

                        if(response.invoice[i].other_id_fk > 0){
                          total_row_price = response.invoice[i].sell_item_quantity * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price = currency_format_display(total_row_price);
                        
                        }else{
                          total_row_price = response.invoice[i].total_length * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price = currency_format_display(total_row_price);
                        }



                        if(response.invoice[i].product_id_fk > 0){
  
                           // display sell item details
                        
                          var Det = '';
                          if(detail_show != null){

                            for(var j=0 ; j < response.details.length;j++){
                              var sell_id = response.invoice[i].sell_item_id;

                              if(sell_id == response.details[j].sell_item_id_fk){
                                // Det = Det + ` <input types="text"  class=" col-sm-4" value="`+response.details[j].sell_item_detail_height+`" readonly> `;
                                Det = Det + ` <span style="border: 1px solid black"  class="">`+response.details[j].sell_item_detail_height+`</span> `;
                              }
                            }
                          }


                          attach = attach + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(+i +1)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+parseInt(response.invoice[i].sell_item_quantity)+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt; font-family:  Times, serif;'>
                                                      <span  id="inv_details">
                                            `+Det+`         </span>
                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].total_length+` ﻡ </span>
                                                    </td>
                                                    <td width=73 style='width:54.9pt;'>
                                                      <span  id="inv_unit_price"> `+currency_format_display(response.invoice[i].item_sell_price_per_meter)+` </span>
                                                    </td>
                                                    <td width=79 style='width:58.95pt;'>
                                                      <span  id="inv_discount">`+ response.invoice[i].sell_item_notes +` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                   </tr>
                                                  `;
                        
                        }else{ // other product

                          attach_other = attach_other + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(response.invoice.length)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt;'>
                                                      <span  id="inv_details">
                                                      </span>
                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length">  </span>
                                                    </td>
                                                    <td width=73 style='width:54.9pt;'>
                                                      <span  id="inv_unit_price"> `+currency_format_display(response.invoice[i].item_sell_price_per_meter)+` </span>
                                                    </td>
                                                    <td width=79 style='width:58.95pt;'>
                                                      <span  id="inv_discount">`+ response.invoice[i].sell_item_notes +` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                   </tr>
                                                  `;

                        }
                       
                      } // for i

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

                      var det_acc = ``;

                      if(detail_show != null){

                          det_acc = `<tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('ﺣﺴﺎﺏ اﻟﺰﺑﻮﻥ اﻟﻜﻠﻲ')+` 
                                  </td>
                                  <td width=74 colspan=2 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.account[0].total_invoice_price_all)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in; color:#2b9408'>
                                 `+Translation('اﻟﻤﺒﻠﻎ اﻟﻜﻠﻲ اﻟﻤﺪﻓﻮﻉ')+` 
                                  </td>
                                  <td width=74 colspan=2 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.account[0].total_Paid_all)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in; color:#2b9408'>
                                 `+Translation('خصومات الحساب الكلية')+`
                                  </td>
                                  <td width=74 colspan=2 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.account[0].total_payment_discount)+`
                                  </td>
                                 </tr>`;

                      }

                      footers =`<tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=439 colspan=7  style='width:329.05pt;border-top:solid #984806 1.0pt;
                                  border-left:solid #984806 1.0pt;border-bottom:none;border-right:none;
                                  background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                 `+Translation('اﻟﺘﻨﺰﻳﻼﺕ')+` 
                                  </td>
                                  

                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].total_discount)+`
                                  </td>

                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=7 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('اﻟﻤﺒﻠﻎ اﻟﻜﻠﻲ ﻟﻠﻮﺻﻞ')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].invoice_total_price_actual)+`
                                  </td>
                                 </tr>

                                 <tr style='page-break-inside:avoid;height:.1in; background: white;'>
                                  
                                  <td width=591 colspan=8 style='width:443.5pt;border:none;
                                  border-bottom:solid #984806 1.0pt; background: white;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   &nbsp;
                                  </td>
                                  
                                 </tr>

                                 <!--
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('ﺣﺴﺎﺏ اﻟﺰﺑﻮﻥ اﻟﻜﻠﻲ')+` 
                                  </td>
                                  <td width=74 colspan=2 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.account[0].total_invoice_price_all)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in; color:#2b9408'>
                                 `+Translation('اﻟﻤﺒﻠﻎ اﻟﻜﻠﻲ اﻟﻤﺪﻓﻮﻉ')+` 
                                  </td>
                                  <td width=74 colspan=2 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.account[0].total_Paid_all)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in; color:#2b9408'>
                                 `+Translation('خصومات الحساب الكلية')+`
                                  </td>
                                  <td width=74 colspan=2 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.account[0].total_payment_discount)+`
                                  </td>
                                 </tr>
                                 -->
                                 ${det_acc}
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in; color:#b92909'>
                                 `+Translation('اﻟﻤﺒﻠﻎ اﻟﻜﻠﻲ اﻟﻤﺘﺒﻘﻲ')+` 
                                  </td>
                                  <td width=74 colspan=2 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.account[0].total_remained_all)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.3in'>
                                 
                                  <td width=517 colspan=8  style='width:388.0pt;border:none;background:white;
                                    padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                    <span id="inv_note">`+Translation('ﻣﻼﺣﻈﺔ')+` : `+response.invoice[0].invoice_note+` </span>
                                  </td>
                                 </tr>
                                 
                                 <tr style='page-break-inside:avoid;height:.1in; background-color: white'>
                                  <td width=517 colspan=7  style='width:388.0pt;border:none;
                                  padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                  
                                  </td>
                                  <td width=74 style='width:55.5pt;border:none;padding:2.15pt .15in 2.15pt .15in;
                                  height:.1in'>
                                 `+Translation('اﻟﺘﻮﻗﻴﻊ')+` 
                                  </td>
                                 </tr>
                                </table>

                                </div>




                                </body>

                                `+print_attach+`

                                </html>`;

                      

                     
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                       HTML_VIEW = HTML_Table + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                        window.open().document.write(HTML_VIEW);
                }

          }); // submit ajax


    }

    

    function add_payments(itm,printing=null){

          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";
          $.ajax({
                url : 'models/crul_invoice.php',
                type : 'POST',
                data : {type:'show_payments_for_add', id : itm},
                dataType : 'json',
                success : function(response) {
                    
                    $("#customer_id_fk_pay").val(response.invoice[0].customer_id)
                    
                    $('span[id$="total_customer_account"]').html(currency_format_display(response.invoice[0].total_invoice_price));
                    $('span[id$="total_customer_account"]').attr('data-original-amount',(response.invoice[0].total_invoice_price));
                    
                    $('span[id$="total_customer_discount"]').html(currency_format_display(response.invoice[0].total_payment_discount));
                    $('span[id$="total_customer_discount"]').attr('data-original-amount',(response.invoice[0].total_payment_discount));
                    
                    $('span[id$="total_customer_paid"]').html(currency_format_display(response.invoice[0].total_Paid));
                    $('span[id$="total_customer_paid"]').attr('data-original-amount',(response.invoice[0].total_Paid));
                 
                    $('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));
                         
                      
                   

                      

                     
                },
                complete: function() {
                      

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

          }); // submit ajax


    }

    function show_payments(itm,printing=null){

          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";
          $.ajax({
                url : 'models/crul_invoice.php',
                type : 'POST',
                data : {type:'show_payments', id : itm},
                dataType : 'json',
                success : function(response) {
                    console.log(response)
                    
                        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;">`+response.invoice[0].invoice_number+`</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">`+response.invoice[0].invoice_date+`</span>
                                        </td>
                                       </tr>
                                       
                                       
                                      </table>
                                      <br>
                                          `;
                        
                        customer_details = `

                                            <table  dir=rtl border=1 cellspacing=0 cellpadding=0  width=595 style='width:6.2in;border-collapse:collapse;border:none'>
                                             <tr style='page-break-inside:avoid;' class="td_head">
                                              <td width=307 style='width:3.2in;' class="table1_td">
                                             `+Translation('اﺳﻢ اﻟﺰﺑﻮﻥ')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td">
                                             `+Translation('ﺭﻗﻢ اﻟﻬﺎﺗﻒ')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td last_td">
                                             `+Translation('اﻟﻌﻨﻮاﻥ')+` 
                                              </td>
                                             </tr>
                                             <tr style='page-break-inside:avoid;' class="td_body">
                                              <td width=307 style='width:3.2in;' class="table1_td1">
                                              <span  id="inv_customer_name"> `+response.invoice[0].customer_full_name+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_phone"> `+response.invoice[0].customer_phone+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_address"> `+response.invoice[0].customer_address+` </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;' class="table2_td">
                                   `+Translation('اﻟﻤﺎﺩﺓ')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td">
                                   `+Translation('اﻟﻜﻤﻴﺔ')+` 
                                    </td>
                                    <td width=74 style='width:55.5pt;' class="table2_td ">
                                   `+Translation('ﻣﺠﻤﻮﻉ اﻟﺴﻌﺮ')+` 
                                    </td>
                                    <td width=114 style='width:85.5pt;' class="table2_td">
                                   `+Translation('اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮﻉ')+` 
                                    </td>
                                    <td width=87 style='width:65.25pt;' class="table2_td">
                                   `+Translation('ﺗﺎﺭﻳﺦ اﻟﺪﻓﻊ')+` 
                                    </td>
                                    <td width=152 style='width:113.85pt;' class="table2_td last_td">
                                   `+Translation('ﻣﻼﺣﻈﺎﺕ')+` 
                                    </td>
                                    
                                    
                                   </tr>`;
                     
                      // show sell item details                       
                      for(var i=0 ; i < response.invoice.length;i++){

                        // compute and format discount
                        var disss = 0;
                        if(response.invoice[i].sell_discount != '0.00'){
                          if(response.invoice[i].sell_discount_type == 0){
                          var disss = response.invoice[i].sell_discount + " %";
                          }else{
                            var disss = currency_format_display(response.invoice[i].sell_discount);
                          }
                        }

                        // compute total row price

                        var total_row_price = 0;

                        if(response.invoice[i].other_id_fk > 0){
                          total_row_price = response.invoice[i].sell_item_quantity * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price = currency_format_display(total_row_price);
                        
                        }else{
                          total_row_price = response.invoice[i].total_length * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price = currency_format_display(total_row_price);
                        }



                        if(response.invoice[i].product_id_fk > 0){
  

                          attach = attach + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(i)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt; font-family:  Times, serif;'>
                                                      <span  id="inv_details"> `+currency_format_display(response.invoice[i].paid_amount)+` </span>
                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].paid_date+`  </span>
                                                    </td>
                                                    <td width=152 style='width:113.85pt;'>
                                                      <span  id="inv_unit_price"> `+(response.invoice[i].payment_note)+` </span>
                                                    </td>
                                                    
                                                    
                                                   </tr>
                                                  `;
                        
                        }else{ // other product

                          attach_other = attach_other + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(response.invoice.length)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt;'>
                                                      <span  id="inv_details">`+currency_format_display(response.invoice[i].paid_amount)+` </span>
                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].paid_date+` </span>
                                                    </td>
                                                    <td width=152 style='width:113.85pt;'>
                                                      <span  id="inv_unit_price"> `+(response.invoice[i].payment_note)+` </span>
                                                    </td>
                                                    
                                                    
                                                   </tr>
                                                  `;

                        }
                       
                      } // for i

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

                      total_pay = response.invoice[0].total_paid; // to check if havnt payment show msg not have payment
                      footers =`
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('اﻟﺘﻨﺰﻳﻼﺕ')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].total_discount)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('اﻟﻤﺒﻠﻎ اﻟﻜﻠﻲ')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].invoice_total_price_actual)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮﻉ')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_paid)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('اﻟﻤﺒﻠﻎ اﻟﻤﺘﺒﻘﻲ')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_remained)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.3in'>
                                 
                                  <td width=517 colspan=7  style='width:388.0pt;border:none;background:white;
                                    padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                    <span id="inv_note">`+Translation('ﻣﻼﺣﻈﺔ')+` : `+response.invoice[0].invoice_note+` </span>
                                  </td>
                                 </tr>
                                 
                                 <tr style='page-break-inside:avoid;height:.1in; background-color: white'>
                                  <td width=517 colspan=6  style='width:388.0pt;border:none;
                                  padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                  
                                  </td>
                                  <td width=74 style='width:55.5pt;border:none;padding:2.15pt .15in 2.15pt .15in;
                                  height:.1in'>
                                 `+Translation('اﻟﺘﻮﻗﻴﻊ')+` 
                                  </td>
                                 </tr>
                                </table>

                                </div>




                                </body>

                                `+print_attach+`

                                </html>`;

                      

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

                      HTML_VIEW_PAY = HTML_Table + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                      if(total_pay == null || total_pay ==''){
                        noty({
                            width: 200,
                            text: Translation("ﻫﺬﻩ اﻟﻮﺻﻞ ﻻ ﻳﺤﺘﻮﻱ ﻋﻠﻰ اﻱ ﺩﻓﻮﻋﺎﺕ"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',

                          });
                      }else{
                        $("#invoice_show").html(HTML_VIEW_PAY);
                        $("#inv_numb").val(itm);

                        $('#show_payments_modal').modal('toggle');
                      }
                     
                        // window.open().document.write(HTML_VIEW);
                }

          }); // submit ajax


    }


    function edit_payments(itm,printing=null){

          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";
          $.ajax({
                url : 'models/crul_invoice.php',
                type : 'POST',
                data : {type:'show_payments', id : itm},
                dataType : 'json',
                success : function(response) {
                    console.log(response)
                    
                       
                        customer_details = `

                                            <table  dir=rtl border=1 cellspacing=0 cellpadding=0  width=595 style='width:90%;border-collapse:collapse;border:none'>
                                             <tr style='page-break-inside:avoid;' class="td_head">
                                              <td width=307 style='width:3.2in;' class="table1_td">
                                             `+Translation('اﺳﻢ اﻟﺰﺑﻮﻥ')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td">
                                             `+Translation('ﺭﻗﻢ اﻟﻬﺎﺗﻒ')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td last_td">
                                             `+Translation('اﻟﻌﻨﻮاﻥ')+` 
                                              </td>
                                             </tr>
                                             <tr style='page-break-inside:avoid;' class="td_body">
                                              <td width=307 style='width:3.2in;' class="table1_td1">
                                              <span  id="inv_customer_name"> `+response.invoice[0].customer_full_name+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_phone"> `+response.invoice[0].customer_phone+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_address"> `+response.invoice[0].customer_address+` </span>
                                              </td>
                                             </tr>
                                            </table>
                                            <br>
                                            `;

                      attach =  `
                                  <table id="inv_table"  dir=rtl border=1 cellspacing=0 cellpadding=0 width=591 style='width:90%;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;' class="table2_td">
                                   `+Translation('اﻟﻤﺎﺩﺓ')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td">
                                   `+Translation('اﻟﻜﻤﻴﺔ')+` 
                                    </td>
                                    <td width=74 style='width:55.5pt;' class="table2_td ">
                                   `+Translation('ﻣﺠﻤﻮﻉ اﻟﺴﻌﺮ')+` 
                                    </td>
                                    <td width=114 style='width:85.5pt;' class="table2_td">
                                   `+Translation('اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮﻉ')+` 
                                    </td>
                                    <td width=87 style='width:65.25pt;' class="table2_td">
                                   `+Translation('ﺗﺎﺭﻳﺦ اﻟﺪﻓﻊ')+` 
                                    </td>
                                    <td width=152 style='width:113.85pt;' class="table2_td">
                                   `+Translation('ﻣﻼﺣﻈﺎﺕ')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td last_td">
                                   `+Translation('اﻟﻌﻤﻠﻴﺎﺕ')+` 
                                    </td>
                                    
                                    
                                   </tr>`;
                     
                      // show sell item details                       
                      for(var i=0 ; i < response.invoice.length;i++){

                        // compute and format discount
                        var disss = 0;
                        if(response.invoice[i].sell_discount != '0.00'){
                          if(response.invoice[i].sell_discount_type == 0){
                          var disss = response.invoice[i].sell_discount + " %";
                          }else{
                            var disss = currency_format_display(response.invoice[i].sell_discount);
                          }
                        }

                        // compute total row price

                        var total_row_price = 0;

                        if(response.invoice[i].other_id_fk > 0){
                          total_row_price = response.invoice[i].sell_item_quantity * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price = currency_format_display(total_row_price);
                        
                        }else{
                          total_row_price = response.invoice[i].total_length * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price = currency_format_display(total_row_price);
                        }



                        if(response.invoice[i].product_id_fk > 0){
  

                          attach = attach + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(i)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt; font-family:  Times, serif;'>
                                                      <input type="text" id="edit_inv_paid_price_`+i+`" data-payment-id-fk="`+response.invoice[i].invoice_payment_id+`" data-sell-id-fk="`+response.invoice[i].sell_item_id+`" name="edit_inv_paid_price_`+i+`" class="form-control text-center text-success text-black" placeholder="`+Translation('اﻟﺪﻓﻌﺔ اﻟﺠﺪﻳﺪﺓ')+`" value="`+currency_format_display(response.invoice[i].paid_amount)+`"  >  

                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].paid_date+`  </span>
                                                    </td>
                                                    <td width=152 style='width:113.85pt;'>
                                                      <textarea type="text" id="edit_pay_note_`+i+`" name="edit_pay_note_`+i+`" class="form-control" placeholder="`+Translation('ﻣﻼﺣﻈﺎﺕ')+`" >`+(response.invoice[i].payment_note)+`</textarea> 

                                                    </td>
                                                    
                                                    <td width=64 style='width:48.3pt;'>
                                                      
                                                      <div class=" " >
                                                       <a id="save_payment_btn_`+i+`" class="btn btn-primary btn-xs" style="margin-top: 3px; margin-bottom: 3px; padding: 4px 7px;" onclick="update_payments(this.id)" data-popup="tooltip" data-original-title="`+Translation('ﺣﻔﻆ')+`">
                                                          <i class="icon-floppy-disk"></i>
                                                       </a>
                                                       <a id="remove_payment_btn_`+i+`" class="btn btn-danger btn-xs" style="margin-top: 3px; margin-bottom: 3px; padding: 4px 7px;" onclick="remove_payments(this.id)" data-popup="tooltip" data-original-title="`+Translation('ﺣﺬﻑ اﻟﺪﻓﻌﺔ')+`">
                                                          <i class="icon-x"></i>
                                                       </a>
                                                      </div>
                                                    </td>
                                                    
                                                   </tr>
                                                  `;
                        
                        }else{ // other product

                          attach_other = attach_other + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(response.invoice.length)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt;'>
                                                      <input type="text" id="edit_inv_paid_price_other`+i+`" data-payment-id-fk="`+response.invoice[i].invoice_payment_id+`" data-sell-id-fk="`+response.invoice[i].sell_item_id+`" name="edit_inv_paid_price_other" class="form-control text-center text-success text-black" placeholder="`+Translation('اﻟﺪﻓﻌﺔ اﻟﺠﺪﻳﺪﺓ')+`" value="`+currency_format_display(response.invoice[i].paid_amount)+`"  >  

                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].paid_date+` </span>
                                                    </td>
                                                    <td width=152 style='width:113.85pt;'>
                                                      <textarea type="text" id="edit_pay_note_other`+i+`" name="edit_pay_note_other`+i+`" class="form-control" placeholder="`+Translation('ﻣﻼﺣﻈﺎﺕ')+`" >`+(response.invoice[i].payment_note)+`</textarea> 

                                                    </td>
                                                    
                                                    <td width=64 style='width:48.3pt;'>
                                                      
                                                      <div class=" " >
                                                       <a id="save_payment_btn_other`+i+`" class="btn btn-primary btn-xs" style="margin-top: 3px; margin-bottom: 3px; padding: 4px 7px;" onclick="update_payments(this.id)" data-popup="tooltip" data-original-title="`+Translation('ﺣﻔﻆ')+`">
                                                          <i class="icon-floppy-disk"></i>
                                                       </a>
                                                       <a id="remove_payment_btn_other`+i+`" class="btn btn-danger btn-xs" style="margin-top: 3px; margin-bottom: 3px; padding: 4px 7px;" onclick="remove_payments(this.id)" data-popup="tooltip" data-original-title="`+Translation('ﺣﺬﻑ ﺩﻓﻌﺔ')+`">
                                                          <i class="icon-x"></i>
                                                       </a>
                                                      </div>
                                                    </td>

                                                   </tr>
                                                  `;

                        }
                       
                      } // for i

                     

                      total_pay = response.invoice[0].total_paid; // to check if havnt payment show msg not have payment
                      footers =`
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('اﻟﺘﻨﺰﻳﻼﺕ')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].total_discount)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('اﻟﻤﺒﻠﻎ اﻟﻜﻠﻲ')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].invoice_total_price_actual)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮﻉ')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_paid)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('اﻟﻤﺒﻠﻎ اﻟﻤﺘﺒﻘﻲ')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_remained)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.3in'>
                                 
                                  <td width=517 colspan=7  style='width:388.0pt;border:none;background:white;
                                    padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                    <span id="inv_note">`+Translation('ﻣﻼﺣﻈﺔ')+` : `+response.invoice[0].invoice_note+` </span>
                                  </td>
                                 </tr>
                                 
                                 <tr style='page-break-inside:avoid;height:.1in; background-color: white'>
                                  <td width=517 colspan=6  style='width:388.0pt;border:none;
                                  padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                  
                                  </td>
                                  <td width=74 style='width:55.5pt;border:none;padding:2.15pt .15in 2.15pt .15in;
                                  height:.1in'>
                                 `+Translation('اﻟﺘﻮﻗﻴﻊ')+` 
                                  </td>
                                 </tr>
                                </table>

                                </div>




                                </body>

                                `+print_attach+`

                                </html>`;

                      

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

                      HTML_VIEW_PAY = HTML_Table + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                      if(total_pay == null || total_pay ==''){
                        noty({
                            width: 200,
                            text: Translation("ﻫﺬﻩ اﻟﻮﺻﻞ ﻻ ﻳﺤﺘﻮﻱ ﻋﻠﻰ اﻱ ﺩﻓﻮﻋﺎﺕ"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',

                          });
                      }else{
                        $("#edit_payments_fields").html(HTML_VIEW_PAY);
                        $("#edit_pay_inv_id").val(itm);

                        $('#edit_payments_modal').modal('toggle');
                      }
                     
                        // window.open().document.write(HTML_VIEW);
                }

          }); // submit ajax


    }

    function update_payments (id){

        var row_num1        = id.split('_');
        var row_num         = row_num1[3];
        // alert(row_num)
        var inv_id          = $("#edit_pay_inv_id").val();
        var notes           = $("#edit_pay_note_"+row_num).val();
        var paid            = $("#edit_inv_paid_price_"+row_num).val();
        var sell_id_fk      = $("#edit_inv_paid_price_"+row_num).attr("data-sell-id-fk");
        var payment_id      = $("#edit_inv_paid_price_"+row_num).attr("data-payment-id-fk");

        if (paid.indexOf('$') > -1)
          {
            
             paid = paid.replace('$','');
            
          }

        if (paid.indexOf(',') > -1)
          {
            
             paid = paid.replace(/,/g,'');
            
          }

          paid = parseFloat(paid);

        var check1          = true;

        if(paid == '' || paid <= 0 || paid == null || paid == undefined || isNaN(paid)){
            noty({
                    width: 200,
                    text: Translation('اﻟﺮﺟﺎء ﻗﻢ ﺑﺎﺩﺧﺎﻝ ﻣﺒﻠﻎ ﺩﻓﻌﻪ'),
                    type: 'success',
                    dismissQueue: true,
                    timeout: 2000,
                    layout: 'topRight',
              });
            check1 = false;
        }



        if(check1){
            $("#save_payment_"+row_num).attr('disabled',true);
            $.ajax({
                url: "models/crul_invoice.php",
                type:"POST",
                dataType: "JSON",
                data : {inv_id              :inv_id,
                        paid                :paid,
                        sell_ids            :sell_id_fk,
                        payment_id          :payment_id,
                        notes               :notes,
                        type                :'update_payments'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                   

                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    $('#edit_payments_modal').modal('toggle');
                    
                    noty({
                                    width: 200,
                                    text: Translation(res.data),
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 2000,
                                    layout: 'topRight',
                                    callback: {
                                              onShow: function() {},
                                              afterShow: function() {},
                                              onClose: function() {},
                                              afterClose: function() {},
                                              onCloseClick: function() {},
                                            },
                              });

                    // i will reload the page to reset all fields
                    
               
                }else{
                    swal({
                        title: Translation("ﺧﻄﺄ"),
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                    //$("#add-form-cont").collapse('hide');
                }

                
                $("#save_payment_"+row_num).attr('disabled',false);
            })
            .fail(function(err) {
                 swal({
                    title: Translation("ﺧﻄﺄ"),
                    text: Translation(err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                
                $("#save_payment_"+row_num).attr('disabled',false);

            })
            .always(function() {
                console.log("complete");
            });
          }else{
              noty({
                    width: 200,
                    text: Translation('اﻟﺮﺟﺎء اﻟﺘﺄﻛﺪ ﻣﻦ اﻟﻘﻴﻢ اﻟﻤﺪﺧﻠﺔ ﻭاﻳﻀﺎ ﻳﺠﺐ اﺩﺧﺎﻝ ﺩﻓﻌﺔ ﺟﺪﻳﺪﺓ ﻋﻠﻰ اﻻﻗﻞ'),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
          }

        
    }


    function remove_payments (id){

          swal({
              title: Translation("ﻫﻞ اﻧﺖ ﻣﺘﺄﻛﺪ؟!"),
              text: Translation("ﺳﻮﻑ ﻟﻦ ﺗﺴﺘﻄﻴﻊ اﺳﺘﺮﺟﺎﻉ اﻟﻤﻌﻠﻮﻣﺎﺕ اﻟﻤﺮﺗﺒﻄﺔ ﺑﻬﺬا اﻟﺴﺠﻞ ﻓﻲ ﺣﺎﻟﺔ اﻟﻤﺴﺢ"),
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "#EF5350",
              confirmButtonText: Translation("ﻣﻮاﻓﻖ: اﻣﺴﺢ!"),
              cancelButtonText: Translation("اﻟﻐﺎء اﻻﻣﺮ"),
              closeOnConfirm: true,
              closeOnCancel: true
          },
          function(isConfirm){
              if (isConfirm) {

                        var row_num1        = id.split('_');
                        var row_num         = row_num1[3];

                        var inv_id          = $("#edit_pay_inv_id").val();
                        var notes           = $("#edit_pay_note_"+row_num).val();
                        var paid            = $("#edit_inv_paid_price_"+row_num).val();
                        var sell_id_fk      = $("#edit_inv_paid_price_"+row_num).attr("data-sell-id-fk");
                        var payment_id      = $("#edit_inv_paid_price_"+row_num).attr("data-payment-id-fk");

                        if (paid.indexOf('$') > -1)
                          {
                            
                            var paid = parseFloat(paid.replace('$',''));
                            
                          }

                        var check1          = true;

                        



                        if(check1){
                            $("#remove_payment_btn_"+row_num).attr('disabled',true);
                            $.ajax({
                                url: "models/crul_invoice.php",
                                type:"POST",
                                dataType: "JSON",
                                data : {inv_id              :inv_id,
                                        paid                :paid,
                                        sell_ids            :sell_id_fk,
                                        payment_id          :payment_id,
                                        notes               :notes,
                                        type                :'delete_payments'}
                            })
                            .done(function(res) {
                               
                                  if(res.is_success == true){

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

                                   

                                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                                    $('#edit_payments_modal').modal('toggle');
                                    
                                    noty({
                                                    width: 200,
                                                    text: Translation(res.data),
                                                    type: 'success',
                                                    dismissQueue: true,
                                                    timeout: 2000,
                                                    layout: 'topRight',
                                                    callback: {
                                                              onShow: function() {},
                                                              afterShow: function() {},
                                                              onClose: function() {},
                                                              afterClose: function() {},
                                                              onCloseClick: function() {},
                                                            },
                                              });

                                    // i will reload the page to reset all fields
                                    
                               
                                }else{
                                    swal({
                                        title: Translation("ﺧﻄﺄ"),
                                        text: Translation(res.data),
                                        confirmButtonColor: "#66BB6A",
                                        type: "warning"
                                    });
                                    //$("#add-form-cont").collapse('hide');
                                }

                                
                                $("#remove_payment_btn_"+row_num).attr('disabled',false);
                            })
                            .fail(function(err) {
                                 swal({
                                    title: Translation("ﺧﻄﺄ"),
                                    text: Translation(err),
                                    confirmButtonColor: "#66BB6A",
                                    type: "error"
                                });
                                
                                $("#remove_payment_btn_"+row_num).attr('disabled',false);

                            })
                            .always(function() {
                                console.log("complete");
                            });
                        }else{
                            noty({
                                  width: 200,
                                  text: Translation('اﻟﺮﺟﺎء اﻟﺘﺄﻛﺪ ﻣﻦ اﻟﻘﻴﻢ اﻟﻤﺪﺧﻠﺔ ﻭاﻳﻀﺎ ﻳﺠﺐ اﺩﺧﺎﻝ ﺩﻓﻌﺔ ﺟﺪﻳﺪﺓ ﻋﻠﻰ اﻻﻗﻞ'),
                                  type: 'success',
                                  dismissQueue: true,
                                  timeout: 3000,
                                  layout: 'topRight',
                            });
                        }
               
              }
          }); // /confirm



        
    }


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

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


    function compute_remain_price(val, id){

      var row_num1 = id.split('_');
      var row_num = row_num1[3];
      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_paid   = $("#inv_total_paid_"+row_num).attr('data-old-paid-price');
        
          // alert("old_paid="+old_paid)

        if(real_price == null || real_price == undefined || isNaN(real_price)){real_price=0;}
        if(old_paid   == null || old_paid   == undefined || isNaN(old_paid)){old_paid=0; }
       
        var new_remaind = real_price - (+old_paid + +val);

       
        if(new_remaind < 0){

           noty({
                  width: 200,
                  text: Translation("اﻟﺮﺟﺎء اﻟﺘﺄﻛﺪ ﻣﻦ اﻟﻘﻴﻤﺔ اﻟﻤﺪﺧﻠﺔ ﻻﻥ اﻟﻤﺪﻓﻮﻋﺎﺕ اﺻﺒﺤﺖ اﻛﺒﺮ ﻣﻦ اﻟﺴﻌﺮ اﻟﻜﻠﻲ ﻟﻠﻤﺎﺩﺓ"),
                  type: 'error',
                  dismissQueue: true,
                  timeout: 4000,
                  layout: 'topRight',
                });

          // $("#inv_row_remaind_price_"+row_num).val('');
          $("#"+id).val('');
          $("#inv_row_remaind_price_"+row_num).val(currency_format_display( real_price - old_paid));
        }else{
          $("#inv_row_remaind_price_"+row_num).val(currency_format_display( new_remaind));

        }

         // compute total invoice paid and total remained
          var sum = 0;        

          $('input[id^="inv_paid_price_"]').each(function() 
          { 
            if(!isNaN(this.value) && this.value.length!=0) 
            {
              sum += parseFloat(this.value);            
            }         
          });

          var old_papid   = $("#total_inv_paid").attr('data-total-inv-paid');
          if(old_papid   == null || old_papid   == undefined || isNaN(old_papid)){old_papid=0; }

          var new_pay = +old_papid + +sum;
          $("#total_inv_paid").html(currency_format_display(new_pay));

          var old_actual_price   = $("#total_inv_actual").attr('data-total-inv-actual');
          if(old_actual_price   == null || old_actual_price   == undefined || isNaN(old_actual_price)){old_actual_price=0; }

          var all_invoice_remaind = old_actual_price - new_pay;
          $("#total_inv_remain").html(currency_format_display(all_invoice_remaind));


    }
    

    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('Download')+' <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 get_Stock(){

            $.ajax({
                  url : 'models/crul_stock.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option value="" selected="selected">'+Translation('ﺗﺤﺪﻳﺪ اﻟﻤﺨﺰﻥ')+'</option>';
                      var aaa='';
                        for(var i=response.length-1 ; i >= 0;i--){
                          var tp =Translation("ﺧﺰﻥ");
                          if(response[i][2]==1){tp =Translation("اﻧﺘﺎﺝ");}
                          attach = attach + '<option data-subtext="'+tp+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          aaa = aaa + '<option  value="'+response[i][0]+'">'+response[i][1]+'</option>';

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

            }); // submit ajax

    }


    function get_Item_Class(){

            $.ajax({
                  url : 'models/crul_items.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option value="0" selected="selected">'+Translation('ﺟﻤﻴﻊ اﻻﺻﻨﺎﻑ')+'</option>';
                      var aaa='';
                        for(var i=response.length-1 ; i >= 0;i--){
                          
                          attach = attach + '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          
                        }
                        $("#item_type_id_fk").html(attach);
                        
                        $('#item_type_id_fk').selectpicker('refresh');
                        
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

    }


    function get_Profile_price(){

            $.ajax({
                  url : 'models/crul_profile_price.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option value="" selected="selected">'+Translation('ﺗﺤﺪﻳﺪ ﻣﻠﻒ اﻟﺴﻌﺮ')+'</option>';
                      var aaa='';
                        for(var i=response.length-1 ; i >= 0;i--){
                          var tp ="";
                          attach = attach + '<option data-subtext="'+tp+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          aaa = aaa + '<option  value="'+response[i][0]+'">'+response[i][1]+'</option>';

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

            }); // submit ajax

    }



    function get_Customer(){

            $.ajax({
                  url : 'models/crul_customer.php',
                  type : 'POST',
                  data : {type:'get_Customer',cust_typ:0},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option value="" selected="selected">'+Translation('ﺗﺤﺪﻳﺪ اﻟﺰﺑﻮﻥ')+'</option>';
                      var aaa='';
                        for(var i=response.length-1 ; i >= 0;i--){
                          var tp  = response[i][2];
                          var tp1 = response[i][3];
                          attach = attach + '<option data-subtext="'+Translation('ﻫﺎﺗﻒ')+': '+tp+' || E-Mail: '+tp1+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          aaa = aaa + '<option  value="'+response[i][0]+'">'+response[i][1]+'</option>';

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

            }); // submit ajax

    }

    var products_array_values =[] ;

    // make products as searchable list

    function get_products(row_num,edit=null){
          
          $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get_product_sell'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option value="" selected="selected">'+Translation('اﺧﺘﻴﺎﺭ اﻟﻤﺎﺩﺓ')+'</option>';
                        for(var i=response.length-1 ; i >= 0;i--){
                          
                          var tp =response[i][2];
                          var BC =response[i][4];
                          attach = attach + '<option  data-subtext="'+Translation('اﻟﺮﻣﺰ اﻻﺟﻨﺒﻲ : ')+tp+' || '+Translation('الرمز التسلسلي : ')+BC+'" value="'+response[i][0]+'" data-forgin-code="'+response[i][2]+'" data-item_type_id="'+response[i][3]+'">'+response[i][1]+'</option>';
                        }
                        $("#product_id_fk_"+row_num).html(attach);
                        $('#product_id_fk_'+row_num).selectpicker('refresh');

                        $("#edit_product_id_fk_"+row_num).html(attach);
                        $('#edit_product_id_fk_'+row_num).selectpicker('refresh');
                        
                        product_list_temp = attach;

                        if(edit !=null && edit !=''){
                          $("#edit_product_id_fk_"+row_num).val(edit).selectpicker('refresh');
                        }
                        // $("#edit_stock_id_fk").selectpicker('refresh');
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

          

         

    }

    function load_products1(val, id){
        var row_num1 = id.split('_');
        var row_num = row_num1[2];
        if(val !=""){

          $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get_one_product_sell',p_val:val},
                  dataType : 'json',
                  success : function(response) {
                   
                        if(response.length==0){
                          $("#product_id_fk_"+row_num).val('');
                          $("#forign_id_"+row_num).html('');
                          noty({
                            width: 200,
                            text: Translation("ﻻ ﺗﻮﺟﺪ ﻫﻜﺬا ﻣﺎﺩﺓ اﻟﺮﺟﺎء اﻟﺘﺎﻛﺪ ﻣﻦ اﻟﻜﻮﺩ"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                          });

                        }else{

                          $("#product_id_fk_"+row_num).val(response[0][0]);
                          $("#item_type_id_"+row_num).val(response[0][3]);
                          $("#forign_id_"+row_num).html(response[0][2]);

                          load_prices(row_num);
                          
                        }

                        // to reset the selected product when change product
                        $("#products_"+row_num).html('');
                        $("#total_length_"+row_num).val('');
                  },
                  complete: function() {

                  }

            }); // submit ajax

        }

         
    }


    function load_products(val, id){
        var row_num1 = id.split('_');
        var row_num = row_num1[3];
        
        var forgin_code = $("#product_id_fk_"+row_num+" option:selected").attr('data-forgin-code');
        var item_type_   = $("#product_id_fk_"+row_num+" option:selected").attr('data-item_type_id');

        $("#forign_id_"+row_num).html(forgin_code);
        $("#item_type_id_"+row_num).val(item_type_);

        // we should show modal for input rolls length 
        var qty = $("#purchase_quantity_"+row_num).val();

        load_prices(row_num);

        // to reset the selected product when change product
        $("#products_"+row_num).html('');
        $("#total_length_"+row_num).val('');
        
        add_qty_input_fields(qty,"purchase_quantity_"+row_num);

    }

    function edit_load_products(val, id){
        var row_num1 = id.split('_');
        var row_num = row_num1[4];
        
        var forgin_code = $("#edit_product_id_fk_"+row_num+" option:selected").attr('data-forgin-code');
        var item_type_   = $("#edit_product_id_fk_"+row_num+" option:selected").attr('data-item_type_id');

        $("#edit_forign_id_"+row_num).html(forgin_code);
        $("#edit_item_type_id_"+row_num).val(item_type_);

        // we should show modal for input rolls length 
        var qty = $("#edit_purchase_quantity_"+row_num).val();

        edit_load_prices(row_num);

        // to reset the selected product when change product
        $("#edit_products_"+row_num).html('');
        $("#edit_total_length_"+row_num).val('');
        
        edit_add_qty_input_fields(qty,"edit_purchase_quantity_"+row_num);

    }


    function get_Others(cnt){

        $.ajax({
                  url : 'models/crul_invoice.php',
                  type : 'POST',
                  data : {type:'get_others'},
                  dataType : 'json',
                  success : function(response) {
                    console.log(response)
                      var attach ='<option value="" selected="selected">'+Translation('ﻣﻮاﺩ اﺧﺮﻯ')+'</option>';
                    
                        for(var i=response.length-1 ; i >= 0;i--){
                         
                          attach = attach + '<option data-subtext="  '+response[i][2]+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          
                        }
                        $("#other_id_fk_"+cnt).html(attach);
                        $('#other_id_fk_'+cnt).selectpicker('refresh');

                        other_list_temp = attach;
                        //$("#edit_product_id").html(edit_attach);

                  },
                  complete: function() {

                  }

            }); // submit ajax

        }


    function load_prices(row_num){
      // load price for this product

          var PP_ID = $("#price_profile_id").val();
          var P_ID  = $("#product_id_fk_"+row_num).val();
          


          if(PP_ID=='' || PP_ID ==null){
              noty({
                      width: 200,
                      text: Translation("اﻟﺮﺟﺎء اﺧﺘﻴﺎﺭ ﻣﻠﻒ ﺳﻌﺮ ﻟﺘﺤﻤﻴﻞ اﻻﺳﻌﺎﺭ ﻣﻨﻪ"),
                      type: 'error',
                      dismissQueue: true,
                      timeout: 3000,
                      layout: 'topRight',

                    });
          }

          $.ajax({
                  url : 'models/crul_product_price.php',
                  type : 'POST',
                  data : {type:'get',PP_ID:PP_ID,p_val:P_ID},
                  dataType : 'json',
                  success : function(response) {
                   
                        if(response==0){
                          $("#buy_price_per_meter_"+row_num).val('');
                          // $("#last_sell_price_"+row_num).val('');
                          
                          noty({
                            width: 200,
                            text: Translation("ﻻ ﻳﻮﺟﺪ ﺳﻌﺮ ﺑﻴﻊ ﻟﻬﺬﻩ اﻟﻤﺎﺩﺓ"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                          });

                        }else{
                          $("#buy_price_per_meter_"+row_num).val(response[0][1]);
                          // $("#last_sell_price_"+row_num).val(response[0][2]); 
                          
                        }
                  },
                  complete: function() {
                    load_last_prices(row_num);
                  }

            }); // submit ajax
      // end loading price
    }

    function edit_load_prices(row_num){
      // load price for this product

          var PP_ID = $("#edit_price_profile_id").val();
          var P_ID  = $("#edit_product_id_fk_"+row_num).val();
          


          if(PP_ID=='' || PP_ID ==null){
              noty({
                      width: 200,
                      text: Translation("اﻟﺮﺟﺎء اﺧﺘﻴﺎﺭ ﻣﻠﻒ ﺳﻌﺮ ﻟﺘﺤﻤﻴﻞ اﻻﺳﻌﺎﺭ ﻣﻨﻪ"),
                      type: 'error',
                      dismissQueue: true,
                      timeout: 3000,
                      layout: 'topRight',

                    });
          }

          $.ajax({
                  url : 'models/crul_product_price.php',
                  type : 'POST',
                  data : {type:'get',PP_ID:PP_ID,p_val:P_ID},
                  dataType : 'json',
                  success : function(response) {
                   
                        if(response==0){
                          $("#edit_buy_price_per_meter_"+row_num).val('');
                          // $("#last_sell_price_"+row_num).val('');
                          
                          noty({
                            width: 200,
                            text: Translation("ﻻ ﻳﻮﺟﺪ ﺳﻌﺮ ﺑﻴﻊ ﻟﻬﺬﻩ اﻟﻤﺎﺩﺓ"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                          });

                        }else{
                          $("#edit_buy_price_per_meter_"+row_num).val(response[0][1]);
                          // $("#last_sell_price_"+row_num).val(response[0][2]); 
                          
                        }
                  },
                  complete: function() {
                    edit_load_last_prices(row_num);
                  }

            }); // submit ajax
      // end loading price
    }

    function load_last_prices(row_num){
      // load price for this product

          
          var P_ID  = $("#product_id_fk_"+row_num).val();
          // to load the last sell price for this customer
          var Cus_ID  = $("#customer_id_fk").val();

          if(Cus_ID=='' || Cus_ID ==null){
              noty({
                      width: 200,
                      text: Translation("اﻟﺮﺟﺎء ﻗﻢ ﺑﺘﺤﺪﻳﺪ اﺳﻢ اﻟﺰﺑﻮﻥ ﻟﺘﺤﻤﻴﻞ اﺧﺮ ﺳﻌﺮ ﺑﻴﻊ ﻟﻪ"),
                      type: 'error',
                      dismissQueue: true,
                      timeout: 3000,
                      layout: 'topRight',
                    });
          }


          $.ajax({
                  url : 'models/crul_product_price.php',
                  type : 'POST',
                  data : {type:'get_last_sell_price',p_val:P_ID,Cus_ID:Cus_ID},
                  dataType : 'json',
                  success : function(response) {
                   
                        if(response==0){
                          $("#last_sell_price_"+row_num).val('');
                          
                          noty({
                            width: 200,
                            text: Translation("ﻻ ﻳﻮﺟﺪ اﺧﺮ ﺳﻌﺮ ﺑﻴﻊ ﻟﻬﺬا اﻟﺰﺑﻮﻥ"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                          });

                        }else{
                          $("#last_sell_price_"+row_num).val(response[0][0]); 
                          
                        }
                  },
                  complete: function() {

                  }

            }); // submit ajax
      // end loading price
    }


    function edit_load_last_prices(row_num){
      // load price for this product

          
          var P_ID  = $("#edit_product_id_fk_"+row_num).val();
          // to load the last sell price for this customer
          var Cus_ID  = $("#edit_customer_id_fk").val();

          if(Cus_ID=='' || Cus_ID ==null){
              noty({
                      width: 200,
                      text: Translation("اﻟﺮﺟﺎء ﻗﻢ ﺑﺘﺤﺪﻳﺪ اﺳﻢ اﻟﺰﺑﻮﻥ ﻟﺘﺤﻤﻴﻞ اﺧﺮ ﺳﻌﺮ ﺑﻴﻊ ﻟﻪ"),
                      type: 'error',
                      dismissQueue: true,
                      timeout: 3000,
                      layout: 'topRight',
                    });
          }


          $.ajax({
                  url : 'models/crul_product_price.php',
                  type : 'POST',
                  data : {type:'get_last_sell_price',p_val:P_ID,Cus_ID:Cus_ID},
                  dataType : 'json',
                  success : function(response) {
                   
                        if(response==0){
                          $("#edit_last_sell_price_"+row_num).val('');
                          
                          noty({
                            width: 200,
                            text: Translation("ﻻ ﻳﻮﺟﺪ اﺧﺮ ﺳﻌﺮ ﺑﻴﻊ ﻟﻬﺬا اﻟﺰﺑﻮﻥ"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                          });

                        }else{
                          $("#edit_last_sell_price_"+row_num).val(response[0][0]); 
                          
                        }
                  },
                  complete: function() {

                  }

            }); // submit ajax
      // end loading price
    }

    

    // this function just to show how many he select roll in the top of modal
    function total_sel_length(){

      var total=$('input[id^="checked_roll_"]:checked').length;
      $("#total_selected").html(total);

      var sum = 0;        
      $('input[id^="part_roll_length_"]').each(function() 
      { 
        if(!isNaN(this.value) && this.value.length!=0) 
        {
          sum += parseFloat(this.value);            
        }         
      });

      $("#total_sel_roll_length").html(sum);
    }

    function edit_total_sel_length(){

      var total=$('input[id^="edit_checked_roll_"]:checked').length;
      $("#edit_total_selected").html(total);

      var sum = 0;        
      $('input[id^="edit_part_roll_length_"]').each(function() 
      { 
        if(!isNaN(this.value) && this.value.length!=0) 
        {
          sum += parseFloat(this.value);            
        }         
      });

      $("#edit_total_sel_roll_length").html(sum);
    }

    function part_sell(cnt){
      

      var chk = $("#checked_roll_"+cnt).is(':checked');

      if(chk){
        var roll_length = $("#checked_roll_"+cnt).attr('data-remained-length');
        $("#part_roll_length_"+cnt).val(roll_length);
      }else{
        $("#part_roll_length_"+cnt).val('');
      }
      total_sel_length();
      
    }

    function edit_part_sell(cnt){
      

      var chk = $("#edit_checked_roll_"+cnt).is(':checked');

      if(chk){
        var roll_length = $("#edit_checked_roll_"+cnt).attr('data-remained-length');
        $("#edit_part_roll_length_"+cnt).val(roll_length);
      }else{
        $("#edit_part_roll_length_"+cnt).val('');
      }
      edit_total_sel_length();
      
    }

    function part_sell2(cnt){
      

      // if he enter value in textbox we should check automatically the checkbox
      var roll_val = $("#part_roll_length_"+cnt).val();
      var roll_length = $("#checked_roll_"+cnt).attr('data-remained-length');
      if(roll_val !=''){
        // check val not 0 or greater than roll length?
        
        if(parseFloat(roll_val) > parseFloat(roll_length) || parseFloat(roll_val) <= 0 || isNaN(parseFloat(roll_val)) ){
          $("#part_roll_length_"+cnt).val(roll_length);
        }
        $("#checked_roll_"+cnt).prop('checked', true);
      }else{
        $("#checked_roll_"+cnt).prop('checked', false);
      }
      total_sel_length();
    }


    function edit_part_sell2(cnt){
      

      // if he enter value in textbox we should check automatically the checkbox
      var roll_val    = $("#edit_part_roll_length_"+cnt).val();
      var roll_length = $("#edit_checked_roll_"+cnt).attr('data-remained-length');
      if(roll_val !=''){
        // check val not 0 or greater than roll length?
        
        if(parseFloat(roll_val) > parseFloat(roll_length) || parseFloat(roll_val) <= 0 || isNaN(parseFloat(roll_val)) ){
          $("#edit_part_roll_length_"+cnt).val(roll_length);
        }
        $("#edit_checked_roll_"+cnt).prop('checked', true);
      }else{
        $("#edit_checked_roll_"+cnt).prop('checked', false);
      }
      edit_total_sel_length();
    }

    function add_qty_input_fields(qty,id){
      console.log(qty);
       // alert(qty);
      var row_num1 = id.split('_');
      var row_num  = row_num1[2];

      

      if(qty >0 && qty !=""){

          // we should check if this product have purchase or not

          var p_id = $("#product_id_fk_"+row_num).val();

          if(p_id == null || p_id == '' || p_id == undefined || p_id < 1){

            noty({
                    width: 200,
                    text: Translation('اﻟﺮﺟﺎء ﻗﻢ ﺑﺎﺧﺘﻴﺎﺭ اﻟﻤﺎﺩﺓ اﻭﻻ'),
                    type: 'information',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
                });

          }else{

            

            $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'check_item_type',p_id:p_id},
                  dataType : 'json',
                  success : function(response) {
                   
                     if(response[0][4]==0){ // have purchase
                        // we should show modal to select the products
                        $("#fields_count_purchase").val(qty);
                        $("#rows_count_purchase").val(row_num);
                        

                        $.ajax({
                                url : 'models/crul_invoice.php',
                                type : 'POST',
                                data : {type:'get_purchase_product',p_id:p_id},
                                dataType : 'json',
                                success : function(res) {
                                  $("#rolls_count_purchase").val(res.data.length);
                                  // get number of store stock for sorting & Grouping
                                  
                                  var attach_input =`<style> .tab-content{display: -webkit-box;} .nav-tabs.nav-justified > li > a {display: block; }
                                                    .nav.nav-lg > li > a {height: 60px;} </style>`;
                                  for (var j = 0; j < res.stocks.length; j++) {
                                    
                                    var panel_header ='white';                    

                                    if(res.stocks[j][2]==1){
                                      panel_header ='success';
                                    }
                                   attach_input = attach_input + `
                                                                  <!-- Heading badge -->
                                                                  <div class="panel panel-`+panel_header+`">
                                                                    <div class="panel-heading">
                                                                      <h6 class="panel-title">`+res.stocks[j][1]+`</h6>
                                                                      <div class="heading-elements">
                                                                        <span class="badge bg-indigo-400 heading-text">`+res.stocks[j][3]+`</span>
                                                                      </div>
                                                                    </div>
                                                                    
                                                                    <div class="panel-body">
                                                                        <!-- Tabs widget -->
                                                                        <div class="tab-content-bordered content-group">
                                                                          <ul class="nav nav-tabs nav-tabs-highlight nav-lg nav-justified">
                                                                            <li class="active"><a href="#complete_roll`+j+`" data-toggle="tab">ﻣﻮاﺩ ﻛﺎﻣﻠﺔ</a></li>
                                                                            <li><a href="#just_damage`+j+`" data-toggle="tab">`+Translation('ﻣﻮاﺩ ﺟﺰء ﻣﻨﻬﺎ ﺗﺎﻟﻒ')+`</a></li>
                                                                            <li><a href="#partiall_sold`+j+`" data-toggle="tab">`+Translation('ﻣﻮاﺩ ﺑﻴﻌﺖ ﺑﺎﻟﺘﺠﺰﺋﺔ')+`</a></li>
                                                                            <li><a href="#partiall_sold_used`+j+`" data-toggle="tab">`+Translation('ﻣﻮاﺩ ﺑﻴﻌﺖ ﺑﺎﻟﺘﺠﺰﺋﺔ ﻭاﺳﺘﺨﺪﻣﺖ ﺑﺎﻻﻧﺘﺎﺝ')+`</a></li>
                                                                            <li><a href="#used_in_production`+j+`" data-toggle="tab">`+Translation('ﻣﻮاﺩ اﺳﺘﺨﺪﻣﺖ ﻓﻘﻂ ﻓﻲ اﻻﻧﺘﺎﺝ')+`</a></li>
                                                                          </ul>

                                                                          <div class="tab-content">
                                                                  `;
                                    var tab_complete_roll       =`<div class="tab-pane has-padding active" id="complete_roll`+j+`">`;
                                    var tab_just_damage         =`<div class="tab-pane has-padding " id="just_damage`+j+`">`;
                                    var tab_partiall_sold       =`<div class="tab-pane has-padding " id="partiall_sold`+j+`">`;
                                    var tab_partiall_sold_used  =`<div class="tab-pane has-padding " id="partiall_sold_used`+j+`">`;
                                    var tab_used_in_production  =`<div class="tab-pane has-padding " id="used_in_production`+j+`">`;
                                    
                                    for (var i = 0; i < res.data.length; i++) {
                                      var item_input = '';
                                      if(res.stocks[j][0] == res.data[i][3]){
                                        // now we should check item_status and group it according to item status
                                        item_input =  `
                                                        <div class="form-group col-sm-3 jQsearch" data-search="`+res.data[i][5]+`" style="">
                                                            <div class="input-group">
                                                              <span class="input-group-addon">
                                                                <input type="checkbox" class="styled" data-item-status="`+res.data[i][4]+`" data-remained-length="`+res.data[i][5]+`" data-roll-length="`+res.data[i][1]+`" data-roll-id-fk="`+res.data[i][0]+`" id="checked_roll_`+i+`" name="checked_roll_`+i+`" onclick="part_sell(`+i+`);"  >
                                                              </span>
                                                              <span class="input-group-addon">`+res.data[i][5]+` </span> <!-- remainded length -->
                                                              <input type="text" id="part_roll_length_`+i+`" name="part_roll_length_`+i+`" class="form-control" placeholder="`+Translation('ﺑﻴﻊ ﺑﺎﻟﺘﺠﺰﺋﺔ')+`" onchange="part_sell2(`+i+`);">
                                                              
                                                            </div>
                                                        </div>

                                                        `;

                                        switch (res.data[i][4])
                                        {
                                          case "0":
                                          case "2":
                                                tab_complete_roll = tab_complete_roll + item_input;
                                                break;
                                          case "8":
                                          case "11":
                                                tab_just_damage = tab_just_damage + item_input;
                                                break;
                                          case "5":
                                                tab_partiall_sold = tab_partiall_sold + item_input;
                                                break;
                                          case "9":
                                                tab_partiall_sold_used = tab_partiall_sold_used + item_input;
                                                break;
                                          case "3":
                                                tab_used_in_production = tab_used_in_production + item_input;
                                                break;
                                        }
                                        
                                      } // if stock
                                      
                                    } // for i
                                    
                                    tab_complete_roll       = tab_complete_roll + `</div>`;
                                    tab_just_damage         = tab_just_damage + `</div>`;
                                    tab_partiall_sold       = tab_partiall_sold + `</div>`;
                                    tab_partiall_sold_used  = tab_partiall_sold_used + `</div>`;
                                    tab_used_in_production  = tab_used_in_production + `</div>`;
                                    
                                    attach_input = attach_input + tab_complete_roll + tab_just_damage + tab_partiall_sold + tab_partiall_sold_used + tab_used_in_production;

                                   attach_input = attach_input + `    
                                                                        </div>
                                                                      </div>
                                                                      <!-- /tabs widget -->
                                                                    </div>
                                                                  </div>
                                                                  <!-- /heading badge -->
                                                                  `;
                                  } // for j

                                  

                                  $("#input_box_array_purchase").html(attach_input);
                                }
                              });

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


                     }else{ // havn't purchase

                        // Modal for input rolls lengths
                        $("#fields_count").val(qty);
                        $("#rows_count").val(row_num);
                        var attach_input ="";
                        for (var i = 1; i <= qty; i++) {
                          attach_input = attach_input + `
                                                          <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2">
                                                            <label class="control-label">`+Translation('اﻟﻄﻮﻝ')+`</label>
                                                            <input type="text" id="roll_length_`+i+`" name="roll_length_`+i+`" class="form-control" placeholder="`+Translation('اﻟﻄﻮﻝ')+`" required="required">
                                                            <div class="form-control-feedback">
                                                              <i class="icon-pencil-ruler text-muted"></i>
                                                            </div>
                                                          </div>`;
                        }

                        $("#input_box_array").html(attach_input);
                        $('#add_new_product').modal('toggle');

                     }
                       
                  },
                  complete: function() {
                    
                  }

            }); // submit ajax

            // end checking for purchasing or not

          } // if p_id

            

      }
      

    }

    function edit_add_qty_input_fields(qty,id){
      console.log(qty);
       // alert(qty);
      var row_num1 = id.split('_');
      var row_num  = row_num1[3];

      var resTmp   = '';
      

      if(qty >0 && qty !=""){

        // we should check if this product have purchase or not

        var p_id    = $("#edit_product_id_fk_"+row_num).val();
        var sell_id = $("#edit_item_row_"+row_num).attr('data-sell-item-id');

        if(sell_id == undefined || sell_id == ''){
          sell_id = '0'
        }
        

        if(p_id == null || p_id == '' || p_id == undefined || p_id < 1){

          noty({
              width: 200,
              text: Translation('اﻟﺮﺟﺎء ﻗﻢ ﺑﺎﺧﺘﻴﺎﺭ اﻟﻤﺎﺩﺓ اﻭﻻ'),
              type: 'information',
              dismissQueue: true,
              timeout: 3000,
              layout: 'topRight',
          });

        }else{

          

          $.ajax({
            url : 'models/crul_product.php',
            type : 'POST',
            data : {type:'check_item_type',p_id:p_id},
            dataType : 'json',
            success : function(response) {
             
            if(response[0][4]==0){ // have purchase
              // we should show modal to select the products
              $("#edit_fields_count_purchase").val(qty);
              $("#edit_rows_count_purchase").val(row_num);
              

              $.ajax({
                url : 'models/crul_invoice.php',
                type : 'POST',
                data : {type:'get_purchase_product_edit',p_id:p_id, sell_id:sell_id},
                dataType : 'json',
                success : function(res) {

                  console.log(res);

                  resTmp = res;
                  $("#edit_rolls_count_purchase").val(res.data.length);
                  // get number of store stock for sorting & Grouping
                  
                  var attach_input =`<style> .tab-content{display: -webkit-box;} .nav-tabs.nav-justified > li > a {display: block; }
                                    .nav.nav-lg > li > a {height: 60px;} </style>`;
                  for (var j = 0; j < res.stocks.length; j++) {
                    
                    var panel_header ='white';                    

                    if(res.stocks[j][2]==1){
                      panel_header ='success';
                    }
                    attach_input = attach_input + `
                                                  <!-- Heading badge -->
                                                  <div class="panel panel-`+panel_header+`">
                                                    <div class="panel-heading">
                                                      <h6 class="panel-title">`+res.stocks[j][1]+`</h6>
                                                      <div class="heading-elements">
                                                        <span class="badge bg-indigo-400 heading-text">`+res.stocks[j][3]+`</span>
                                                      </div>
                                                    </div>
                                                    
                                                    <div class="panel-body">
                                                        <!-- Tabs widget -->
                                                        <div class="tab-content-bordered content-group">
                                                          <ul class="nav nav-tabs nav-tabs-highlight nav-lg nav-justified">
                                                            <li class="active"><a href="#edit_complete_roll`+j+`" data-toggle="tab">ﻣﻮاﺩ ﻛﺎﻣﻠﺔ</a></li>
                                                            <li><a href="#edit_just_damage`+j+`" data-toggle="tab">`+Translation('ﻣﻮاﺩ ﺟﺰء ﻣﻨﻬﺎ ﺗﺎﻟﻒ')+`</a></li>
                                                            <li><a href="#edit_partiall_sold`+j+`" data-toggle="tab">`+Translation('ﻣﻮاﺩ ﺑﻴﻌﺖ ﺑﺎﻟﺘﺠﺰﺋﺔ')+`</a></li>
                                                            <li><a href="#edit_partiall_sold_used`+j+`" data-toggle="tab">`+Translation('ﻣﻮاﺩ ﺑﻴﻌﺖ ﺑﺎﻟﺘﺠﺰﺋﺔ ﻭاﺳﺘﺨﺪﻣﺖ ﺑﺎﻻﻧﺘﺎﺝ')+`</a></li>
                                                            <li><a href="#edit_used_in_production`+j+`" data-toggle="tab">`+Translation('ﻣﻮاﺩ اﺳﺘﺨﺪﻣﺖ ﻓﻘﻂ ﻓﻲ اﻻﻧﺘﺎﺝ')+`</a></li>
                                                          </ul>

                                                          <div class="tab-content">
                                                  `;
                    var tab_complete_roll       =`<div class="tab-pane has-padding active" id="edit_complete_roll`+j+`">`;
                    var tab_just_damage         =`<div class="tab-pane has-padding " id="edit_just_damage`+j+`">`;
                    var tab_partiall_sold       =`<div class="tab-pane has-padding " id="edit_partiall_sold`+j+`">`;
                    var tab_partiall_sold_used  =`<div class="tab-pane has-padding " id="edit_partiall_sold_used`+j+`">`;
                    var tab_used_in_production  =`<div class="tab-pane has-padding " id="edit_used_in_production`+j+`">`;
                    
                    for (var i = 0; i < res.data.length; i++) {
                      var item_input = '';
                      if(res.stocks[j][0] == res.data[i][3]){
                        // now we should check item_status and group it according to item status
                        

                        // if(res.data[i][4] == '1'){ // completly sold
                        if(res.data[i][6] > 0){ // completly sold

                          item_input =  `
                                        <div class="form-group col-sm-3 alpha-info">
                                            <div class="input-group">
                                              <span class="input-group-addon">
                                                <input type="checkbox" class="styled" checked='checked' data-item-status="`+res.data[i][4]+`" data-remained-length="`+res.data[i][7]+`" data-roll-length="`+res.data[i][1]+`" data-roll-id-fk="`+res.data[i][0]+`" id="edit_checked_roll_`+i+`" name="edit_checked_roll_`+i+`" onclick="edit_part_sell(`+i+`);"  >
                                              </span>
                                              <span class="input-group-addon">`+res.data[i][7]+` </span> <!-- remainded length -->
                                              <input type="text" id="edit_part_roll_length_`+i+`" name="edit_part_roll_length_`+i+`" value="`+res.data[i][7]+`" class="form-control" placeholder="`+Translation('ﺑﻴﻊ ﺑﺎﻟﺘﺠﺰﺋﺔ')+`" onchange="edit_part_sell2(`+i+`);">
                                              
                                            </div>
                                        </div>

                                        `;

                        }else{

                        
                          item_input =  `
                                        <div class="form-group col-sm-3">
                                            <div class="input-group">
                                              <span class="input-group-addon">
                                                <input type="checkbox" class="styled" data-item-status="`+res.data[i][4]+`" data-remained-length="`+res.data[i][5]+`" data-roll-length="`+res.data[i][1]+`" data-roll-id-fk="`+res.data[i][0]+`" id="edit_checked_roll_`+i+`" name="edit_checked_roll_`+i+`" onclick="edit_part_sell(`+i+`);"  >
                                              </span>
                                              <span class="input-group-addon">`+res.data[i][5]+` </span> <!-- remainded length -->
                                              <input type="text" id="edit_part_roll_length_`+i+`" name="edit_part_roll_length_`+i+`" class="form-control" placeholder="`+Translation('ﺑﻴﻊ ﺑﺎﻟﺘﺠﺰﺋﺔ')+`" onchange="edit_part_sell2(`+i+`);">
                                              
                                            </div>
                                        </div>

                                        `;
                        }


                        switch (res.data[i][4])
                        {
                          case "0":
                          case "1":
                          case "2":
                                tab_complete_roll = tab_complete_roll + item_input;
                                break;
                          case "8":
                          case "11":
                                tab_just_damage = tab_just_damage + item_input;
                                break;
                          case "5":
                                tab_partiall_sold = tab_partiall_sold + item_input;
                                break;
                          case "9":
                                tab_partiall_sold_used = tab_partiall_sold_used + item_input;
                                break;
                          case "3":
                                tab_used_in_production = tab_used_in_production + item_input;
                                break;
                        }
                        
                      } // if stock
                      
                    } // for i
                    
                    tab_complete_roll       = tab_complete_roll + `</div>`;
                    tab_just_damage         = tab_just_damage + `</div>`;
                    tab_partiall_sold       = tab_partiall_sold + `</div>`;
                    tab_partiall_sold_used  = tab_partiall_sold_used + `</div>`;
                    tab_used_in_production  = tab_used_in_production + `</div>`;
                    
                    attach_input = attach_input + tab_complete_roll + tab_just_damage + tab_partiall_sold + tab_partiall_sold_used + tab_used_in_production;

                   attach_input = attach_input + `    
                                                        </div>
                                                      </div>
                                                      <!-- /tabs widget -->
                                                    </div>
                                                  </div>
                                                  <!-- /heading badge -->
                                                  `;
                  } // for j

                  

                  $("#edit_input_box_array_purchase").html(attach_input);
                },
                complete: function() {

                  console.log(resTmp);
                  

                  for (var i = 0; i < resTmp.data.length; i++) {                
                    if(resTmp.data[i][4] == '1'){ 
                      edit_part_sell(i);
                    }
                  }
                  
                }
              });

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




            }else{ // havn't purchase

                // Modal for input rolls lengths
                $("#edit_fields_count").val(qty);
                $("#edit_rows_count").val(row_num);
                var attach_input ="";
                for (var i = 1; i <= qty; i++) {
                  attach_input = attach_input + `
                                                  <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2">
                                                    <label class="control-label">`+Translation('اﻟﻄﻮﻝ')+`</label>
                                                    <input type="text" id="edit_roll_length_`+i+`" name="edit_roll_length_`+i+`" class="form-control" placeholder="`+Translation('اﻟﻄﻮﻝ')+`" required="required">
                                                    <div class="form-control-feedback">
                                                      <i class="icon-pencil-ruler text-muted"></i>
                                                    </div>
                                                  </div>`;
                }

                $("#edit_input_box_array").html(attach_input);
                $('#edit_add_new_product').modal('toggle');

            }
                 
            },
            complete: function() {


            }

          }); // submit ajax

          // end checking for purchasing or not

        } // if p_id

            

      }
      

    }


    function calc_total_length(row_no,qty){
          var total_roll_length =0;
          for (var i = 1; i <= qty; i++) {
            total_roll_length = +total_roll_length + +$("#row_"+row_no+"_roll_"+i).val();
          }
          $("#total_length_"+row_no).val(total_roll_length);
          var total_item_cost = total_roll_length * $("#buy_price_per_meter_"+row_no).val();
          $("#total_item_cost_"+row_no).val(currency_format_display(total_item_cost));
          calc_total_purchase_price();
    }


    function edit_calc_total_length(row_no,qty){
          var total_roll_length =0;
          for (var i = 1; i <= qty; i++) {
            total_roll_length = +total_roll_length + +$("#edit_row_"+row_no+"_roll_"+i).val();
          }
          $("#edit_total_length_"+row_no).val(total_roll_length);
          var total_item_cost = total_roll_length * $("#edit_buy_price_per_meter_"+row_no).val();
          $("#edit_total_item_cost_"+row_no).val(currency_format_display(total_item_cost));
          edit_calc_total_purchase_price();
    }


    function calc_total_item_cost(id,row_no){
          var row_num1 = id.split('_');
          var row_num = row_no ; // row_num1[4];
          var actual_disc = 0;
          
          var total_item_cost = $("#total_length_"+row_num).val() * $("#buy_price_per_meter_"+row_num).val();
          
          // discount and checking for % or absolute val
          var discount = $("#sell_discount_"+row_no).val();
          if (discount.indexOf('%') > -1)
          {
            $("#sell_discount_"+row_no).attr('data-discount-type','0'); // percentage
            var diss = parseFloat(discount.replace('%',''));
            if(!isNaN(diss)){
              actual_disc     = (total_item_cost * diss / 100);
              total_item_cost = total_item_cost - actual_disc;
              

            }
            
          }else if(discount !='' && !isNaN(discount)){
            $("#sell_discount_"+row_no).attr('data-discount-type','1'); // absolute
            total_item_cost = total_item_cost - discount;
            actual_disc = discount;

          }

          $("#sell_discount_"+row_no).attr('data-discount-actual',actual_disc); // absolute discount

          $("#total_item_cost_"+row_num).val(currency_format_display(total_item_cost));  
          
          calc_total_purchase_price();
    }


    

    function edit_calc_total_item_cost(id,row_no){
          var row_num1 = id.split('_');
          var row_num = row_no ; // row_num1[4];
          var actual_disc = 0;
          
          var total_item_cost = $("#edit_total_length_"+row_num).val() * $("#edit_buy_price_per_meter_"+row_num).val();
          
          // discount and checking for % or absolute val
          var discount = $("#edit_sell_discount_"+row_no).val();
          if (discount.indexOf('%') > -1)
          {
            $("#edit_sell_discount_"+row_no).attr('data-discount-type','0'); // percentage
            var diss = parseFloat(discount.replace('%',''));
            if(!isNaN(diss)){
              actual_disc     = (total_item_cost * diss / 100);
              total_item_cost = total_item_cost - actual_disc;
              

            }
            
          }else if(discount !='' && !isNaN(discount)){
            $("#edit_sell_discount_"+row_no).attr('data-discount-type','1'); // absolute
            total_item_cost = total_item_cost - discount;
            actual_disc = discount;

          }

          $("#edit_sell_discount_"+row_no).attr('data-discount-actual',actual_disc); // absolute discount

          $("#edit_total_item_cost_"+row_num).val(currency_format_display(total_item_cost));  
          
          edit_calc_total_purchase_price();
    }

    function calc_other_cost(row_num){

          var total_item_cost = $("#other_quantity_"+row_num).val() * $("#buy_price_per_meter_other_"+row_num).val();
          var actual_disc = 0;
          // discount and checking for % or absolute val
          var discount = $("#sell_discount_other_"+row_num).val();
          if (discount.indexOf('%') > -1)
          {
            $("#sell_discount_other_"+row_num).attr('data-discount-type','0'); // percentage
            var diss = parseFloat(discount.replace('%',''));
            if(!isNaN(diss)){
              actual_disc     = (total_item_cost * diss / 100);

              total_item_cost = total_item_cost - actual_disc;

            }
            
          }else if(discount !='' && !isNaN(discount)){
            $("#sell_discount_other_"+row_num).attr('data-discount-type','1'); // absolute
            total_item_cost = total_item_cost - discount;
            actual_disc = discount;
          }

          $("#sell_discount_other_"+row_num).attr('data-discount-actual',actual_disc); // absolute discount

          $("#total_item_cost_other_"+row_num).val(currency_format_display(total_item_cost));  
          

          calc_total_purchase_price();

    }


    function edit_calc_other_cost(row_num){

          var total_item_cost = $("#edit_other_quantity_"+row_num).val() * $("#edit_buy_price_per_meter_other_"+row_num).val();
          var actual_disc = 0;
          // discount and checking for % or absolute val
          var discount = $("#edit_sell_discount_other_"+row_num).val();
          if (discount.indexOf('%') > -1)
          {
            $("#edit_sell_discount_other_"+row_num).attr('data-discount-type','0'); // percentage
            var diss = parseFloat(discount.replace('%',''));
            if(!isNaN(diss)){
              actual_disc     = (total_item_cost * diss / 100);

              total_item_cost = total_item_cost - actual_disc;

            }
            
          }else if(discount !='' && !isNaN(discount)){
            $("#edit_sell_discount_other_"+row_num).attr('data-discount-type','1'); // absolute
            total_item_cost = total_item_cost - discount;
            actual_disc = discount;
          }

          $("#edit_sell_discount_other_"+row_num).attr('data-discount-actual',actual_disc); // absolute discount

          $("#edit_total_item_cost_other_"+row_num).val(currency_format_display(total_item_cost));  
          

          edit_calc_total_purchase_price();

    }

    function calc_payments_5_5_2018(row_num=null,other_cnt=null) {

          // check if current payment greater than row total price
          if(row_num !=null){

            if(row_num == 'other'){
              var cur_pay   = $("#other_pay_"+other_cnt).val();
              var prod_cost = $("#total_item_cost_other_"+other_cnt).val();

            }else{
              var cur_pay   = $("#product_pay_"+row_num).val();
              var prod_cost = $("#total_item_cost_"+row_num).val();

            }

            if (prod_cost.indexOf('$') > -1)
            {
              
               prod_cost = prod_cost.replace('$','');
              
            }

            if (prod_cost.indexOf(',') > -1)
            {
              
               prod_cost = prod_cost.replace(/,/g,'');
              
            }

            prod_cost = parseFloat(prod_cost);

            if(cur_pay > prod_cost){
              noty({
                        width: 200,
                        text: Translation("ﻗﻴﻤﺔ اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮﻉ اﻛﺒﺮ ﻣﻦ اﻟﻤﺠﻤﻮﻉ اﻟﻜﻠﻲ ﻟﻬﺬﻩ اﻟﻤﺎﺩﺓ .. اﻟﺮﺟﺎء اﺩﺧﺎﻝ اﻟﻘﻴﻤﺔ اﻟﺼﺤﻴﺤﺔ"),
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'topRight',
                      });
              
              if(row_num == 'other'){
                $("#other_pay_"+other_cnt).val('');
              }else{
                $("#product_pay_"+row_num).val('');
              }
            }


          }
          

         // footer of table purchase_total
          var purchase_total =0;
          var curnt_row_num = $("#total_rows").val();
          for (var i = 1; i <= curnt_row_num; i++) {

            // check if items exisit and not delted
            if($("#product_pay_"+i).length > 0){
              var td_cost = $("#product_pay_"+i).val();
            
              
              if(isNaN(td_cost) || td_cost == ""){
                td_cost =0;
              }
              purchase_total = +purchase_total + +parseFloat(td_cost).toFixed(2);
            }
            
          }

          var curnt_row_num_other = $("#total_rows_other").val();
          for (var i = 1; i <= curnt_row_num_other; i++) {

            // check if items exisit and not delted
            if($("#other_pay_"+i).length > 0){
              var td_cost = $("#other_pay_"+i).val();
            
              
              if(isNaN(td_cost) || td_cost == ""){
                td_cost =0;
              }
              purchase_total = +purchase_total + +parseFloat(td_cost).toFixed(2);
            }
            
          }
          
          
          
          // purchase_total = +purchase_total + +other_price;
          $("#total_paid").val(currency_format_display(purchase_total));

    }

    function calc_payments(row_num=null,other_cnt=null) {

       

          
              
            var prod_cost = $("#purchase_total").val();
            var cur_pay   = $("#total_paid").val();


            if (prod_cost.indexOf('$') > -1)
            {
              
               prod_cost = prod_cost.replace('$','');
              
            }

            if (prod_cost.indexOf(',') > -1)
            {
              
               prod_cost = prod_cost.replace(/,/g,'');
              
            }

            prod_cost = parseFloat(prod_cost);

            if(cur_pay > prod_cost){
              noty({
                        width: 200,
                        text: Translation("ﻗﻴﻤﺔ اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮﻉ اﻛﺒﺮ ﻣﻦ اﻟﻤﺠﻤﻮﻉ اﻟﻜﻠﻲ ﻟﻠﻮﺻﻞ .. اﻟﺮﺟﺎء اﺩﺧﺎﻝ اﻟﻘﻴﻤﺔ اﻟﺼﺤﻴﺤﺔ"),
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'topRight',
                      });
              
             
                $("#total_paid").val('');
              
            }


          
          


    }


    function edit_calc_payments_5_5_2018(row_num=null,other_cnt=null) {

          // check if current payment greater than row total price
          if(row_num !=null){

            if(row_num == 'other'){
              var cur_pay   = $("#edit_other_pay_"+other_cnt).val();
              var prod_cost = $("#edit_total_item_cost_other_"+other_cnt).val();

            }else{
              var cur_pay   = $("#edit_product_pay_"+row_num).val();
              var prod_cost = $("#edit_total_item_cost_"+row_num).val();

            }

            if (prod_cost.indexOf('$') > -1)
            {
              
               prod_cost = prod_cost.replace('$','');
              
            }

            if (prod_cost.indexOf(',') > -1)
            {
              
               prod_cost = prod_cost.replace(/,/g,'');
              
            }

            prod_cost = parseFloat(prod_cost);

            if(cur_pay > prod_cost){
              noty({
                        width: 200,
                        text: Translation("ﻗﻴﻤﺔ اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮﻉ اﻛﺒﺮ ﻣﻦ اﻟﻤﺠﻤﻮﻉ اﻟﻜﻠﻲ ﻟﻬﺬﻩ اﻟﻤﺎﺩﺓ .. اﻟﺮﺟﺎء اﺩﺧﺎﻝ اﻟﻘﻴﻤﺔ اﻟﺼﺤﻴﺤﺔ"),
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'topRight',
                      });
              
              if(row_num == 'other'){
                $("#edit_other_pay_"+other_cnt).val('');
              }else{
                $("#edit_product_pay_"+row_num).val('');
              }
            }


          }
          

         // footer of table purchase_total
          var purchase_total =0;
          var curnt_row_num = $("#edit_total_rows").val();
          for (var i = 0; i < curnt_row_num; i++) {

            // check if items exisit and not delted
            if($("#edit_product_pay_"+i).length > 0){
              var td_cost = $("#edit_product_pay_"+i).val();
            
              
              if(isNaN(td_cost) || td_cost == ""){
                td_cost =0;
              }
              purchase_total = +purchase_total + +parseFloat(td_cost).toFixed(2);
            }
            
          }

          var curnt_row_num_other = $("#edit_total_rows_other").val();
          for (var i = 0; i < curnt_row_num_other; i++) {

            // check if items exisit and not delted
            if($("#edit_other_pay_"+i).length > 0){
              var td_cost = $("#edit_other_pay_"+i).val();
            
              
              if(isNaN(td_cost) || td_cost == ""){
                td_cost =0;
              }
              purchase_total = +purchase_total + +parseFloat(td_cost).toFixed(2);
            }
            
          }
          
          
          
          // purchase_total = +purchase_total + +other_price;
          $("#edit_total_paid").val(currency_format_display(purchase_total));

    }


    function edit_calc_payments(row_num=null,other_cnt=null) {

         var prod_cost    = $("#edit_purchase_total").val();
            var cur_pay   = $("#edit_total_paid").val();


            if (prod_cost.indexOf('$') > -1)
            {
              
               prod_cost = prod_cost.replace('$','');
              
            }

            if (prod_cost.indexOf(',') > -1)
            {
              
               prod_cost = prod_cost.replace(/,/g,'');
              
            }

            prod_cost = parseFloat(prod_cost);

            if(cur_pay > prod_cost){
              noty({
                        width: 200,
                        text: Translation("ﻗﻴﻤﺔ اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮﻉ اﻛﺒﺮ ﻣﻦ اﻟﻤﺠﻤﻮﻉ اﻟﻜﻠﻲ ﻟﻠﻮﺻﻞ .. اﻟﺮﺟﺎء اﺩﺧﺎﻝ اﻟﻘﻴﻤﺔ اﻟﺼﺤﻴﺤﺔ"),
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'topRight',
                      });
              
             
                $("#edit_total_paid").val('');
              
            }
          


    }


    


    function calc_total_purchase_price(){
          // footer of table purchase_total
          var purchase_total =0;
          var curnt_row_num = $("#total_rows").val();
          for (var i = 1; i <= curnt_row_num; i++) {

            // check if items exisit and not delted
            if($("#total_item_cost_"+i).length > 0){
              var td_cost = $("#total_item_cost_"+i).val();
            
              cost = td_cost.split(" ");
              rep_cost =cost[0].replace(/,/g,'');
              console.log(rep_cost +" rep_cost");
              if(isNaN(rep_cost) || rep_cost ==""){
                rep_cost =0;
              }
              purchase_total = +purchase_total + +parseFloat(rep_cost).toFixed(2);
            }
            
          }
          // console.log(purchase_total +" TT");
          // calculate other

          var curnt_row_num_other = $("#total_rows_other").val();
          for (var i = 1; i <= curnt_row_num_other; i++) {

            // check if items exisit and not delted
            if($("#total_item_cost_other_"+i).length > 0){
              var td_cost = $("#total_item_cost_other_"+i).val();
            
              cost = td_cost.split(" ");
              rep_cost =cost[0].replace(/,/g,'');
              // console.log(rep_cost +" rep_cost");
              if(isNaN(rep_cost) || rep_cost ==""){
                rep_cost =0;
              }
              purchase_total = +purchase_total + +parseFloat(rep_cost).toFixed(2);
            }
            
          }

          // var other_price = $("#total_item_cost_other_1").val();
          // other_price = other_price.replace('$','');
          
          // var other_val = parseFloat(other_price.replace(/,/g,''));
          // purchase_total = +purchase_total + +other_val;
          $("#purchase_total").val(currency_format_display(purchase_total));


    }

    function edit_calc_total_purchase_price(){
          // footer of table purchase_total
          var purchase_total =0;
          var curnt_row_num = $("#edit_total_rows").val();
          for (var i = 0; i <= curnt_row_num; i++) {

            // check if items exisit and not delted
            if($("#edit_total_item_cost_"+i).length > 0){
              var td_cost = $("#edit_total_item_cost_"+i).val();
            
              cost = td_cost.split(" ");
              rep_cost =cost[0].replace(/,/g,'');
              // console.log(rep_cost +" rep_cost");
              if(isNaN(rep_cost) || rep_cost ==""){
                rep_cost =0;
              }
              purchase_total = +purchase_total + +parseFloat(rep_cost).toFixed(2);
            }
            
          }
          // console.log(purchase_total +" TT");
          // calculate other

          var curnt_row_num_other = $("#edit_total_rows_other").val();
          for (var i = 0; i < curnt_row_num_other; i++) {

            // check if items exisit and not delted
            if($("#edit_total_item_cost_other_"+i).length > 0){
              var td_cost = $("#edit_total_item_cost_other_"+i).val();
            
              cost = td_cost.split(" ");
              rep_cost =cost[0].replace(/,/g,'');
              // console.log(rep_cost +" rep_cost");
              if(isNaN(rep_cost) || rep_cost ==""){
                rep_cost =0;
              }
              purchase_total = +purchase_total + +parseFloat(rep_cost).toFixed(2);
            }
            
          }

          
          $("#edit_purchase_total").val(currency_format_display(purchase_total));


    }

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

    function calc_general_pay(val,id){
      var remain  = $("#total_customer_remaind").attr('data-original-amount');
      var pay     = $("#payment_withdraw_amount").val();

      remain      = parseFloat(remain);

      pay         = parseFloat(pay);

      // alert(remain)
      if(pay > remain){
        $("#payment_withdraw_amount").val('');
        noty({
                        width: 200,
                        text: Translation("ﻗﻴﻤﺔ اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮﻉ اﻛﺒﺮ ﻣﻦ اﻟﻤﺠﻤﻮﻉ اﻟﻜﻠﻲ ﻟﺤﺴﺎﺏ اﻟﺰﺑﻮﻥ .. اﻟﺮﺟﺎء اﺩﺧﺎﻝ اﻟﻘﻴﻤﺔ اﻟﺼﺤﻴﺤﺔ"),
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'topRight',
                      });

      }
    }

    function  Add_New_Row() {

      var curnt_row_num = $("#total_rows").val();
      var CNT = +curnt_row_num + +1;
      var attach_new_row =`
                          <tr  id="item_row_`+CNT+`" >
                            <td width="5%" id="num_`+CNT+`">`+CNT+`</td>
                            <td width="10%">
                              
                              <select class="form-control multi_lang stop_enter" name="product_id_fk_`+CNT+`" id="product_id_fk_`+CNT+`" data-width="100%" placeholder="ﺭﻣﺰ اﻟﻤﺎﺩﺓ" onchange="load_products(this.value,this.id);" data-live-search="true">

                              </select>
                              
                              <input id="item_type_id_`+CNT+`" name="item_type_id_`+CNT+`" type="hidden" placeholder="`+Translation('ﺭﻣﺰ اﻟﻤﺎﺩﺓ')+`">
                              
                            </td>
                            <td width="10%" id="forign_id_`+CNT+`"></td>
                            <td width="8%">
                              <input type="number" autocomplete="~~~~~~~~" value="1" id="purchase_quantity_`+CNT+`" name="purchase_quantity_`+CNT+`"  class="form-control text-center stop_enter" placeholder="`+Translation('اﻟﻌﺪﺩ')+`"  onchange="add_qty_input_fields(this.value,this.id);">
                            </td>
                            <td id="products_`+CNT+`"></td>
                            <td width="7%" >
                              <input id="total_length_`+CNT+`" name="total_length_`+CNT+`" type="text" placeholder="`+Translation('اﻟﻄﻮﻝ اﻟﻜﻠﻲ')+`" class="form-control stop_enter" readonly >
                            </td>
                            <td width="6%">
                              <input id="last_sell_price_`+CNT+`" name="last_sell_price_`+CNT+`" type="text" class="form-control stop_enter" placeholder="`+Translation('اﺧﺮ ﺳﻌﺮ ﺑﻴﻊ')+`" readonly >
                            </td>
                            <td width="8%">
                              <input autocomplete="~~~~~~~~" id="buy_price_per_meter_`+CNT+`" name="buy_price_per_meter_`+CNT+`" type="text" class="form-control stop_enter" placeholder="`+Translation('ﺳﻌﺮ ﺑﻴﻊ اﻟﻤﺘﺮ')+`" onchange="calc_total_item_cost(this.id,`+CNT+`);" >
                            </td>
                            <td width="8%">
                              <input autocomplete="~~~~~~~~" id="sell_discount_`+CNT+`" name="sell_discount_`+CNT+`" data-discount-type="" data-discount-actual="" type="text" class="form-control stop_enter" placeholder="`+Translation('ﺗﻨﺰﻳﻼﺕ')+`" onchange="calc_total_item_cost(this.id,`+CNT+`);" >
                            </td>
                            <td width="9%" > 
                            
                              <input id="total_item_cost_`+CNT+`" name="total_item_cost_`+CNT+`" type="text" value="0 $" class="form-control text-center stop_enter" readonly >
                            </td>
                            <td width="9%">
                              <input autocomplete="~~~~~~~~" type="text" id="purchase_item_note_`+CNT+`" name="purchase_item_note_`+CNT+`" class="form-control stop_enter" placeholder="`+Translation('ﻣﻼﺣﻈﺎﺕ')+`" >
                            </td>
                           <!-- <td width="7%" >
                              <input id="product_pay_`+CNT+`" name="product_pay_`+CNT+`" type="text"  class="form-control text-center" placeholder="`+Translation('اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮﻉ')+`" onchange="calc_payments(`+CNT+`);" >
                            
                            </td> -->
                            <td width="6%">
                              <button class="btn btn-link btn-xs btn_add_item" >
                                <i  class="icon-add text-blue"></i>
                              </button>
                              <button class="btn btn-link btn-xs btn_remove_item" id="row_`+CNT+`" >
                                <i  class="icon-subtract text-danger-600"></i>
                              </button>
                              
                            </td>
                          </tr>
                            `;

            $("#purchase_item_body").append(attach_new_row);
            $("#total_rows").val(CNT);
            get_products(CNT);
            $(".stop_enter").autotab();

    }





    // Editing invoice section


    function  Add_Rows() {

      var curnt_row_num = $("#edit_total_rows").val();
      var CNT = +curnt_row_num + +1;
      var attach_new_row =`
                          <tr  id="edit_item_row_`+CNT+`" >
                            <td width="5%" id="edit_num_`+CNT+`">`+CNT+`</td>
                            <td width="10%">
                              
                              <select class="form-control multi_lang stop_enter" name="edit_product_id_fk_`+CNT+`" id="edit_product_id_fk_`+CNT+`" data-width="100%" placeholder="ﺭﻣﺰ اﻟﻤﺎﺩﺓ" onchange="edit_load_products(this.value,this.id);" data-live-search="true">

                              </select>
                              
                              <input id="edit_item_type_id_`+CNT+`" name="edit_item_type_id_`+CNT+`" type="hidden" placeholder="`+Translation('ﺭﻣﺰ اﻟﻤﺎﺩﺓ')+`">
                              
                            </td>
                            <td width="10%" id="edit_forign_id_`+CNT+`"></td>
                            <td width="8%">
                              <input type="number" value="1" id="edit_purchase_quantity_`+CNT+`" name="edit_purchase_quantity_`+CNT+`"  class="form-control text-center stop_enter" placeholder="`+Translation('اﻟﻌﺪﺩ')+`"  onchange="edit_add_qty_input_fields(this.value,this.id);">
                            </td>
                            <td id="edit_products_`+CNT+`"></td>
                            <td width="7%" >
                              <input id="edit_total_length_`+CNT+`" name="edit_total_length_`+CNT+`" type="text" placeholder="`+Translation('اﻟﻄﻮﻝ اﻟﻜﻠﻲ')+`" class="form-control stop_enter" readonly >
                            </td>
                            <td width="6%">
                              <input id="edit_last_sell_price_`+CNT+`" name="edit_last_sell_price_`+CNT+`" type="text" class="form-control stop_enter" placeholder="`+Translation('اﺧﺮ ﺳﻌﺮ ﺑﻴﻊ')+`" readonly >
                            </td>
                            <td width="8%">
                              <input id="edit_buy_price_per_meter_`+CNT+`" name="edit_buy_price_per_meter_`+CNT+`" type="text" class="form-control stop_enter" placeholder="`+Translation('ﺳﻌﺮ ﺑﻴﻊ اﻟﻤﺘﺮ')+`" onchange="edit_calc_total_item_cost(this.id,`+CNT+`);" >
                            </td>
                            <td width="8%">
                              <input id="edit_sell_discount_`+CNT+`" name="edit_sell_discount_`+CNT+`" data-discount-type="" data-discount-actual="" type="text" class="form-control stop_enter" placeholder="`+Translation('ﺗﻨﺰﻳﻼﺕ')+`" onchange="edit_calc_total_item_cost(this.id,`+CNT+`);" >
                            </td>
                            <td width="9%" > 
                            
                              <input id="edit_total_item_cost_`+CNT+`" name="edit_total_item_cost_`+CNT+`" type="text" value="0 $" class="form-control text-center stop_enter" readonly >
                            </td>
                            <td width="9%">
                              <input type="text" id="edit_purchase_item_note_`+CNT+`" name="edit_purchase_item_note_`+CNT+`" class="form-control stop_enter" placeholder="`+Translation('ﻣﻼﺣﻈﺎﺕ')+`" >
                            </td>
                           <!-- <td width="7%" >
                              <input id="edit_product_pay_`+CNT+`" name="edit_product_pay_`+CNT+`" type="text"  class="form-control text-center" placeholder="`+Translation('اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮﻉ')+`" onchange="calc_payments(`+CNT+`);" >
                            
                            </td> -->
                            <td width="6%">
                              <button class="btn btn-link btn-xs edit_btn_add_item" >
                                <i  class="icon-add text-blue"></i>
                              </button>
                              <button class="btn btn-link btn-xs edit_btn_remove_item" id="edit_row_`+CNT+`" >
                                <i  class="icon-subtract text-danger-600"></i>
                              </button>
                              
                            </td>
                          </tr>
                            `;

            $("#edit_purchase_item_body").append(attach_new_row);
            $("#edit_total_rows").val(CNT);
            get_products(CNT);
            $(".stop_enter").autotab();

    }




    // End editing invoice section

$(document).ready(function() {
  
    get_products(1);
    get_Profile_price();
    get_Customer();
    // escape_notes();
    get_Others(1);
    get_Item_Class();


    // handling two level of modal in same page 

    $('.modal').on('hidden.bs.modal', function (e) {
        if($('.modal').hasClass('in')) {
        $('body').addClass('modal-open');
        }    
    });

    $("#search").on('keyup', function(){

       $('.jQsearch').each(function () {

            // alert($(this).attr('data-search'));


            var strg = $(this).attr('data-search');

            var keywords = $("#search").val();

            var reso = strg.match(keywords);
              
             // alert(reso)

             if(reso == null){
              $(this).attr('style','display:none;');
             }else{
              $(this).attr('style','');
             }
          });


    });


    $("#purchase_item_body").on("keypress","[id^='purchase_item_note_']", function (e) {
          
         // alert(e.keyCode);

          if (e.keyCode == 9 || e.which ==9) {
           
            e.preventDefault();
            
            // Add_New_Row();
            $.autotab.next();
          }else if (e.keyCode == 13 || e.which ==13) {
            e.preventDefault();
           Add_New_Row();
          }

           $.autotab.next();
    });


    // to prevent submitting form
    $("#edit_purchase_item_body").on('click','.edit_btn_add_item',function(e){
        e.preventDefault();

    });

     $("#edit_purchase_item_body").on('click','.edit_btn_remove_item',function(e){
        e.preventDefault();

    });


    // to prevent default show modal on page load

    $('#product_id_fk_1').change(function(e) {
      e.preventDefault();
         load_products(this.value,this.id);
    });

    $('#purchase_quantity_1').change(function(e) {
      e.preventDefault();
         add_qty_input_fields(this.value,this.id);
    });

    // add new row to purchase menu
    $("#purchase_item_body").on('click','.btn_add_item',function(e){
      e.preventDefault();

       Add_New_Row();

     

    });
    

    $("#purchase_item_footer").on('click','#add_others_btn',function(e){
        e.preventDefault();
        var curnt_row_num = $("#total_rows_other").val();
        var CNT = +curnt_row_num + +1;
        var attach_new_row =`
                          <tr  id="item_row_other_`+CNT+`" >
                            <td width="5%" id="num_`+CNT+`">#`+CNT+`</td>
                            <td width="10%" colspan="2">
                              <select class="form-control multi_lang" data-live-search="true" name="other_id_fk_`+CNT+`" id="other_id_fk_`+CNT+`" data-width="100%" placeholder="`+Translation('ﻣﻮاﺩ اﺧﺮﻯ')+`" >
                              </select>
                            </td>
                            
                            <td width="6%">
                              <input type="number" id="other_quantity_`+CNT+`" name="other_quantity_`+CNT+`"  class="form-control multi_lang" placeholder="`+Translation('اﻟﻌﺪﺩ')+`" onchange="calc_other_cost(`+CNT+`);" >
                            </td>
                            <td id="products_other"></td>
                            <td width="7%" >
                              <input id="total_length_other_`+CNT+`" name="total_length_other_`+CNT+`" type="text" class="form-control" readonly >
                            </td>
                            <td width="6%">
                              <input id="last_sell_price_other_`+CNT+`" name="last_sell_price_other_`+CNT+`" type="text" class="form-control multi_lang" placeholder="`+Translation('اﺧﺮ ﺳﻌﺮ ﺑﻴﻊ')+`" readonly >
                            </td>
                            <td width="8%">
                              <input id="buy_price_per_meter_other_`+CNT+`" name="buy_price_per_meter_other_`+CNT+`" type="text" class="form-control multi_lang" placeholder="`+Translation('ﺳﻌﺮ اﻟﺒﻴﻊ')+`" onchange="calc_other_cost(`+CNT+`);" >
                            </td>
                            <td width="8%">
                              <input id="sell_discount_other_`+CNT+`" name="sell_discount_other_`+CNT+`" data-discount-type="" data-discount-actual="" type="text" class="form-control multi_lang" placeholder="`+Translation('ﺗﻨﺰﻳﻼﺕ')+`" onchange="calc_other_cost(`+CNT+`);" >
                            </td>
                            <td width="9%" >
                              <input id="total_item_cost_other_`+CNT+`" name="total_item_cost_other_`+CNT+`" type="text" value="0 $" class="form-control text-center" readonly >
                            
                            </td>
                            <td width="9%">
                              <textarea type="text" id="purchase_item_note_other_`+CNT+`" name="purchase_item_note_other_`+CNT+`" class="form-control multi_lang" placeholder="`+Translation('ﻣﻼﺣﻈﺎﺕ')+`" > </textarea>
                            </td>
                           <!-- <td width="7%" >
                              <input id="other_pay_`+CNT+`" name="other_pay_1" type="text"  class="form-control multi_lang text-center" placeholder="`+Translation('اﻟﻤﺒﻠﻎ اﻟﻤﺪﻏﻮﻉ')+`" onchange="calc_payments('other',`+CNT+`);" >
                            
                            </td> -->
                            <td width="6%">
                              <button class="btn btn-link" id="add_others_btn">
                                <i  class="icon-database-add text-teal"></i>
                              </button>
                              <button class="btn btn-link btn-xs btn_other_remove_item" id="row_other_`+CNT+`" >
                                <i  class="icon-subtract text-danger-600"></i>
                              </button>
                            </td>
                          </tr>
                            `;

            $("#item_row_other_"+(CNT-1)).after(attach_new_row);
            $("#total_rows_other").val(CNT);
            get_Others(CNT);
    });


    // remove current other row 
    $("#purchase_item_footer").on('click','.btn_other_remove_item',function(e){
          e.preventDefault();
          // console.log(this.id);
          var row_num1 = this.id.split('_');
          var row_num = row_num1[2];
          $("#item_row_other_"+row_num).remove();
          calc_total_purchase_price();
          calc_payments();
    });

    // remove current row 
    $("#purchase_item_body").on('click','.btn_remove_item',function(e){
          e.preventDefault();
          // console.log(this.id);
          var row_num1 = this.id.split('_');
          var row_num = row_num1[1];
          $("#item_row_"+row_num).remove();
          calc_total_purchase_price();
          calc_payments();
    });


    $("#edit_purchase_item_body").on('click','.edit_btn_remove_item',function(e){
          e.preventDefault();
          // console.log(this.id);
          var row_num1 = this.id.split('_');
          var row_num = row_num1[2];
          $("#edit_item_row_"+row_num).remove();

          edit_calc_total_purchase_price();
          // calc_total_purchase_price();

          edit_calc_payments();
          
    });

    $("#default_val_btn").on('click',function(){
        var qty   =$("#fields_count").val();
        var deflt = $("#default_val").val();
        for (var i = 1; i <= qty; i++) {
          $("#roll_length_"+i).val(deflt);
        }
     })

    $("#edit_default_val_btn").on('click',function(){
        var qty   = $("#edit_fields_count").val();
        var deflt = $("#edit_default_val").val();
        for (var i = 1; i <= qty; i++) {
          $("#edit_roll_length_"+i).val(deflt);
        }
     })


   


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

          e.preventDefault();

          var cust_id                   = $("#customer_id_fk_pay").val();
          var payment_amount            = $("#payment_withdraw_amount").val();
          var paid_date                 = $("#paid_date").val();
          var payment_note              = $("#payment_note").val();
          var pay_type                  = $("#pay_type").val();
          var item_type_id_fk           = $("#item_type_id_fk").val();
         

          var check_paid  = false;
          var check_ids   = true;

          check_paid      = Checks('payment_withdraw_amount','No',0.000001);

        

          if(check_paid && check_ids){
            $("#submit_add_pay_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_invoice.php",
                type:"POST",
                dataType: "JSON",
                data : {cust_id              :cust_id,
                        payment_amount       :payment_amount,
                        paid_date            :paid_date,
                        payment_note         :payment_note,
                        pay_type             :pay_type,
                        item_type_id_fk      :item_type_id_fk,
                        type                 :'add_payments'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                   

                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    $('#add_payments_modal').modal('toggle');
                    
                    noty({
                                    width: 200,
                                    text: Translation(res.data),
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 2000,
                                    layout: 'topRight',
                                    callback: {
                                              onShow: function() {},
                                              afterShow: function() {},
                                              onClose: function() {},
                                              afterClose: function() {},
                                              onCloseClick: function() {},
                                            },
                              });

                    // i will reload the page to reset all fields
                    
               
                  }else{
                      swal({
                          title: Translation("ﺧﻄﺄ"),
                          text: Translation(res.data),
                          confirmButtonColor: "#66BB6A",
                          type: "warning"
                      });
                      //$("#add-form-cont").collapse('hide');
                  }

                $("#submit_add_pay_btn").attr('disabled',false);
            })
            .fail(function(err) {
                 swal({
                    title: Translation("ﺧﻄﺄ"),
                    text: (err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                $("#submit_add_pay_btn").attr('disabled',false);
            })
            .always(function() {
                console.log("complete");
            });
          }else{
              noty({
                    width: 200,
                    text: Translation('اﻟﺮﺟﺎء اﻟﺘﺄﻛﺪ ﻣﻦ اﻟﻘﻴﻢ اﻟﻤﺪﺧﻠﺔ ﻭاﻳﻀﺎ ﻳﺠﺐ اﺩﺧﺎﻝ ﺩﻓﻌﺔ ﺟﺪﻳﺪﺓ ﻋﻠﻰ اﻻﻗﻞ'),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
          }

          

    });

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

          e.preventDefault();

          var qty     = $("#fields_count").val();
          var row_no  = $("#rows_count").val();
          var attach_input ="";
          var total_roll_length =0;
          for (var i = 1; i <= qty; i++) {
            
            total_roll_length = +total_roll_length + +$("#roll_length_"+i).val();

            attach_input = attach_input + `<input data-roll-id-fk="0" types="text" id="row_`+row_no+`_roll_`+i+`" class="badge badge-primary col-sm-5" value="`+$("#roll_length_"+i).val()+`" onchange="calc_total_length(`+row_no+`,`+qty+`);">`;
          }
          
          $("#products_"+row_no).html(attach_input);
          $("#total_length_"+row_no).val(total_roll_length);
          var total_item_cost = total_roll_length * $("#buy_price_per_meter_"+row_no).val();
          $("#total_item_cost_"+row_no).val(currency_format_display(total_item_cost));
          calc_total_purchase_price();
          $('#add_new_product').modal('toggle');

    });


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

          e.preventDefault();

          var qty     = $("#edit_fields_count").val();
          var row_no  = $("#edit_rows_count").val();
          var attach_input ="";
          var total_roll_length =0;
          for (var i = 1; i <= qty; i++) {
            
            total_roll_length = +total_roll_length + +$("#edit_roll_length_"+i).val();

            attach_input = attach_input + `<input data-roll-id-fk="0" types="text" id="edit_row_`+row_no+`_roll_`+i+`" class="badge badge-primary col-sm-5" value="`+$("#edit_roll_length_"+i).val()+`" onchange="edit_calc_total_length(`+row_no+`,`+qty+`);">`;
          }
          
          $("#edit_products_"+row_no).html(attach_input);
          $("#edit_total_length_"+row_no).val(total_roll_length);
          var total_item_cost = total_roll_length * $("#edit_buy_price_per_meter_"+row_no).val();
          $("#edit_total_item_cost_"+row_no).val(currency_format_display(total_item_cost));
          edit_calc_total_purchase_price();
          $('#edit_add_new_product').modal('toggle');

    });


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

          e.preventDefault();

          var qty               = $("#fields_count_purchase").val();
          var row_no            = $("#rows_count_purchase").val();
          var qty_all_rolls     = $("#rolls_count_purchase").val();
          var attach_input      = "";
          var total_roll_length = 0;
          var k =1;
          for (var i = 0; i <  qty_all_rolls; i++) {
            
            
            if($("#part_roll_length_"+i).val() !='' && $("#part_roll_length_"+i).val() != undefined){
              total_roll_length = +total_roll_length + +$("#part_roll_length_"+i).val();
              
              // we should store id-fk for selected rolls
              var original_roll_length  = $("#checked_roll_"+i).attr('data-roll-length');
              var roll_id_fk            = $("#checked_roll_"+i).attr('data-roll-id-fk');
              var roll_status           = $("#checked_roll_"+i).attr('data-item-status');
              var remained_length       = $("#checked_roll_"+i).attr('data-remained-length');
              attach_input = attach_input + `<input data-item-status="`+roll_status+`" data-remained-length="`+remained_length+`"  data-roll-id-fk="`+roll_id_fk+`" data-roll-length="`+original_roll_length+`" types="text" id="row_`+row_no+`_roll_`+k+`" class="badge bg-orange-400 col-sm-6" value="`+$("#part_roll_length_"+i).val()+`" onchange="calc_total_length(`+row_no+`,`+qty+`);" readonly>`;
              k = k +1;
            }
          }
          
          $("#products_"+row_no).html(attach_input);
          $("#total_length_"+row_no).val(total_roll_length);
          // update the quantity field to fit with selected product
          $("#purchase_quantity_"+row_no).val(k-1);
          var total_item_cost = total_roll_length * $("#buy_price_per_meter_"+row_no).val();

          
          $("#total_item_cost_"+row_no).val(currency_format_display(total_item_cost));
          calc_total_purchase_price();
          $('#add_new_product_from_purchase').modal('toggle');

    });


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

          e.preventDefault();

          var qty               = $("#edit_fields_count_purchase").val();
          var row_no            = $("#edit_rows_count_purchase").val();
          var qty_all_rolls     = $("#edit_rolls_count_purchase").val();
          var attach_input      = "";
          var total_roll_length = 0;
          var k =1;
          for (var i = 0; i <  qty_all_rolls; i++) {
            
            
            if($("#edit_part_roll_length_"+i).val() !='' && $("#edit_part_roll_length_"+i).val() != undefined){
              total_roll_length = +total_roll_length + +$("#edit_part_roll_length_"+i).val();
              
              // we should store id-fk for selected rolls
              var original_roll_length  = $("#edit_checked_roll_"+i).attr('data-roll-length');
              var roll_id_fk            = $("#edit_checked_roll_"+i).attr('data-roll-id-fk');
              var roll_status           = $("#edit_checked_roll_"+i).attr('data-item-status');
              var remained_length       = $("#edit_checked_roll_"+i).attr('data-remained-length');
              

              attach_input = attach_input + `<input data-item-status="`+roll_status+`" data-remained-length="`+remained_length+`"  data-roll-id-fk="`+roll_id_fk+`" data-roll-length="`+original_roll_length+`" types="text" id="edit_row_`+row_no+`_roll_`+k+`" class="badge bg-orange-400 col-sm-6" value="`+$("#edit_part_roll_length_"+i).val()+`" onchange="edit_calc_total_length(`+row_no+`,`+qty+`);" readonly>`;
              k = k +1;
            }
          }
          
          $("#edit_products_"+row_no).html(attach_input);
          $("#edit_total_length_"+row_no).val(total_roll_length);
          // update the quantity field to fit with selected product
          $("#edit_purchase_quantity_"+row_no).val(k-1);
          var total_item_cost = total_roll_length * $("#edit_buy_price_per_meter_"+row_no).val();

          
          $("#edit_total_item_cost_"+row_no).val(currency_format_display(total_item_cost));
          edit_calc_total_purchase_price();
          $('#edit_add_new_product_from_purchase').modal('toggle');

    });





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

          var cnt                                 = $("#total_rows").val();
          
          var product_id_array                    =[];
          var quantity_array                      =[];
          var roll_length_array                   =[];
          var roll_total_array                    =[];
          var unit_price_array                    =[];
          var discount_val_array                  =[];
          var discount_type_array                 =[];
          var discount_actual_array               =[];
          var roll_id_fk_array                    =[];
          var roll_id_fk_total_array              =[];
          var roll_origianl_length_array          =[];
          var roll_original_length_total_array    =[];
          var row_total_price_array               =[];
          var notes_array                         =[];
          // var payments_array                      =[];
          var item_type_array                     =[];

          var check_products                      =[];
          var check_quantity                      =[];
          var check_price                         =[];
          var check_rolls                         =[];
          var check_rolls_all                     =[];
          var k=1;

          for(var i =1; i <= cnt; i++){

              var productID       = $("#product_id_fk_"+i).val();
              var itemTypeID      = $("#item_type_id_"+i).val();
              var quantityField   = $("#purchase_quantity_"+i).val();
              var unit_price      = $("#buy_price_per_meter_"+i).val();
              var notes           = $("#purchase_item_note_"+i).val();
              var row_total_price = $("#total_item_cost_"+i).val();
              // var product_pay     = $("#product_pay_"+i).val();
              var discount        = $("#sell_discount_"+i).val();
              var discount_type   = $("#sell_discount_"+i).attr('data-discount-type');
              var discount_actual = $("#sell_discount_"+i).attr('data-discount-actual');



              if(productID != undefined && productID != null && productID != ''){
                row_total_price     = row_total_price.replace('$','');
                row_total_price     = row_total_price.replace(/,/g,'');
                row_total_price     = parseFloat(row_total_price);

                check_products[k]         = Checks('product_id_fk_'+i);
                check_quantity[k]         = Checks('purchase_quantity_'+i,'No',1);
                check_price[k]            = Checks('buy_price_per_meter_'+i,'No',0.00000001);
                //console.log(check_quantity)
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                notes_array[k]            = notes;
                unit_price_array[k]       = unit_price;
                discount_val_array[k]     = discount;
                discount_type_array[k]    = discount_type;
                discount_actual_array[k]  = discount_actual;
                row_total_price_array[k]  = row_total_price;
                // payments_array[k]         = product_pay;
                item_type_array[k]        = itemTypeID;
                // now i should check for rolls number and it should equal to quantity
                roll_length_array          =[];
                check_rolls                =[];
                roll_id_fk_array           =[];
                roll_origianl_length_array =[];

                for(var j=1; j<=quantityField; j++){
                  check_rolls[j]           = Checks('row_'+i+'_roll_'+j,'No',1,null,'badge');
                  var rolls                = $('#row_'+i+'_roll_'+j).val();
                  var roll_id_fk           = $('#row_'+i+'_roll_'+j).attr('data-roll-id-fk');
                  var roll_original_length = $('#row_'+i+'_roll_'+j).attr('data-roll-length');
                  
                  
                  roll_id_fk_array[j]            = roll_id_fk;

                  roll_origianl_length_array[j]  = roll_original_length;
          
                  
                  console.log(rolls);
                  console.log('#row_'+k+'_roll_'+j);

                  roll_length_array[j]    = rolls;
                }

                roll_id_fk_total_array[k]           = roll_id_fk_array;
                roll_original_length_total_array[k] = roll_origianl_length_array;
                roll_total_array[k]                 = roll_length_array;
                check_rolls_all[k]                  = check_rolls;
                // end checking rolls number
                console.log(roll_length_array);
                console.log(roll_total_array);
                console.log(roll_id_fk_array);
                console.log(roll_id_fk_total_array);
                k++;
              }
          }
          
          var invoice_type       = $("#invoice_type").val();  //0 raw ; 1 curtain
          var customer_id_fk     = $("#customer_id_fk").val();
          var pay_term           = $("#pay_term").val();
          var invoice_date       = $("#invoice_date").val();
          var price_profile_id   = $("#price_profile_id").val();
          // var sell_discount_type = $("#sell_discount_type").val();
          var invoice_note       = $("#invoice_note").val();
          var total_invoice      = $("#purchase_total").val();
          var total_paid         = $("#total_paid").val();
          total_invoice          = total_invoice.replace('$','');
          total_invoice          = total_invoice.replace(/,/g,'');
          total_invoice          = parseFloat( total_invoice);
          
          // total_paid             = total_paid.replace('$','');
          // total_paid             = total_paid.replace(/,/g,'');
          // total_paid             = parseFloat( total_paid);

          







          // other products

          var cnt                                 = $("#total_rows_other").val();
          
          var other_id_array                    =[];
          var other_quantity_array                      =[];
          var other_price_array                    =[];
          var other_discount_val_array                  =[];
          var other_discount_type_array                 =[];
          var other_discount_actual_array               =[];
          var other_row_total_price_array               =[];
          var other_notes_array                         =[];
          // var other_payments_array                      =[];
          
          
          var check_quantity_other                      =[];
          var check_price_other                         =[];
          var k=1;

          for(var i =1; i <= cnt; i++){

              var productID       = $("#other_id_fk_"+i).val();
              var quantityField   = $("#other_quantity_"+i).val();
              var unit_price      = $("#buy_price_per_meter_other_"+i).val();
              var notes           = $("#purchase_item_note_other_"+i).val();
              var row_total_price = $("#total_item_cost_other_"+i).val();
              // var product_pay     = $("#other_pay_"+i).val();
              var discount        = $("#sell_discount_other_"+i).val();
              var discount_type   = $("#sell_discount_other_"+i).attr('data-discount-type');
              var discount_actual = $("#sell_discount_other_"+i).attr('data-discount-actual');

              
              if(productID != undefined && productID != null && productID != '' ){

                row_total_price     = row_total_price.replace('$','');
                row_total_price     = row_total_price.replace(/,/g,'');
                row_total_price     = parseFloat(row_total_price);


                check_quantity_other[k]         = Checks('other_quantity_'+i,'No',1);
                check_price_other[k]            = Checks('buy_price_per_meter_other_'+i,'No',0.00000001);
                //console.log(check_quantity)
                other_id_array[k]       = productID;
                other_quantity_array[k]         = quantityField;
                other_notes_array[k]            = notes;
                other_price_array[k]       = unit_price;
                other_discount_val_array[k]     = discount;
                other_discount_type_array[k]    = discount_type;
                other_discount_actual_array[k]  = discount_actual;
                other_row_total_price_array[k]  = row_total_price;
                // other_payments_array[k]         = product_pay;
                
                
                k++;
              }
          }

          
          
          

          

          var Check1      = Checks('customer_id_fk');
          var Check2      = Checks('price_profile_id');
          
          var CheckPro    = true;
          var checkQty    = true;
          var checkrolls  = true;
          var checkprice  = true;
          
          var checkpriceOther  = true;
          var checkQtyOther  = true;

          for(m=1;m<=check_products.length;m++){

            if(check_products[m]==false){
              CheckPro = false;
            }
            if(check_quantity[m]==false){
              checkQty = false;
            }

            if(check_price[m]==false){
              checkprice = false;
            }

            for(var n=1;n<=roll_total_array[m];n++){
              if(check_rolls_all[m][n]==false){
                checkrolls = false;
              }
            }

          }

          for(m=1;m<=check_quantity_other.length;m++){

            
            if(check_quantity_other[m]==false){
              checkQtyOther = false;
            }

            if(check_price_other[m]==false){
              checkpriceOther = false;
            }

            

          }

          // if there is no other in invoice we should make its value to be send in ajax
          if(other_id_array.length ==0){
             other_id_array[0]                    =0;
             other_quantity_array[0]              =0;
             other_price_array[0]                 =0;
             other_discount_val_array[0]          =0;
             other_discount_type_array[0]         =0;
             other_discount_actual_array[0]       =0;
             other_row_total_price_array[0]       =0;
             other_notes_array[0]                 =0;
             // other_payments_array              ='';
          }



        if(Check1 && Check2 && CheckPro && checkQty && checkrolls && checkprice && checkpriceOther && checkQtyOther){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_invoice.php",
                type:"POST",
                dataType: "JSON",
                data : {invoice_type              :invoice_type,
                        customer_id_fk            :customer_id_fk,
                        pay_term                  :pay_term,
                        invoice_date              :invoice_date,
                        price_profile_id          :price_profile_id,
                        invoice_note              :invoice_note,
                        

                        other_id_fk               :other_id_array,
                        other_quantity_1          :other_quantity_array,
                        other_sell_price          :other_price_array,
                        other_discount            :other_discount_val_array,
                        other_discount_type       :other_discount_type_array,
                        other_discount_actual     :other_discount_actual_array,
                        other_note                :other_notes_array,
                        other_row_price           :other_row_total_price_array,
                        // other_pay                 :other_payments_array,
                        
                        total_invoice             :total_invoice,
                        total_paid                :total_paid,

                        product_id                :product_id_array,
                        quantity                  :quantity_array,
                        item_length               :roll_total_array,
                        sell_price                :unit_price_array,
                        discount                  :discount_val_array,
                        discount_type             :discount_type_array,
                        discount_actual           :discount_actual_array,
                        roll_id_fk                :roll_id_fk_total_array,
                        sell_item_note            :notes_array,
                        row_price                 :row_total_price_array,
                        // row_payments              :payments_array,
                        item_type                 :item_type_array,
                        original_length           :roll_original_length_total_array,
                        type                      :'create'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                    // remove table rows
                    $('tr[id^="item_row_"]').each(function(){ 
                        if( this.id !='item_row_1' && this.id !='item_row_other') 
                        {
                          $(this).remove();          
                        }         
                    });

                    // empty td rows
                    $('td[id^="products_"]').each(function(){ 
                        
                          $(this).html('');                  
                    });

                    $('td[id^="forign_id_"]').each(function(){ 
                        
                          $(this).html('');                  
                    });

                    $("#price_profile_id").val('0').selectpicker('refresh');
                    $("#customer_id_fk").val('0').selectpicker('refresh');
                    $("#other_id_fk").val('0').selectpicker('refresh');
                    $("#total_rows").val('1');


                    // $("#product_name").val('');
                    // $("#erbil_code").val('');
                    // $("#turkish_code").val('');
                    // $("#barcode").val('');
                    // $("#product_note").val('');
                    // $(".fileinput-remove-button").trigger('click');

                    $(".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: 2000,
                                    layout: 'topRight',
                                    callback: {
                                              onShow: function() {},
                                              afterShow: function() {},
                                              onClose: function() {location.reload();},
                                              afterClose: function() {},
                                              onCloseClick: function() {},
                                            },
                              });

                    // i will reload the page to reset all fields
                    
               
                }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: (err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                $("#submit_add_btn").attr('disabled',false);
            })
            .always(function() {
                console.log("complete");
            });
        }else{
          noty({
                    width: 200,
                    text: Translation('اﻟﺮﺟﺎء اﻟﺘﺄﻛﺪ ﻣﻦ اﻟﻘﻴﻢ اﻟﻤﺪﺧﻠﺔ ﻭاﻳﻀﺎ اﻟﺘﺤﻘﻖ ﻣﻦ اﻥ اﻻﻃﻮاﻝ اﻟﻤﺤﺪﺩﺓ ﻣﺴﺎﻭﻳﺔ ﻟﻠﻌﺪﺩ'),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
        }

    });
  



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

      var cnt                                 = $("#edit_total_rows").val();
      
      var product_id_array                    =[];
      var quantity_array                      =[];
      var roll_length_array                   =[];
      var roll_total_array                    =[];
      var unit_price_array                    =[];
      var discount_val_array                  =[];
      var discount_type_array                 =[];
      var discount_actual_array               =[];
      var roll_id_fk_array                    =[];
      var roll_id_fk_total_array              =[];
      var roll_origianl_length_array          =[];
      var roll_original_length_total_array    =[];
      var row_total_price_array               =[];
      var notes_array                         =[];
      var item_type_array                     =[];
      var check_products                      =[];
      var check_quantity                      =[];
      var check_price                         =[];
      var check_rolls                         =[];
      var check_rolls_all                     =[];

      // from edit
      var sell_id_array                       =[];        
      var check_quantity_other                =[];
      var check_price_other                   =[];


      var k=1;

      // end this 


      for(var i =0; i <= cnt; i++){

          var productID       = $("#edit_product_id_fk_"+i).val();
          var sellID          = $("#edit_product_id_fk_"+i).attr('data-sell-id');
          var itemTypeID      = $("#edit_item_type_id_"+i).val();
          var quantityField   = $("#edit_purchase_quantity_"+i).val();
          var unit_price      = $("#edit_buy_price_per_meter_"+i).val();
          var notes           = $("#edit_purchase_item_note_"+i).val();
          var row_total_price = $("#edit_total_item_cost_"+i).val();
          // var product_pay     = $("#edit_product_pay_"+i).val();
          // var product_pay_id  = $("#edit_product_pay_"+i).attr('data-payment-id-fk');
          var discount        = $("#edit_sell_discount_"+i).val();
          var discount_type   = $("#edit_sell_discount_"+i).attr('data-discount-type');
          var discount_actual = $("#edit_sell_discount_"+i).attr('data-discount-actual');

       
          if(productID != undefined && productID != null && productID != ''){
            row_total_price     = row_total_price.replace('$','');
            row_total_price     = row_total_price.replace(/,/g,'');
            row_total_price     = parseFloat(row_total_price);

            check_products[k]         = Checks('edit_product_id_fk_'+i);
            check_quantity[k]         = Checks('edit_purchase_quantity_'+i,'No',1);
            check_price[k]            = Checks('edit_buy_price_per_meter_'+i,'No',0.00000001);
            product_id_array[k]       = productID;
            quantity_array[k]         = quantityField;
            notes_array[k]            = notes;
            unit_price_array[k]       = unit_price;
            discount_val_array[k]     = discount;
            discount_type_array[k]    = discount_type;
            discount_actual_array[k]  = discount_actual;
            row_total_price_array[k]  = row_total_price;
            item_type_array[k]        = itemTypeID;

            sell_id_array[k]          = sellID;

            // now i should check for rolls number and it should equal to quantity
            roll_length_array          =[];
            check_rolls                =[];
            roll_id_fk_array           =[];
            roll_origianl_length_array =[];

            var j =1;
            $('input[id^="edit_row_'+i+'_roll_"]').each(function() 
              { 
                if(!isNaN(this.value) && this.value.length!=0) 
                {
                  
                  check_rolls[j]           = Checks(this.id,'No',1,null,'badge');
                  var rolls                = this.value;
                  var roll_id_fk           = $(this).attr('data-roll-id-fk');
                  var roll_original_length = $(this).attr('data-roll-length');
                  
                  
                  roll_id_fk_array[j]            = roll_id_fk;

                  roll_origianl_length_array[j]  = roll_original_length;
          
                  
                  console.log(rolls);
                  console.log(this.id);

                  roll_length_array[j]    = rolls;

                  j++;
                }         
            });


            roll_id_fk_total_array[k]           = roll_id_fk_array;
            roll_original_length_total_array[k] = roll_origianl_length_array;
            roll_total_array[k]                 = roll_length_array;
            check_rolls_all[k]                  = check_rolls;
            // end checking rolls number
            console.log(roll_length_array);
            console.log(roll_total_array);
            console.log(roll_id_fk_array);
            console.log(roll_id_fk_total_array);
            k++;
          }
      }

       
      var invoice_id         = $("#edit_invoice_id").val();
      var invoice_number     = $("#edit_invoice_number").val();


      var invoice_type       = $("#edit_invoice_type").val();  //0 raw ; 1 curtain
      var is_single          = $("#edit_is_single").val();  //0 raw ; 1 curtain
      var customer_id_fk     = $("#edit_customer_id_fk").attr('data-fk');
      var pay_term           = $("#edit_pay_term").val();
      var invoice_date       = $("#edit_invoice_date").val();
      var price_profile_id   = $("#edit_price_profile_id").val();
      
      var invoice_note       = $("#edit_invoice_note").val();
      var total_invoice      = $("#edit_purchase_total").val();
      var total_paid         = $("#edit_total_paid").val();
      var payment_id         = $("#edit_total_paid").attr('data-payment_id');

      total_invoice          = total_invoice.replace('$','');
      total_invoice          = total_invoice.replace(/,/g,'');
      total_invoice          = parseFloat( total_invoice);
     

      if(payment_id == null || payment_id == '' || payment_id == undefined){
        payment_id = 0;
      }



      // other products

      var cnt                                       = $("#edit_total_rows_other").val();
      
      var other_id_array                    =[];
      var other_quantity_array              =[];
      var other_price_array                 =[];
      var other_discount_val_array          =[];
      var other_discount_type_array         =[];
      var other_discount_actual_array       =[];
      var other_row_total_price_array       =[];
      var other_notes_array                 =[];    
      
      var check_quantity_other              =[];
      var check_price_other                 =[];
      var k=1;    
         

      for(var i =0; i <= cnt; i++){

          var productID       = $("#edit_other_id_fk_"+i).attr('data-other-id');
          var sellID          = $("#edit_other_id_fk_"+i).attr('data-sell-id');
          var quantityField   = $("#edit_other_quantity_"+i).val();
          var unit_price      = $("#edit_buy_price_per_meter_other_"+i).val();
          var notes           = $("#edit_purchase_item_note_other_"+i).val();
          var row_total_price = $("#edit_total_item_cost_other_"+i).val();
          var discount        = $("#edit_sell_discount_other_"+i).val();
          var discount_type   = $("#edit_sell_discount_other_"+i).attr('data-discount-type');
          var discount_actual = $("#edit_sell_discount_other_"+i).attr('data-discount-actual');

          
          if(productID != undefined && productID != null && productID != '' ){

            row_total_price     = row_total_price.replace('$','');
            row_total_price     = row_total_price.replace(/,/g,'');
            row_total_price     = parseFloat(row_total_price);


            check_quantity_other[k]         = Checks('edit_other_quantity_'+i,'No',1);
            check_price_other[k]            = Checks('edit_buy_price_per_meter_other_'+i,'No',0.00000001);
            

            sell_id_array[k]                = sellID;

            other_id_array[k]               = productID;
            other_quantity_array[k]         = quantityField;
            other_notes_array[k]            = notes;
            other_price_array[k]            = unit_price;
            other_discount_val_array[k]     = discount;
            other_discount_type_array[k]    = discount_type;
            other_discount_actual_array[k]  = discount_actual;
            other_row_total_price_array[k]  = row_total_price;
            
            
            k++;
          }
      }         
      console.log(sell_id_array);
      console.log(product_id_array);
      console.log(unit_price_array);
      console.log(row_total_price_array);

      var Check1            = Checks('edit_customer_id_fk');
      var Check2            = true; 
      
       
      var CheckPro          = true;
      var checkQty          = true;
      var checkrolls        = true;
      var checkprice        = true;
      
      var checkpriceOther   = true;
      var checkQtyOther     = true;

      for(m=1;m<=check_products.length;m++){

        if(check_products[m]==false){
          CheckPro = false;
        }
        if(check_quantity[m]==false){
          checkQty = false;
        }

        if(check_price[m]==false){
          checkprice = false;
        }

        for(var n=1;n<=roll_total_array[m];n++){
          if(check_rolls_all[m][n]==false){
            checkrolls = false;
          }
        }

      }

      for(m=1;m<=check_quantity_other.length;m++){

        
        if(check_quantity_other[m]==false){
          checkQtyOther = false;
        }

        if(check_price_other[m]==false){
          checkpriceOther = false;
        }

        

      }




      // if there is no other in invoice we should make its value to be send in ajax
      if(other_id_array.length ==0){
         other_id_array[0]                    =0;
         other_quantity_array[0]              =0;
         other_price_array[0]                 =0;
         other_discount_val_array[0]          =0;
         other_discount_type_array[0]         =0;
         other_discount_actual_array[0]       =0;
         other_row_total_price_array[0]       =0;
         other_notes_array[0]                 =0;
      }



      if(Check1 && Check2 && CheckPro && checkQty && checkrolls && checkprice && checkpriceOther && checkQtyOther){
        $("#submit_edit_btn").attr('disabled',true);
        
        $.ajax({
          url: "models/crul_invoice.php",
          type:"POST",
          dataType: "JSON",
          data : {invoice_type              :invoice_type,
                  customer_id_fk            :customer_id_fk,
                  pay_term                  :pay_term,
                  invoice_date              :invoice_date,
                  price_profile_id          :price_profile_id,
                  invoice_note              :invoice_note,
                  

                  other_id_fk               :other_id_array,
                  other_quantity_1          :other_quantity_array,
                  other_sell_price          :other_price_array,
                  other_discount            :other_discount_val_array,
                  other_discount_type       :other_discount_type_array,
                  other_discount_actual     :other_discount_actual_array,
                  other_note                :other_notes_array,
                  other_row_price           :other_row_total_price_array,
                  // other_pay                 :other_payments_array,
                  
                  total_invoice             :total_invoice,
                  total_paid                :total_paid,

                  product_id                :product_id_array,
                  quantity                  :quantity_array,
                  item_length               :roll_total_array,
                  sell_price                :unit_price_array,
                  discount                  :discount_val_array,
                  discount_type             :discount_type_array,
                  discount_actual           :discount_actual_array,
                  roll_id_fk                :roll_id_fk_total_array,
                  sell_item_note            :notes_array,
                  row_price                 :row_total_price_array,
                  item_type                 :item_type_array,
                  original_length           :roll_original_length_total_array,
    
                  invoice_id                :invoice_id,
                  is_single                 :is_single,
                  invoice_number            :invoice_number,
                
                  payment_id                :payment_id,
                  sell_item_id              :sell_id_array,
                  sell_item_note            :notes_array,
                  row_price                 :row_total_price_array,
                  
                  type                      :'update'}
        })
        .done(function(res) {
           
          if(res.is_success == true){

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

                  


                   

            $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    
            $('#edit_form_cont').modal('toggle');
                    
            noty({
                  width: 200,
                  text: Translation(res.data),
                  type: 'success',
                  dismissQueue: true,
                  timeout: 2000,
                  layout: 'topRight',
                  callback: {
                            onShow: function() {},
                            afterShow: function() {},
                            onClose: function() {},
                            afterClose: function() {},
                            onCloseClick: function() {},
                          },
            });
            
         
          }else{
              swal({
                  title: Translation("ﺧﻄﺄ"),
                  text: Translation(res.data),
                  confirmButtonColor: "#66BB6A",
                  type: "warning"
              });
              //$("#add-form-cont").collapse('hide');
          }

          $("#submit_edit_btn").attr('disabled',false);
        })
        .fail(function(err) {
            swal({
                title: Translation("ﺧﻄﺄ"),
                text: (err),
                confirmButtonColor: "#66BB6A",
                type: "error"
            });
            $("#submit_edit_btn").attr('disabled',false);
        })
        .always(function() {
            console.log("complete");
        });
      }else{
        noty({
                  width: 200,
                  text: Translation('اﻟﺮﺟﺎء اﻟﺘﺄﻛﺪ ﻣﻦ اﻟﻘﻴﻢ اﻟﻤﺪﺧﻠﺔ ﻭاﻳﻀﺎ اﻟﺘﺤﻘﻖ ﻣﻦ اﻥ اﻻﻃﻮاﻝ اﻟﻤﺤﺪﺩﺓ ﻣﺴﺎﻭﻳﺔ ﻟﻠﻌﺪﺩ'),
                  type: 'error',
                  dismissQueue: true,
                  timeout: 3000,
                  layout: 'topRight',
            });
      }

    });




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

          var cnt                                 = $("#edit_total_rows").val();
          
          var product_id_array                    =[];
          var quantity_array                      =[];
          var unit_price_array                    =[];
          var discount_val_array                  =[];
          var discount_type_array                 =[];
          var discount_actual_array               =[];
          var row_total_price_array               =[];
          var notes_array                         =[];
          // var payments_array                      =[];
          // var payments_id_array                   =[];
          var sell_id_array                       =[];

          var check_products                      =[];
          var check_quantity                      =[];
          var check_price                         =[];
          
          var check_quantity_other                =[];
          var check_price_other                   =[];


          var k=0;

          for(var i =0; i < cnt; i++){

              var productID       = $("#edit_product_id_fk_"+i).val();
              var sellID          = $("#edit_product_id_fk_"+i).attr('data-sell-id');
              
              var quantityField   = $("#edit_purchase_quantity_"+i).val();
              var unit_price      = $("#edit_buy_price_per_meter_"+i).val();
              var notes           = $("#edit_purchase_item_note_"+i).val();
              var row_total_price = $("#edit_total_item_cost_"+i).val();
              // var product_pay     = $("#edit_product_pay_"+i).val();
              // var product_pay_id  = $("#edit_product_pay_"+i).attr('data-payment-id-fk');
              var discount        = $("#edit_sell_discount_"+i).val();
              var discount_type   = $("#edit_sell_discount_"+i).attr('data-discount-type');
              var discount_actual = $("#edit_sell_discount_"+i).attr('data-discount-actual');



              if(productID != undefined && productID != null && productID != '' ){
                row_total_price     = row_total_price.replace('$','');
                row_total_price     = row_total_price.replace(/,/g,'');
                row_total_price     = parseFloat(row_total_price);

                check_products[k]         = Checks('edit_product_id_fk_'+i);
                check_quantity[k]         = Checks('edit_purchase_quantity_'+i,'No',1);
                check_price[k]            = Checks('edit_buy_price_per_meter_'+i,'No',0.00000001);
                //console.log(check_quantity)
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                notes_array[k]            = notes;
                unit_price_array[k]       = unit_price;
                discount_val_array[k]     = discount;
                discount_type_array[k]    = discount_type;
                discount_actual_array[k]  = discount_actual;
                row_total_price_array[k]  = row_total_price;
                // payments_array[k]         = product_pay;
                // payments_id_array[k]      = product_pay_id;
                sell_id_array[k]          = sellID;
                // now i should check for rolls number and it should equal to quantity
                

                
                k++;
              }
          }
          
          var invoice_id         = $("#edit_invoice_id").val();
          var invoice_number     = $("#edit_invoice_number").val();


          var invoice_type       = $("#edit_invoice_type").val();  //0 raw ; 1 curtain
          var is_single          = $("#edit_is_single").val();  //0 raw ; 1 curtain
          var customer_id_fk     = $("#edit_customer_id_fk").attr('data-fk');
          var pay_term           = $("#edit_pay_term").val();
          var invoice_date       = $("#edit_invoice_date").val();
          var price_profile_id   = $("#edit_price_profile_id").val();
          
          var invoice_note       = $("#edit_invoice_note").val();
          var total_invoice      = $("#edit_purchase_total").val();
          var total_paid         = $("#edit_total_paid").val();
          var payment_id         = $("#edit_total_paid").attr('data-payment_id');

          total_invoice          = total_invoice.replace('$','');
          total_invoice          = total_invoice.replace(/,/g,'');
          total_invoice          = parseFloat( total_invoice);
          
          // total_paid             = total_paid.replace('$','');
          // total_paid             = total_paid.replace(/,/g,'');
          // total_paid             = parseFloat( total_paid);

          if(payment_id == null || payment_id == '' || payment_id == undefined){
            payment_id = 0;
          }

          // other products

          var cnt                                       = $("#edit_total_rows_other").val();
          
         

          for(var i =0; i < cnt; i++){

              var productID       = $("#edit_other_id_fk_"+i).val();
              var sellID          = $("#edit_other_id_fk_"+i).attr('data-sell-id');
              var quantityField   = $("#edit_other_quantity_"+i).val();
              var unit_price      = $("#edit_buy_price_per_meter_other_"+i).val();
              var notes           = $("#edit_purchase_item_note_other_"+i).val();
              var row_total_price = $("#edit_total_item_cost_other_"+i).val();
              // var product_pay     = $("#edit_other_pay_"+i).val();
              // var product_pay_id  = $("#edit_other_pay_"+i).attr('data-payment-id-fk');
              var discount        = $("#edit_sell_discount_other_"+i).val();
              var discount_type   = $("#edit_sell_discount_other_"+i).attr('data-discount-type');
              var discount_actual = $("#edit_sell_discount_other_"+i).attr('data-discount-actual');

              
              if(productID != undefined && productID != null && productID != '' ){

                row_total_price     = row_total_price.replace('$','');
                row_total_price     = row_total_price.replace(/,/g,'');
                row_total_price     = parseFloat(row_total_price);


                check_quantity_other[k]         = Checks('edit_other_quantity_'+i,'No',1);
                check_price_other[k]            = Checks('edit_buy_price_per_meter_other_'+i,'No',0.00000001);
                

                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                notes_array[k]            = notes;
                unit_price_array[k]       = unit_price;
                discount_val_array[k]     = discount;
                discount_type_array[k]    = discount_type;
                discount_actual_array[k]  = discount_actual;
                row_total_price_array[k]  = row_total_price;
                // payments_array[k]         = product_pay;
                // payments_id_array[k]      = product_pay_id;
                sell_id_array[k]          = sellID;
                
                
                k++;
              }
          }

          
          console.log(sell_id_array);
          console.log(product_id_array);
          console.log(unit_price_array);
          console.log(row_total_price_array);
          

          

          var Check1      = Checks('edit_customer_id_fk');
          var Check2      = true; // Checks('edit_price_profile_id');
          
          var CheckPro    = true;
          var checkQty    = true;
          var checkrolls  = true;
          var checkprice  = true;
          
          var checkpriceOther  = true;
          var checkQtyOther  = true;

          for(m=0;m<check_products.length;m++){

            if(check_products[m]==false){
              CheckPro = false;
            }
            if(check_quantity[m]==false){
              checkQty = false;
            }

            if(check_price[m]==false){
              checkprice = false;
            }

          }

          for(m=0;m<check_quantity_other.length;m++){

            
            if(check_quantity_other[m]==false){
              checkQtyOther = false;
            }

            if(check_price_other[m]==false){
              checkpriceOther = false;
            }

            

          }

          


        if(Check1 && Check2 && CheckPro && checkQty && checkrolls && checkprice && checkpriceOther && checkQtyOther){
            $("#submit_edit_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_invoice.php",
                type:"POST",
                dataType: "JSON",
                data : {invoice_type              :invoice_type,
                        customer_id_fk            :customer_id_fk,
                        pay_term                  :pay_term,
                        invoice_date              :invoice_date,
                        price_profile_id          :price_profile_id,
                        invoice_note              :invoice_note,
                        invoice_id                :invoice_id,
                        is_single                 :is_single,
                        invoice_number            :invoice_number,
                        

                        
                        total_invoice             :total_invoice,
                        total_paid                :total_paid,
                        payment_id                :payment_id,

                        product_id                :product_id_array,
                        quantity                  :quantity_array,
                        sell_item_id              :sell_id_array,
                        sell_price                :unit_price_array,
                        discount                  :discount_val_array,
                        discount_type             :discount_type_array,
                        discount_actual           :discount_actual_array,
                      
                        sell_item_note            :notes_array,
                        row_price                 :row_total_price_array,
                        // row_payments              :payments_array,
                        // payments_id               :payments_id_array,
                        
                        type                      :'update'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                  


                   

                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    
                    $('#edit_form_cont').modal('toggle');
                    noty({
                                    width: 200,
                                    text: Translation(res.data),
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 2000,
                                    layout: 'topRight',
                                    callback: {
                                              onShow: function() {},
                                              afterShow: function() {},
                                              onClose: function() {},
                                              afterClose: function() {},
                                              onCloseClick: function() {},
                                            },
                              });

                    // i will reload the page to reset all fields
                    
               
                }else{
                    swal({
                        title: Translation("ﺧﻄﺄ"),
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                    //$("#add-form-cont").collapse('hide');
                }

                $("#submit_edit_btn").attr('disabled',false);
            })
            .fail(function(err) {
                 swal({
                    title: Translation("ﺧﻄﺄ"),
                    text: (err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                $("#submit_edit_btn").attr('disabled',false);
            })
            .always(function() {
                $("#submit_edit_btn").attr('disabled',false);
                
            });
        }else{
          noty({
                    width: 200,
                    text: Translation('اﻟﺮﺟﺎء اﻟﺘﺄﻛﺪ ﻣﻦ اﻟﻘﻴﻢ اﻟﻤﺪﺧﻠﺔ ﻭاﻳﻀﺎ اﻟﺘﺤﻘﻖ ﻣﻦ اﻥ اﻻﻃﻮاﻝ اﻟﻤﺤﺪﺩﺓ ﻣﺴﺎﻭﻳﺔ ﻟﻠﻌﺪﺩ'),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
        }


            
            
    });



   
    

  $('#add_other_form').submit(function(event) {
      event.preventDefault();
      
      var other_name                = $("#other_name").val();
      var other_description         = $("#other_description").val();
      var other_buy_price_per_unit  = $("#other_buy_price_per_unit").val();

      var check1 = true;
      var check2 = true;
      var check3 = true;

      var Check1    = Checks('other_name');
      var Check2    = Checks('other_buy_price_per_unit');

      if(Check1 && Check2){
          $("#submit_add_other_btn").attr('disabled',true);
          $.ajax({
              url: "models/crul_invoice.php",
              type:"POST",
              dataType: "JSON",
              data : {other_name:other_name,other_description:other_description,other_buy_price_per_unit:other_buy_price_per_unit
                      ,type:'add_other'}
          })
          .done(function(res) {
             
                if(res.is_success == true){

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

                  $("#add_other_modal").modal('toggle');
                  get_Others();
                  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_other_btn").attr('disabled',false);
          })
          .fail(function(err) {
               swal({
                  title: Translation("ﺧﻄﺄ"),
                  text: Translation(err),
                  confirmButtonColor: "#66BB6A",
                  type: "error"
              });
              $("#submit_add_other_btn").attr('disabled',false);
          })
          .always(function() {
              console.log("complete");
          });

      }else{
        noty({
                width: 200,
                text: Translation("اﻟﺮﺟﺎء اﺩﺧﺎﻝ اﻟﺤﻘﻮﻝ اﻟﻤﻄﻠﻮﺑﺔ"),
                type: 'error',
                dismissQueue: true,
                timeout: 3000,
                layout: 'topRight',
          });
      }



  });



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

    e.preventDefault();

    var customer_full_name    = $("#customer_full_name").val();
    var customer_email        = $("#customer_email").val();
    var customer_phone        = $("#customer_phone").val();
    var customer_phone2       = $("#customer_phone2").val();
    var customer_address      = $("#customer_address").val();
    var customer_job_title    = $("#customer_job_title").val();
    var customer_type         = $("#customer_type").val();

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

    var Check1    = Checks('customer_full_name');
    var Check3    = Checks('customer_phone');
    var Check5    = Checks('customer_type');
            


    if(Check1 && Check2 && Check3 && Check4 && Check5){
      $("#submit_add_cat_btn").attr('disabled',true);
        $.ajax({
            url: "models/crul_customer.php",
            type:"POST",
            dataType : "JSON",
            data : {customer_full_name:customer_full_name,
                    customer_email:customer_email,
                    customer_phone:customer_phone,
                    customer_phone2:customer_phone2,
                    customer_address:customer_address,
                    customer_job_title:customer_job_title,
                    customer_type:customer_type,
                    type:'create'}
        })
        .done(function(res) {
          //alert(res);
          if(res.is_success == false){
              noty({
                    width: 200,
                    text: Translation(res.data),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
                  });
              $('#add_new_category').modal('toggle');
              
          }else{
              get_Customer();
              // $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
              $('#add_new_category').modal('toggle');
              
              noty({
                              width: 200,
                              text: Translation(res.data),
                              type: 'success',
                              dismissQueue: true,
                              timeout: 3000,
                              layout: 'topRight',
                        });
          }
          $("#submit_add_cat_btn").attr('disabled',false);
        })
        .fail(function(err) {
           swal({
              title: Translation("خطأ"),
              text: (err),
              confirmButtonColor: "#66BB6A",
              type: "error"
            });
           $("#submit_add_cat_btn").attr('disabled',false);
        })
        .always(function() {
            console.log("complete");
        });
    }
    
  });


});







$(function() {
//var singleSelect = $('.datatable-column-search-inputs').DataTable();
    
  $(".touchspin-basic").TouchSpin({
        min: 1,
        max: 10000000,
        step: 1,
        buttondown_class: "btn btn-xs",
        buttonup_class: "btn btn-xs"
    });

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

  // Mini
    $('.select-size-xs').select2({
        containerCssClass: 'select-xs'
    });


   // Setting datatable defaults
    $.extend( $.fn.dataTable.defaults, {
        autoWidth: false,
        columnDefs: [{ 
            orderable: false,
            width: '100px',
            targets: [ 5 ]
        }],
        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_ip = getQueryVariable("ip");


    function invoce_filter_btn_label(){

       if(query_ip =='not' ){
         $("#inv_filter").html(Translation('ﻓﻠﺘﺮﺓ اﻟﻮﺻﻮﻻﺕ'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-teal-400 btn-labeled dropdown-toggle');

       }
       if(query_ip ==2){
         $("#inv_filter").html(Translation('ﻭاﺻﻞ'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-success-400 btn-labeled dropdown-toggle');

       }
       if(query_ip ==3){
         $("#inv_filter").html(Translation('ﻣﺴﺘﺮﺟﻊ'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-purple-400 btn-labeled dropdown-toggle');

       }
       if(query_ip ==4){
         $("#inv_filter").html(Translation('ﻋﺮﻭﺽ'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-violet-400 btn-labeled dropdown-toggle');

       }
       if(query_ip ==1 ){
         $("#inv_filter").html(Translation('ﻭاﺻﻞ ﺟﺰﺋﻴﺎ'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-orange-400 btn-labeled dropdown-toggle');

       }
       

       if(query_ip ==0 ){
         $("#inv_filter").html(Translation('ﻏﻴﺮ ﻭاﺻﻞ'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-danger-400 btn-labeled dropdown-toggle');

       }

     }


   var table = $('.datatable-column-search-inputs').DataTable({
        
        buttons: {            
            buttons: [
                {
                    extend: 'copyHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: [ 0, ':visible' ]
                    }
                },
                {
                    extend: 'excelHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'pdfHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'print',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'colvis',
                    text: '<i class="icon-three-bars"></i> <span class="caret"></span>',
                    className: 'btn bg-blue btn-icon'
                }
                
            ]
        },
        lengthMenu: [
            [  10, 25, 50, 100 ],
            [  '10', '25', '50', '100' ]
        ],
        "processing": true,
        "serverSide": true,
        "ajax": {
        "url" : "models/crul_invoice.php",
        "data": function(d){
          d.type = "load";
          if(query_ip !='not'){
            d.ip =query_ip ;
          }
        }
        },
        drawCallback: function() {
                  $('[data-popup=tooltip]').tooltip();
                  $('[data-popup=popover-custom]').popover({
                    template: '<div class="popover  border-teal-400"><div class="arrow"></div><h3 class="popover-title bg-teal-400"></h3><div class="popover-content"></div></div>'
                  });

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

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

                                         
                                        <li class="dropdown">
                                          <a  class="dropdown-toggle" data-toggle="dropdown"  data-original-title1='`+Translation('تفاصيل دفوعات الوصل')+` '>
                                            <i class="icon-menu9 icon-2x"></i>
                                          </a>

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


                                            <li class='text-primary-600'>
                                                <a  class='text-success-400' onclick="show_invoice(`+row[0]+`,null,'Details')" data-popup1='tooltip' data-original-title=''>
                                                    <i class='icon-stack-text'></i>`+Translation('ﻋﺮﺽ ﻭﺻﻞ اﻟﺒﻴﻊ ﻣﻊ اﻟﺘﻔﺎﺻﻴﻞ')+`
                                                </a>
                                            </li>

                                            <li class='text-primary-600'>
                                                <a  class='text-info-400' onclick="show_invoice(`+row[0]+`,'Print','Details')" data-popup=1'tooltip' data-original-title=''>
                                                    <i class='icon-printer2'></i>`+Translation('ﻃﺒﺎﻋﺔ اﻟﻮﺻﻞ ﻣﻊ اﻟﺘﻔﺎﺻﻴﻞ')+`
                                                </a>
                                            </li>

                                            <li class='text-primary-600'>
                                                <a  class='text-orange-400' onclick="show_invoice(`+row[0]+`)" data-popup1='tooltip' data-original-title=''>
                                                    <i class='icon-calculator'></i>`+Translation('ﻋﺮﺽ ﻭﺻﻞ اﻟﺒﻴﻊ ﺑﺪﻭﻥ اﻟﺘﻔﺎﺻﻴﻞ')+`
                                                </a>
                                            </li>

                                            <li class='text-primary-600'>
                                                <a  class='text-pink-400' onclick="show_invoice(`+row[0]+`,'Print')" data-popup1='tooltip' data-original-title=''>
                                                    <i class='icon-printer4'></i>`+Translation('ﻃﺒﺎﻋﺔ اﻟﻮﺻﻞ ﺑﺪﻭﻥ اﻟﺘﻔﺎﺻﻴﻞ')+`
                                                </a>
                                            </li>
                                            
                                            <li class='text-primary-600'>
                                                <a  class='text-primary-400' onclick="edit_items(`+row[0]+`)" data-popup1='tooltip' data-original-title=''>
                                                    <i class='icon-pencil7'></i>`+Translation('ﺗﻌﺪﻳﻞ')+`
                                                </a>
                                            </li>

                                            <li class='text-danger-600'>
                                                <a  class='text-danger-400' onclick="delete_items(`+row[0]+`)" data-popup1='tooltip' data-original-title=''>
                                                    <i class='icon-trash'></i>`+Translation('ﺣﺬﻑ')+`
                                                </a>
                                            </li>
                                            


                                          </ul>
                                        </li>
                                      </ul>`;
                        }
          },


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


                        // return  `<a onclick="show_invoice(`+row[0]+`)"  data-popup='tooltip' data-original-title='Show Invoice Details'>`+data+`</a>`;
                        return  `<a onclick="load_account_statment('',`+row[0]+`)"  data-popup='tooltip' data-original-title='`+Translation('ﻋﺮﺽ ﺟﻤﻴﻊ ﻛﺸﻮﻓﺎﺕ اﻟﺤﺴﺎﺏ ﻟﻬﺬا اﻟﻮﺻﻞ')+`'>`+data+`</a>`;


               },
               "targets": 1
            },

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


                        return  `<a onclick="load_account_statment(`+row[11]+`)"  data-popup='tooltip' data-original-title='`+Translation('ﻋﺮﺽ ﺟﻤﻴﻊ ﻛﺸﻮﻓﺎﺕ اﻟﺤﺴﺎﺏ ﻟﻬﺬا اﻟﺰﺑﻮﻥ')+`'>`+data+`</a>`;


               },
               "targets": 3
            },

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

            //         return currency_format_display(data);
            //     },
            //     "targets": 4
            // },

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

                    return currency_format_display(data);
                },
                "targets": 5
            },

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

                    return currency_format_display(data);
                },
                "targets": 6
            },

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

                    return currency_format_display(data);
                },
                "targets": 7
            },
            

            {
                "render": function(data, type, row){
                   if(row[8] ==2 ){
                     status=  `<span class="label label-success btn-block ">`+Translation('ﻭاﺻﻞ')+`</span>`;
                   }else if(row[8] ==3){
                     status = '<span class="label bg-purple  btn-block ">'+Translation('ﻣﺮﺟﻊ')+'  </span>';
                   }else if(row[8] ==4){
                     status = '<span class="label bg-violet  btn-block ">'+Translation('ﻋﺮﺽ')+'  </span>';
                   }else{

                        // datepart: 'y', 'm', 'w', 'd', 'h', 'n', 's'

                        //Set the two dates
                        var y2k  = new Date(row[2]);
                        var today= new Date();
                        var days = Date.dateDiff('d', y2k, today); //displays 625
                        //alert(days)
                         if(days >= row[10]){
                             var afterTermDays = days - row[10];
                             if(row[8]==1){
                               status = '<span class="label bg-orange  btn-block btn-xs">'+Translation('ﻭاﺻﻞ ﺟﺰﺋﻴﺎ')+'  ('+afterTermDays+' DAYS OUT)</span>';
                             }else{
                               status = '<span class="label label-danger btn-block btn-xs">'+Translation('ﻏﻴﺮ ﻭاﺻﻞ')+'  ('+afterTermDays+' DAYS OUT)</span>';
                             }

                         }else{
                             var remainedDays = row[10]-days;
                             if(row[8]==1){
                               status = '<span class="label label-info  btn-block btn-xs"> '+Translation('ﻭاﺻﻞ ﺟﺰﺋﻴﺎ')+'  ('+remainedDays+' DAYS REM)</span>';
                             }else{
                               status = '<span class="label label-primary btn-block btn-xs">'+Translation('ﻏﻴﺮ ﻭاﺻﻞ')+'  ('+remainedDays+' DAYS REM)</span>';
                             }

                         }
                   }
                   return  status;
                },
                "targets": 8
            }
            

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


            if(   aData[5] == 1 ){ // outcome type
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('alpha-info');
                });
            }
        },
        "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">
                          <li><a href="index.php?p=invoice"><i class="icon-close2 text-teal"></i>`+Translation('اﺯاﻟﺔ اﻟﻔﻠﺘﺮ')+`  </a></li>
                          <li class="divider"></li>
                          <li><a href="index.php?p=invoice&ip=2"><i class="icon-coins text-success"></i>`+Translation('اﻟﻮاﺻﻞ')+` </a></li>
                          <li class="divider"></li>
                          <li><a href="index.php?p=invoice&ip=1"><i class="icon-bell-check text-info"></i>`+Translation('ﻭاﺻﻞ ﺟﺰﺋﻴﺎ')+`  </a></li>
                          <li class="divider"></li>
                          <li><a href="index.php?p=invoice&ip=0"><i class="icon-alarm-check text-danger"></i>`+Translation('ﻏﻴﺮ ﻭاﺻﻞ')+` </a></li>
                          <li class="divider"></li>
                          <li><a href="index.php?p=invoice&ip=4"><i class=" icon-task text-violet"></i>`+Translation('ﻋﺮﻭﺽ')+`  </a></li>
                          <li><a href="index.php?p=invoice&ip=3"><i class="icon-loop text-purple"></i>`+Translation('ﻣﺴﺘﺮﺟﻊ')+`  </a></li>

                        </ul>
                      </div>`);
 
            invoce_filter_btn_label();

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

            });
            escape_notes();
        }
    });

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


});



