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

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

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

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

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

                          .col-sm-12 {
                            width: 100%;
                          }
                          .col-sm-6 {
                            width: 50%;
                          }

                          .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 HTML_Sticker = `
                        <!DOCTYPE html>
                        <html lang="ar" dir="rtl">
                          <head>
                            <meta charset="utf-8">
                            <meta http-equiv="X-UA-Compatible" content="IE=edge">
                            <style>

                              @media print and (width: 10cm) and (height: 5cm) {
                                 @page {
                                  margin: .3cm;
                                 }
                              }
                              .print {  
                                  -webkit-print-color-adjust: exact;
                                  }
                                  
                              @page {
                                  size:  1.968in 3.937in landscape;
                                  }

                                  .page-break  {
                                                  clear: left;
                                                  display:block;
                                                  page-break-after:always;
                                              }
                            </style>


                          </head>

                          <body lang=ar style="font-family:  Times, serif !important; font-size:18px;">

                              <div class=WordSection1>

                                

                                <div align=left style="align:left !important;">
                        `;
    

    function edit_items(itemid){

        var footers           =  ``;
        var attach            =  ``;
        var attach_other      =  ``;
        var total_rows_both   =0;
        var resp;

        $.ajax({
                url : 'models/crul_offer_curt.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;
                  // total_rows          = total_rows_both;
                  $("#edit_total_rows").val(total_rows_both);
                  $("#edit_total_rows_other").val(response.invoice[0].total_other_cnt);
                  

                  $("#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 id="edit_footer_sum" 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></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></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></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></th>
                                  
                                  <th><i  class="icon-cash "></i></th>
                                </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 = (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].total_area > 0){
                        total_row_price = +(round(response.invoice[i].total_area,2) * response.invoice[i].item_sell_price_per_meter) + +(response.invoice[i].total_decor_width * response.invoice[i].decorate_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);
                      }
                    }

                    total_row_price = currency_format_display(round(total_row_price,2));


                    // 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){


                      // we should Check for total area if greater than 0 it mean its curtain and we should show the width else we show just height and collpase td
                          
                      if(response.invoice[i].total_area > 0){

                        // display sell item details
                        var attach_height ='';
                        var attach_width ='';
                        // i will show just one height and width because we have quantity
                        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){
                            attach_height1 =  ` <input types="text" id="height_`+i+`_`+j+`" data-detail-id="`+response.details[j].sell_item_detail_id+`" data-purchase-id="`+response.details[j].purchase_item_detail_id_fk+`" class="label bg-success-400 col-sm-6" value="`+response.details[j].sell_item_detail_height+`" readonly> `;
                            attach_width1  =  ` <input types="text" id="width_`+i+`_`+j+`" data-detail-id="`+response.details[j].sell_item_detail_id+`" data-purchase-id="`+response.details[j].purchase_item_detail_id_fk+`" class="label bg-success-400 col-sm-6" value="`+response.details[j].sell_item_detail_width+`" readonly> `;
                            
                            attach_height =  response.details[j].sell_item_detail_height;
                            attach_width  =  response.details[j].sell_item_detail_width;
                          
                          }
                        }


                        attach = attach + `
                                            <tr  id="edit_item_row_`+i+`" >
                                              <td width="3%" id="edit_num_`+i+`">`+(+i + +1)+`</td>
                                              <td width="8%">
                                                <!--<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="رمز المادة" readonly > -->
                                                <select class="form-control multi_lang stop_enter" name="edit_product_id_fk_`+i+`" id="edit_product_id_fk_`+i+`" data-width="100%" placeholder="رمز المادة" onchange="edit_load_products(this.value,this.id);" data-live-search="true">

                                                </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="8%" id="edit_forign_id_`+i+`">`+response.invoice[i].turkish_code+`</td>

                                              <td width="6%">
                                                <input type="number" value="`+response.invoice[i].sell_item_quantity+`" id="edit_purchase_quantity_`+i+`" name="edit_purchase_quantity_`+i+`"  class="form-control text-center" placeholder="`+Translation('الكمية')+`"   onchange="edit_compute_area(this.value,this.id,`+i+`);">
                                              </td>

                                              <td width="6%" id="edit_products_width_`+i+`">
                                                <input type="text" value="`+attach_width+`" id="edit_curtain_width_`+i+`" name="edit_curtain_width_`+i+`"  class="form-control text-center" placeholder="`+Translation('العرض')+`"  onchange="edit_compute_area(this.value,this.id,`+i+`);">

                                              </td>
                                              
                                              <td width="6%" id="edit_products_height_`+i+`">
                                                <input type="text" value="`+attach_height+`" id="edit_curtain_height_`+i+`" name="edit_curtain_height_`+i+`"  class="form-control text-center" placeholder="`+Translation('الارتفاع')+`"  onchange="edit_compute_area(this.value,this.id,`+i+`);">

                                              </td>
                                              

                                              <td width="7%" >
                                                <input value="`+round(response.invoice[i].total_area,2)+`" id="edit_total_length_`+i+`" name="edit_total_length_`+i+`" type="text" class="form-control text-center" readonly >
                                              </td>

                                             <!-- <td width="6%">
                                                <input id="edit_last_sell_price_`+i+`" name="edit_last_sell_price_`+i+`" type="text" class="form-control text-center" placeholder="`+Translation('اخر سعر بيع')+`" readonly >
                                              </td> -->

                                              <td width="7%">
                                                <input value="`+response.invoice[i].item_sell_price_per_meter+`" id="edit_buy_price_per_meter_`+i+`" name="edit_buy_price_per_meter_`+i+`" type="text" class="form-control text-center" placeholder="`+Translation('سعر بيع المتر')+`" onchange="edit_calc_total_item_cost(this.id,`+i+`);" >
                                              </td>

                                            <!--  <td width="6%">
                                                <input id="edit_last_sell_price_decor_`+i+`" name="edit_last_sell_price_decor_`+i+`" type="text" class="form-control text-center" placeholder="`+Translation('اخر سعر بيع ديكور')+`" readonly >
                                              </td> -->

                                              <td width="7%">
                                                <input value="`+response.invoice[i].decorate_price_per_meter+`" id="edit_buy_price_per_meter_decor_`+i+`" name="edit_buy_price_per_meter_decor_`+i+`" type="text" class="form-control text-center" placeholder="`+Translation('سعر بيع متر الديكور')+`" onchange="edit_calc_total_item_cost(this.id,`+i+`);" >
                                              </td>

                                              <td width="7%">
                                                  <input id="edit_sell_discount_`+i+`" name="edit_sell_discount_`+i+`" value="`+disss+`" 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%">
                                                <textarea type="text" id="edit_purchase_item_note_`+i+`" name="edit_purchase_item_note_`+i+`"  class="form-control multi_lang" placeholder="ملاحظات" >`+response.invoice[i].sell_item_notes+`</textarea>
                                              </td>
                                              <td width="9%" >
                                                <input value="`+response.invoice[i].sell_item_delivery_name+`" id="edit_sell_item_delivery_name_`+i+`" name="edit_sell_item_delivery_name_`+i+`" type="text" class="form-control text-center" placeholder="`+Translation('المستلم')+`">
                                              </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="2%">
                                                <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 btn_remove_item" id="edit_row_`+i+`" onclick="remove_rows(`+i+`)">
                                                  <i  class="icon-subtract text-danger-600"></i>
                                                </button>
                                              </td>
                                            </tr>

                                             `;

                      }else{


                        // 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){
                            Det = Det + ` <input types="text" id="roll_`+i+`_`+j+`" 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+`" >
                                              <td width="3%" id="edit_num_`+i+`">`+(+i + +1)+`</td>
                                              <td width="8%">
                                                <!--<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="رمز المادة" readonly > -->
                                                <!--<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="رمز المادة" readonly > -->
                                                <select class="form-control multi_lang stop_enter" name="edit_product_id_fk_`+i+`" id="edit_product_id_fk_`+i+`" data-width="100%" placeholder="رمز المادة" onchange="edit_load_products(this.value,this.id);" data-live-search="true">

                                                </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="8%" id="edit_forign_id_`+i+`">`+response.invoice[i].turkish_code+`</td>

                                              <td width="6%">
                                                <input type="number" value="`+response.invoice[i].sell_item_quantity+`" id="edit_purchase_quantity_`+i+`" name="edit_purchase_quantity_`+i+`"  class="form-control text-center" placeholder="`+Translation('الكمية')+`" readonly  >
                                              </td>

                                              <td width="6%" colspan=2 id="edit_products_width_`+i+`">
                                                `+Det+`
                                              </td>
                                             

                                              <td width="7%" >
                                                <input value="`+response.invoice[i].total_length+`" id="edit_total_length_`+i+`" name="edit_total_length_`+i+`" type="text" class="form-control text-center" readonly >
                                              </td>

                                              <td width="6%">
                                                <input id="edit_last_sell_price_`+i+`" name="edit_last_sell_price_`+i+`" type="text" class="form-control text-center" placeholder="`+Translation('اخر سعر بيع')+`" readonly >
                                              </td>

                                              <td width="7%">
                                                <input value="`+response.invoice[i].item_sell_price_per_meter+`" id="edit_buy_price_per_meter_`+i+`" name="edit_buy_price_per_meter_`+i+`" type="text" class="form-control text-center" placeholder="`+Translation('سعر بيع المتر')+`" onchange="edit_calc_total_item_cost(this.id,`+i+`);" >
                                              </td>

                                              <td width="6%">
                                                <input id="edit_last_sell_price_decor_`+i+`" name="edit_last_sell_price_decor_`+i+`" type="text" class="form-control text-center" placeholder="`+Translation('اخر سعر بيع ديكور')+`" readonly >
                                              </td>

                                              <td width="7%">
                                                <input value="" id="edit_buy_price_per_meter_decor_`+i+`" name="edit_buy_price_per_meter_decor_`+i+`" type="text" class="form-control text-center" placeholder="`+Translation('سعر بيع متر الديكور')+`" readonly >
                                              </td>

                                              <td width="7%">
                                                  <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%">
                                                <textarea type="text" id="edit_purchase_item_note_`+i+`" name="edit_purchase_item_note_`+i+`" class="form-control multi_lang" placeholder="ملاحظات" >`+response.invoice[i].sell_item_notes+`</textarea>
                                              </td>
                                              <td width="9%" >
                                                <input value="`+response.invoice[i].sell_item_delivery_name+`" id="edit_sell_item_delivery_name_`+i+`" name="edit_sell_item_delivery_name_`+i+`" type="text" class="form-control text-center" placeholder="`+Translation('المستلم')+`">
                                              </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="2%">
                                                
                                              </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>-->
                                                          <select class="form-control multi_lang stop_enter" data-live-search="true" name="edit_other_id_fk_`+i+`" id="edit_other_id_fk_`+i+`" data-width="100%" placeholder="`+Translation('مواد اخرى')+`" >
                                                          </select>
                                                        </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" colspan="2"></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%" colspan="2">
                                                          <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+`" class="form-control multi_lang" placeholder="ملاحظات" >`+response.invoice[i].sell_item_notes+`</textarea>
                                                        </td>
                                                        <td width="9%" >
                                                          <input id="edit_sell_item_delivery_name_other_`+i+`" name="edit_sell_item_delivery_name_other_`+i+`" value="`+response.invoice[i].sell_item_delivery_name+`" type="text"  class="form-control text-center" placeholder="المستلم" >
                                                        
                                                        </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 >
                                                          <button class="btn btn-link edit_add_others_btn" onclick="Add_Other_Rows()">
                                                            <i  class="icon-database-add text-teal"></i>
                                                          </button>
                                                          <button class="btn btn-link btn-xs edit_btn_other_remove_item" id="edit_row_other_`+i+`" onclick="remove_other_rows(`+i+`)">
                                                            <i  class="icon-subtract text-danger-600"></i>
                                                          </button>
                                                        </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);
                      }


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


                      
                      // for(var i=0 ; i < total_rows_both;i++){ // to load product in select
                      //  $("#edit_product_id_fk_"+i).val(resp.invoice[i].product_id_fk).selectpicker('refresh')
                      //   alert($("#edit_product_id_fk_"+i).val())
                      // }
                }

          }); // submit ajax



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

    function delete_items(itemid) {
       
          swal({
              title: Translation("هل انت متأكد؟!"),
              text: Translation("سيتم مسح وصل البيع وجميع الدفعات المرتبطه به من حساب الزبون!! هل انت متأكد؟!"),
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "#EF5350",
              confirmButtonText: Translation("موافق: امسح!"),
              cancelButtonText: Translation("الغاء الامر"),
              closeOnConfirm: false,
              closeOnCancel: true
          },
          function(isConfirm){
              if (isConfirm) {
                $.ajax({
                  url: "models/crul_offer_curt.php",
                  type:"POST",
                  dataType: "JSON",
                  data: {"type":"delete","obj_id":itemid} ,
                  complete:function(){
                    
                  },
                  beforeSend:function(){
                 
              },
                  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 reject_offer(itemid) {
       
          swal({
              title: Translation("هل انت متأكد؟!"),
              text: Translation("سيتم تغيير حالة العرض الى عرض مرفوض ؟!"),
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "#EF5350",
              confirmButtonText: Translation("موافق: !"),
              cancelButtonText: Translation("الغاء الامر"),
              closeOnConfirm: false,
              closeOnCancel: true
          },
          function(isConfirm){
              if (isConfirm) {
                $.ajax({
                  url: "models/crul_offer_curt.php",
                  type:"POST",
                  dataType: "JSON",
                  data: {"type":"reject_offer","obj_id":itemid} ,
                  complete:function(){
                    
                  },
                  beforeSend:function(){
                 
              },
                  success: function(res) {
                    if(res.is_success == true){
                     
                      swal({
                                  title: "تمت العملية",
                                  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 accept_offer(itemid) {
       
          swal({
              title: Translation("هل انت متأكد؟!"),
              text: Translation("بمجرد الموافقه سيتم تحويله الى وصل بيع وسوف لن تستطيع اجراء اية عملية على وصل العرض ولحذفه او الغاءه يجب ان تقوم بحذفه من جدول المبيعات!"),
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "#EF5350",
              confirmButtonText: Translation("موافق: !"),
              cancelButtonText: Translation("الغاء الامر"),
              closeOnConfirm: false,
              closeOnCancel: true
          },
          function(isConfirm){
              if (isConfirm) {
                $.ajax({
                  url: "models/crul_offer_curt.php",
                  type:"POST",
                  dataType: "JSON",
                  data: {"type":"accept_offer","obj_id":itemid} ,
                  complete:function(){
                    
                  },
                  beforeSend:function(){
                 
              },
                  success: function(res) {
                    if(res.is_success == true){
                     
                      swal({
                                  title: "تمت العملية",
                                  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: "Please Enter the Required Field with minimum length of "+ min + " and maximum length " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min !=null && max ==null){
                  if(name ==''  || name.length < min ){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

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

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

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

                    noty({
                            width: 200,
                            text: "حقل " + 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(types == 'No'){  // it mean numbers

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

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

                    noty({
                            width: 200,
                            text: "Please Enter Numeric Value Greater than "+ 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: "الرجاء قم بادخال قيمة عددية اكبر او تساوي "+ min + " في حقل " + 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: "Please Enter Numeric Value Less than " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else{

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

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

              }

        }
    }

    
    function 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_offer_curt.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=57 style='width:42.75pt;' class="table2_td">
                                    
                                   `+Translation('العرض')+` 
                                    </td>
                                    <td width=57 style='width:42.75pt;' 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=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>`;
                     
                      var all_area = 0;
                      // 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;

                        all_area = +all_area + +(response.invoice[i].total_area);

                        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{
                          if(response.invoice[i].total_area > 0){
                            total_row_price = +( round(response.invoice[i].total_area,2)  * response.invoice[i].item_sell_price_per_meter) + +(response.invoice[i].total_decor_width * response.invoice[i].decorate_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);
                          }
                          
                        }

                        total_row_price = currency_format_display(round(total_row_price,2));


                        if(response.invoice[i].product_id_fk > 0){
  
                          // we should Check for total area if greater than 0 it mean its curtain and we should show the width else we show just height and collpase td
                          
                          if(response.invoice[i].total_area > 0){

                            // display sell item details
                            var attach_height ='';
                            var attach_width ='';
                            // i will show just one height and width because we have quantity
                            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){
                                
                                // attach_height =  ` <input types="text"  class="label bg-success-400 col-sm-6" value="`+response.details[j].sell_item_detail_height+`" readonly> `;
                                // attach_width  =  ` <input types="text"  class="label bg-success-400 col-sm-6" value="`+response.details[j].sell_item_detail_width+`" readonly> `;
                                
                                attach_height =  ` <span   class="  col-sm-4" >`+response.details[j].sell_item_detail_height+`</span>`;

                                attach_width  =  ` <span   class="  col-sm-4" >`+response.details[j].sell_item_detail_width+`</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=57 style='width:42.75pt; font-family:  Times, serif;'>
                                                      <span  id="inv_details">
                                                      `+attach_width+`
                                                      </span>
                                                    </td>
                                                    <td width=57 style='width:42.75pt; font-family:  Times, serif;'>
                                                      <span  id="inv_details">
                                                      `+attach_height+`
                                                      </span>
                                                    </td>
                                                
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+round(response.invoice[i].total_area,2)+` م<sup>2</sup> </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=73 style='width:54.9pt;'>
                                                      <span  id="inv_unit_price"> `+currency_format_display(response.invoice[i].decorate_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{ // raw products

                            // display sell item details
                        
                            var Det = '';
                            if(detail_show != null){

                              // display sell item details
                              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 + ` <span   class="  col-sm-4" >`+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"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td colspan="2" 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=73 style='width:54.9pt;'>
                                                      <span  id="inv_unit_price"> `+currency_format_display(response.invoice[i].decorate_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 colspan="2" 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=73 style='width:54.9pt;'>
                                                      <span  id="inv_unit_price">  </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>
                                            setTimeout(function() {
                                              window.print()
                                            }, 2000)
                                        </script>
                                        `;
                      }else{
                        print_attach = "";
                      }


                      all_area = round(all_area,2);


                      footers =`<tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=439 colspan=9  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=79 style='width:58.95pt;border:solid #984806 1.0pt;border-right:
                                  none;padding:0pt 0in 0pt 0in;height:.1in;text-align: center;'>
                                  `+currency_format_display(response.invoice[0].total_discount)+`
                                  </td>
                                  
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=9 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'>
                                   `+(all_area)+` م<sup>2</sup>
                                  </td>
                                 </tr>

                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=9 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=10 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=8 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=8 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=8 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=10  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=9  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 show_sticker(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_offer_curt.php',
                type : 'POST',
                data : {type:'show_sticker', id : itm},
                dataType : 'json',
                success : function(response) {
                    console.log(response)
                    
                       
                       var tot = response.sticker.length;
                     
                      // show all stickers                       
                      for(var i=0 ; i < response.sticker.length;i++){

                          attach = attach + `
                                            <table class=MsoNormalTable dir=rtl border=0 cellspacing=0 cellpadding=0 width=353 style='width:260.8pt;border-collapse:collapse; font-weight: bolder;'>
                                               <tr style='height:19.9pt; text-align: center;'>
                                                  <td width=245 colspan=3 style='width:183.75pt;padding:0in .4pt 0in .4pt;
                                                  height:19.9pt'>
                                                  `+COMPANY_NAME+`
                                                  </td>
                                                  <td width=108 style='width:81.05pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+response.sticker[i].invoice_date+`
                                                  </td>
                                               </tr>
                                               <tr style='height:19.9pt'>
                                                  <td width=95 style='width:71.25pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+Translation('الزبون')+` :
                                                  </td>
                                                  <td width=258 colspan=3 style='width:193.55pt;padding:0in .4pt 0in .4pt;
                                                  height:19.9pt'>
                                                  `+response.sticker[i].customer_full_name+`
                                                  </td>
                                               </tr>
                                               <tr style='height:19.9pt'>
                                                  <td width=95 style='width:71.25pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+Translation('الرمز')+` :
                                                  </td>
                                                  <td width=258 colspan=3 style='width:193.55pt;padding:0in .4pt 0in .4pt;
                                                  height:19.9pt'>
                                                  `+response.sticker[i].product_name+`
                                                  </td>
                                               </tr>
                                               <tr style='height:19.9pt'>
                                                  <td width=95 style='width:71.25pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+Translation('العرض (م)')+` :
                                                  </td>
                                                  <td width=67 style='width:50.5pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+response.sticker[i].sell_item_detail_width+`
                                                  </td>
                                                  <td width=108 style='width:81.05pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+Translation('الارتفاع (م)')+` :
                                                  </td>
                                                  <td width=83 style='width:62.0pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+response.sticker[i].sell_item_detail_height+`
                                                  </td>
                                               </tr>
                                               <tr style='height:19.9pt'>
                                                  <td width=95 style='width:71.25pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+Translation('ملاحظات')+` :
                                                  </td>
                                                  <td width=258 colspan=3 style='width:193.55pt;padding:0in .4pt 0in .4pt;
                                                  height:19.9pt'>
                                                  `+response.sticker[i].sell_item_notes+`
                                                  </td>
                                               </tr>
                                               <tr style='height:19.9pt'>
                                                  <td width=95 style='width:71.25pt;padding:0in .4pt 0in .4pt;height:19.9pt'>
                                                  `+Translation('المستلم')+` :
                                                  </td>
                                                  <td width=258 colspan=3 style='width:193.55pt;padding:0in .4pt 0in .4pt;
                                                  height:19.9pt'>
                                                  `+response.sticker[i].sell_item_delivery_name+`
                                                  <span style="float:left;">`+(+i+1)+`/`+tot+` </span>
                                                  </td>
                                               </tr>
                                               
                                            </table>
                                            <div class="page-break"></div>
                                            <br>
                                                  `;
                      
                       
                      } // for i

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

                      footers =`        </div>

                                      </div>

                                  </body>

                                </html>

                                `+print_attach+`
                               `;

                      

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

                      HTML_VIEW_PAY = HTML_Sticker + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                      
                        $("#sticker_show").html(HTML_VIEW_PAY);
                        $("#sticker_inv_numb").val(itm);

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

          }); // submit ajax


    }

   


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

      }
    }

  


    $('#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('');
          // we should return the old remaind too
          $("#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 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(){

            var cust_typ  = getQueryVariable("typ");

            $.ajax({
                  url : 'models/crul_customer.php',
                  type : 'POST',
                  data : {type:'get_Customer',cust_typ:cust_typ},
                  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 =[] ;

  

    function get_Others(cnt, edit=null){

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

                        $("#edit_other_id_fk_"+cnt).html(attach);
                        $('#edit_other_id_fk_'+cnt).selectpicker('refresh');
                        //$("#edit_product_id").html(edit_attach);

                        if(edit !=null && edit !=''){
                          $("#edit_other_id_fk_"+cnt).val(edit).selectpicker('refresh');
                        }
                  },
                  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',

                    });
              return false;
          }

          $.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() {
                     // 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('');
                          $("#last_sell_price_decor_"+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]); 
                          $("#last_sell_price_decor_"+row_num).val(response[0][1]); 
                          
                        }
                  },
                  complete: function() {

                  }

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

    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_height_"+row_num).html('');
        $("#products_height_"+row_num).html('<input type="text" id="curtain_height_'+row_num+'" name="curtain_height_'+row_num+'"  class="form-control text-center multi_lang" placeholder="'+Translation('الارتفاع')+'"  onchange="compute_area(this.value,this.id,'+row_num+');">');

        $("#products_width_"+row_num).html('');
        $("#products_width_"+row_num).html('<input type="text" id="curtain_width_'+row_num+'" name="curtain_width_'+row_num+'"  class="form-control text-center multi_lang" placeholder="'+Translation('العرض')+'"  onchange="compute_area(this.value,this.id,'+row_num+');">');


        $("#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_height_"+row_num).html('');
        $("#edit_products_height_"+row_num).html('<input type="text" id="edit_curtain_height_'+row_num+'" name="edit_curtain_height_'+row_num+'"  class="form-control text-center multi_lang" placeholder="'+Translation('الارتفاع')+'"  onchange="edit_compute_area(this.value,this.id,'+row_num+');">');

        $("#edit_products_width_"+row_num).html('');
        $("#edit_products_width_"+row_num).html('<input type="text" id="edit_curtain_width_'+row_num+'" name="edit_curtain_width_'+row_num+'"  class="form-control text-center multi_lang" placeholder="'+Translation('العرض')+'"  onchange="edit_compute_area(this.value,this.id,'+row_num+');">');


        $("#edit_total_length_"+row_num).val('');
        
        add_qty_input_fields(qty,"edit_purchase_quantity_"+row_num);

    }

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


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

            }); // submit ajax

          

         

    }


    // 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 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 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 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][6]==0){ // is have curtain 0: havnt we should show him to select product from purchase; 1: have curtain and we wont show him any thing because he will write the height and width of curtain
                     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">`+Translation('مواد كاملة')+`</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">
                                                            <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="number" 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');

                     }
                    }else{ // is have curtain
                      calc_total_item_cost(id,row_num);
                      compute_area('','',row_num);
                    }    
                  },
                  complete: function() {
                    
                  }

            }); // submit ajax
          }
            // end checking for purchasing or not


            

      }
      

    }

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

      

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

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

          var p_id = $("#edit_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][6]==0){ // is have curtain 0: havnt we should show him to select product from purchase; 1: have curtain and we wont show him any thing because he will write the height and width of curtain
                     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',p_id:p_id},
                                dataType : 'json',
                                success : function(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="#complete_roll`+j+`" data-toggle="tab">`+Translation('مواد كاملة')+`</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">
                                                            <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="number" 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

                                  

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

                        $('#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="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>`;
                        }

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

                     }
                    }else{ // is have curtain
                      edit_calc_total_item_cost(id,row_num);
                      edit_compute_area('','',row_num);
                    }    
                  },
                  complete: function() {
                    
                  }

            }); // submit ajax
          }
            // end checking for purchasing or not


            

      }
      

    }


    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 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();
          
          // check if this product have curtain so we should include the decor cost also
          var sell_decor_price  = $("#buy_price_per_meter_decor_"+row_num).val();
          var height            = $("#curtain_height_"+row_num).val();
          var width             = $("#curtain_width_"+row_num).val();
          var qanty             = $("#purchase_quantity_"+row_num).val();

          
          
          if(!isNaN(height) && !isNaN(width) && height !='' && height !=null && height !=undefined && height >0 && width !='' && width !=null && width !=undefined && width >0){ // that mean its curtain because it have height and width, also we should mutliple it with qanity
            // alert('height='+height + ' width='+width)
            if(!isNaN(sell_decor_price) ){
              total_item_cost = (total_item_cost  + (sell_decor_price * width * qanty)) ;
            }
          }

          // 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();
          
          // check if this product have curtain so we should include the decor cost also
          var sell_decor_price  = $("#edit_buy_price_per_meter_decor_"+row_num).val();
          var height            = $("#edit_curtain_height_"+row_num).val();
          var width             = $("#edit_curtain_width_"+row_num).val();
          var qanty             = $("#edit_purchase_quantity_"+row_num).val();

          
          
          if(!isNaN(height) && !isNaN(width) && height !='' && height !=null && height !=undefined && height >0 && width !='' && width !=null && width !=undefined && width >0){ // that mean its curtain because it have height and width, also we should mutliple it with qanity
            // alert('height='+height + ' width='+width)
            if(!isNaN(sell_decor_price) ){
              total_item_cost = (total_item_cost  + (sell_decor_price * width * qanty)) ;
            }
          }

          // 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_1").val() * $("#buy_price_per_meter_other").val();
          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();
          // var discount = $("#sell_discount_other").val();
          if (discount.indexOf('%') > -1)
          {
            $("#sell_discount_other_"+row_num).attr('data-discount-type','0'); // percentage
            // $("#sell_discount_other").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
            // $("#sell_discount_other").attr('data-discount-type','1'); // absolute
            total_item_cost = total_item_cost - discount;
            actual_disc = discount;
          }

          // $("#sell_discount_other").attr('data-discount-actual',actual_disc); // absolute 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));  
          // $("#total_item_cost_other").val(currency_format_display(total_item_cost));  
          

          calc_total_purchase_price();

    }

    function edit_calc_other_cost(row_num){

          // var total_item_cost = $("#other_quantity_1").val() * $("#buy_price_per_meter_other").val();
          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();
          // var discount = $("#sell_discount_other").val();
          if (discount.indexOf('%') > -1)
          {
            $("#edit_sell_discount_other_"+row_num).attr('data-discount-type','0'); // percentage
            // $("#sell_discount_other").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
            // $("#sell_discount_other").attr('data-discount-type','1'); // absolute
            total_item_cost = total_item_cost - discount;
            actual_disc = discount;
          }

          // $("#sell_discount_other").attr('data-discount-actual',actual_disc); // absolute 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));  
          // $("#total_item_cost_other").val(currency_format_display(total_item_cost));  
          

          edit_calc_total_purchase_price();

    }

    function calc_payments_9_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").val();
              // var prod_cost = $("#total_item_cost_other").val();
              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('');
                // $("#other_pay").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 other_price = $("#other_pay").val();
          // if(isNaN(other_price)){
          //       other_price =0;
          //     }

          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_9_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").val();
              // var prod_cost = $("#total_item_cost_other").val();
              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('');
                // $("#other_pay").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 + +round(parseFloat(rep_cost),2);
            }
            
          }
          // console.log(purchase_total +" TT");
          // calculate other

          // var other_price = $("#total_item_cost_other").val();
          // other_price = other_price.replace('$','');
          // var other_val = parseFloat(other_price.replace(/,/g,''));




          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 + +round(parseFloat(rep_cost),2);
            }
            
          }


          // 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();
              // alert(td_cost)
              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 + +round(parseFloat(rep_cost),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_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 + +round(parseFloat(rep_cost),2);
            }
            
          }


          // purchase_total = +purchase_total + +other_val;
          $("#edit_purchase_total").val(currency_format_display(purchase_total));


    }

    function compute_area(val, id, row_num){

      var height = $("#curtain_height_"+row_num).val();
      var width  = $("#curtain_width_"+row_num).val();
      var qty    = $("#purchase_quantity_"+row_num).val();

      if(isNaN(height) ){
          noty({
                    width: 200,
                    text: Translation('الرجاء ادخال قيمة عددية في حقل الارتفاع '),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
          $("#curtain_height_"+row_num).val('');
      }

      if( isNaN(width)){
          noty({
                    width: 200,
                    text: Translation('الرجاء ادخال قيمة عددية في حقل  العرض'),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
          $("#curtain_width_"+row_num).val('');
      }

      var area = height * width * qty;
      area = round(area,2);
      if( isNaN(area)){
        area = '';
      }
      $("#total_length_"+row_num).val(area);

      calc_total_item_cost(id,row_num);

    }

    function edit_compute_area(val, id, row_num){

      var height = $("#edit_curtain_height_"+row_num).val();
      var width  = $("#edit_curtain_width_"+row_num).val();
      var qty    = $("#edit_purchase_quantity_"+row_num).val();

      if(isNaN(height) ){
          noty({
                    width: 200,
                    text: Translation('الرجاء ادخال قيمة عددية في حقل الارتفاع '),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
          $("#edit_curtain_height_"+row_num).val('');
      }

      if( isNaN(width)){
          noty({
                    width: 200,
                    text: Translation('الرجاء ادخال قيمة عددية في حقل  العرض'),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
          $("#edit_curtain_width_"+row_num).val('');
      }

      var area = height * width * qty;
      area = round(area,2);

      if( isNaN(area)){
        area = '';
      }
      $("#edit_total_length_"+row_num).val(area);

      edit_calc_total_item_cost(id,row_num);

    }

    
    var states = [];
   
    function CreateStatesCombo(ids) {
        var combo = new STComboBox();
        combo.Init(ids);
        var data = [];

        

        for(var i=0; i < states.length; i++) {
            data.push({id: i, text: states[i]});
        }
        combo.populateList(data);
    }

    function GetStates() {

        var resp;
        $.ajax({
                  url : 'models/crul_offer_curt.php',
                  type : 'POST',
                  data : {type:'search'},
                  dataType : 'json',
                  success : function(response) {
                    states = response;
                  },
                  complete: function() {
                   // console.log(states)
                   CreateStatesCombo('purchase_item_note_1');
                  }

        }); // submit ajax

       
    }


    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="3%" id="edit_num_`+CNT+`">`+CNT+`</td>
                            <td width="8%">
                              <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="8%" id="edit_forign_id_`+CNT+`"></td>

                            <td width="6%">
                              <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 width="6%" id="products_width_`+CNT+`">
                              <input type="text" id="edit_curtain_width_`+CNT+`" name="edit_curtain_width_`+CNT+`"  class="form-control text-center stop_enter" placeholder="`+Translation('العرض')+`"  onchange="edit_compute_area(this.value,this.id,`+CNT+`);">

                            </td>
                            
                            <td width="6%" id="products_height_`+CNT+`">
                              <input type="text" id="edit_curtain_height_`+CNT+`" name="edit_curtain_height_`+CNT+`"  class="form-control text-center stop_enter" placeholder="`+Translation('الارتفاع')+`"  onchange="edit_compute_area(this.value,this.id,`+CNT+`);">

                            </td>
                            

                            <td width="7%" >
                              <input id="edit_total_length_`+CNT+`" name="edit_total_length_`+CNT+`" type="text" class="form-control text-center" readonly >
                            </td>

                           <!-- <td width="6%">
                              <input id="edit_last_sell_price_`+CNT+`" name="edit_last_sell_price_`+CNT+`" type="text" class="form-control text-center" placeholder="`+Translation('اخر سعر بيع')+`" readonly >
                            </td> -->

                            <td width="7%">
                              <input id="edit_buy_price_per_meter_`+CNT+`" name="edit_buy_price_per_meter_`+CNT+`" type="text" class="form-control text-center stop_enter" placeholder="`+Translation('سعر بيع المتر')+`" onchange="edit_calc_total_item_cost(this.id,`+CNT+`);" >
                            </td>

                           <!-- <td width="6%">
                              <input id="edit_last_sell_price_decor_`+CNT+`" name="edit_last_sell_price_decor_`+CNT+`" type="text" class="form-control text-center" placeholder="`+Translation('اخر سعر بيع ديكور')+`" readonly >
                            </td> -->

                            <td width="7%">
                              <input id="edit_buy_price_per_meter_decor_`+CNT+`" name="edit_buy_price_per_meter_decor_`+CNT+`" type="text" class="form-control text-center stop_enter" placeholder="`+Translation('سعر بيع متر الديكور')+`" onchange="edit_calc_total_item_cost(this.id,`+CNT+`);" >
                            </td>

                            <td width="7%">
                              <input id="edit_sell_discount_`+CNT+`" name="edit_sell_discount_`+CNT+`" data-discount-type="" data-discount-actual="" type="text" class="form-control text-center 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" 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('ملاحظات')+`" >
                              <span id="purchase_item_note_`+CNT+`"></span>
                            </td>
                            <td width="9%" >
                              <input id="edit_sell_item_delivery_name_`+CNT+`" name="edit_sell_item_delivery_name_`+CNT+`" type="text" class="form-control text-center 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" onclick="Add_Rows()">
                                <i  class="icon-add text-blue"></i>
                              </button>
                              <button class="btn btn-link btn-xs btn_remove_item" id="edit_row_`+CNT+`" onclick="remove_rows(`+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();
            CreateStatesCombo('edit_purchase_item_note_'+CNT);


    }


    function remove_rows(row_num){
    
          
          $("#edit_item_row_"+row_num).remove();
          edit_calc_total_purchase_price();
          edit_calc_payments();
    
    }


    function Add_Other_Rows(){


        var curnt_row_num = $("#edit_total_rows_other").val();
        var CNT = curnt_row_num;
        
        var attach_new_row =`
                          <tr  id="edit_item_row_other_`+CNT+`" >
                            <td width="3%" id="edit_num_`+CNT+`">#`+CNT+`</td>
                            <td width="8%" colspan="2">
                              <select class="form-control multi_lang stop_enter" data-live-search="true" name="edit_other_id_fk_`+CNT+`" id="edit_other_id_fk_`+CNT+`" data-width="100%" placeholder="`+Translation('مواد اخرى')+`" >
                              </select>
                            </td>
                            
                            <td width="6%">
                              <input type="number" id="edit_other_quantity_`+CNT+`" name="edit_other_quantity_`+CNT+`"  class="form-control multi_lang stop_enter" placeholder="`+Translation('العدد')+`" onchange="edit_calc_other_cost(`+CNT+`);" >
                            </td>
                            <td id="products_other" colspan="2"></td>
                            <td width="7%" >
                              <input id="edit_total_length_other_`+CNT+`" name="edit_total_length_other_`+CNT+`" type="text" class="form-control" readonly >
                            </td>
                           <!-- <td width="6%">
                              <input id="edit_last_sell_price_other_`+CNT+`" name="edit_last_sell_price_other_`+CNT+`" type="text" class="form-control multi_lang stop_enter" placeholder="`+Translation('اخر سعر بيع')+`" readonly >
                            </td> -->
                            <td width="8%" colspan="2">
                              <input id="edit_buy_price_per_meter_other_`+CNT+`" name="edit_buy_price_per_meter_other_`+CNT+`" type="text" class="form-control multi_lang stop_enter" placeholder="`+Translation('سعر البيع')+`" onchange="edit_calc_other_cost(`+CNT+`);" >
                            </td>
                            <td width="8%">
                              <input id="edit_sell_discount_other_`+CNT+`" name="edit_sell_discount_other_`+CNT+`" data-discount-type="" data-discount-actual="" type="text" class="form-control multi_lang stop_enter" placeholder="`+Translation('تنزيلات')+`" onchange="edit_calc_other_cost(`+CNT+`);" >
                            </td>
                            <td width="9%" >
                              <input id="edit_total_item_cost_other_`+CNT+`" name="edit_total_item_cost_other_`+CNT+`" type="text" value="0 $" class="form-control text-center" readonly >
                            
                            </td>
                            <td width="9%">
                              <input type="text" id="edit_purchase_item_note_other_`+CNT+`" name="edit_purchase_item_note_other_`+CNT+`" class="form-control multi_lang stop_enter" placeholder="`+Translation('ملاحظات')+`" >
                            </td>
                            <td width="9%" >
                              <input id="edit_sell_item_delivery_name_other_`+CNT+`" name="edit_sell_item_delivery_name_other_`+CNT+`" type="text"  class="form-control text-center stop_enter" placeholder="المستلم" >
                            
                            </td>
                            <!--<td width="7%" >
                              <input id="edit_other_pay_`+CNT+`" name="edit_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 edit_add_others_btn" onclick="Add_Other_Rows()">
                                <i  class="icon-database-add text-teal"></i>
                              </button>
                              <button class="btn btn-link btn-xs edit_btn_other_remove_item" id="edit_row_other_`+CNT+`" onclick="remove_other_rows(`+CNT+`)">
                                <i  class="icon-subtract text-danger-600"></i>
                              </button>
                            </td>
                          </tr>
                            `;

            $("#edit_footer_sum").before(attach_new_row);
            get_Others(CNT);
            CNT = +curnt_row_num + +1;
            $("#edit_total_rows_other").val(CNT);
            
            $(".stop_enter").autotab();
            


    }


    function remove_other_rows(row_num){
    
          
          $("#edit_item_row_other_"+row_num).remove();
          edit_calc_total_purchase_price();
          edit_calc_payments();
    
    }


    function elements_set_focus(){
      $("#customer_id_fk").val('').selectpicker('refresh');
    }


    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="3%" id="num_`+CNT+`">`+CNT+`</td>
                            <td width="8%">
                              <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="8%" id="forign_id_`+CNT+`"></td>

                            <td width="6%">
                              <input type="number" 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 width="6%" id="products_width_`+CNT+`">
                              <input type="text" id="curtain_width_`+CNT+`" name="curtain_width_`+CNT+`"  class="form-control text-center stop_enter" placeholder="`+Translation('العرض')+`"  onchange="compute_area(this.value,this.id,`+CNT+`);">

                            </td>
                            
                            <td width="6%" id="products_height_`+CNT+`">
                              <input type="text" id="curtain_height_`+CNT+`" name="curtain_height_`+CNT+`"  class="form-control text-center stop_enter" placeholder="`+Translation('الارتفاع')+`"  onchange="compute_area(this.value,this.id,`+CNT+`);">

                            </td>
                            

                            <td width="7%" >
                              <input id="total_length_`+CNT+`" name="total_length_`+CNT+`" type="text" class="form-control text-center" readonly >
                            </td>

                           <!-- <td width="6%">
                              <input id="last_sell_price_`+CNT+`" name="last_sell_price_`+CNT+`" type="text" class="form-control text-center" placeholder="`+Translation('اخر سعر بيع')+`" readonly >
                            </td> -->

                            <td width="7%">
                              <input id="buy_price_per_meter_`+CNT+`" name="buy_price_per_meter_`+CNT+`" type="text" class="form-control text-center stop_enter" placeholder="`+Translation('سعر بيع المتر')+`" onchange="calc_total_item_cost(this.id,`+CNT+`);" >
                            </td>

                           <!-- <td width="6%">
                              <input id="last_sell_price_decor_`+CNT+`" name="last_sell_price_decor_`+CNT+`" type="text" class="form-control text-center" placeholder="`+Translation('اخر سعر بيع ديكور')+`" readonly >
                            </td> -->

                            <td width="7%">
                              <input id="buy_price_per_meter_decor_`+CNT+`" name="buy_price_per_meter_decor_`+CNT+`" type="text" class="form-control text-center stop_enter" placeholder="`+Translation('سعر بيع متر الديكور')+`" onchange="calc_total_item_cost(this.id,`+CNT+`);" >
                            </td>

                            <td width="7%">
                              <input id="sell_discount_`+CNT+`" name="sell_discount_`+CNT+`" data-discount-type="" data-discount-actual="" type="text" class="form-control text-center 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" readonly >
                            </td>
                            <td width="9%">
                              <!-- <input type="text" id="purchase_item_note_`+CNT+`" name="purchase_item_note_`+CNT+`" class="form-control stop_enter" placeholder="`+Translation('ملاحظات')+`" > -->
                              <span id="purchase_item_note_`+CNT+`"></span>
                            </td>
                            <td width="9%" >
                              <input id="sell_item_delivery_name_`+CNT+`" name="sell_item_delivery_name_`+CNT+`" type="text" class="form-control text-center 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();
            CreateStatesCombo('purchase_item_note_'+CNT);

    }



$(document).ready(function() {
  
    get_products(1);
    get_Profile_price();
    get_Customer();
    // escape_notes();
    get_Others(1);
    get_Item_Class();
    GetStates();
    // type_ahead_list('#purchase_item_note_1');



    
    // add new tab when reach the end of row
    $("#purchase_item_body").on("keypress","[id^='sell_item_delivery_name_']", 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();

     });


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

     });

     $("#edit_purchase_item_footer").on('click','.edit_btn_other_remove_item',function(e){
        e.preventDefault();

     });


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

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

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


    $("#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="3%" id="num_`+CNT+`">#`+CNT+`</td>
                            <td width="8%" colspan="2">
                              <select class="form-control multi_lang stop_enter" 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 stop_enter" placeholder="`+Translation('العدد')+`" onchange="calc_other_cost(`+CNT+`);" >
                            </td>
                            <td id="products_other" colspan="2"></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 stop_enter" placeholder="`+Translation('اخر سعر بيع')+`" readonly >
                            </td> -->
                            <td width="8%" colspan="2">
                              <input id="buy_price_per_meter_other_`+CNT+`" name="buy_price_per_meter_other_`+CNT+`" type="text" class="form-control multi_lang stop_enter" 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 stop_enter" 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 stop_enter" placeholder="`+Translation('ملاحظات')+`" > </textarea>
                            </td>
                            <td width="9%" >
                              <input id="sell_item_delivery_name_other_`+CNT+`" name="sell_item_delivery_name_other_`+CNT+`" type="text"  class="form-control text-center stop_enter" placeholder="المستلم" >
                            
                            </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);
            $(".stop_enter").autotab();
    });


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

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


    $('#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-6" value="`+$("#roll_length_"+i).val()+`" onchange="calc_total_length(`+row_no+`,`+qty+`);">`;
          }
          
          $("#products_height_"+row_no).html(attach_input);
          $("#products_width_"+row_no).remove();
          $("#products_height_"+row_no).attr('colspan','2');
          $("#buy_price_per_meter_decor_"+row_no).attr('readonly','readonly');


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

    });




    $('#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_height_"+row_no).html(attach_input);
          $("#products_width_"+row_no).remove();
          $("#products_height_"+row_no).attr('colspan','2');
          $("#buy_price_per_meter_decor_"+row_no).attr('readonly','readonly');

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

    });


    $("#add_form").on("keyup",".btn_add_item", function (e) {
          
         

          if (e.keyCode == 9 || e.which ==9) {
           
            e.preventDefault();
            
            // Add_Rows();

            $(this).trigger('click');
          
          }else if (e.keyCode == 13 || e.which ==13) {
            e.preventDefault();
             $.autotab.next();
          }
    });


    // submit form when enter pressed in note field
    $("#add_form").on("keypress",".submit_enter", function (e) {
         
          if (e.keyCode == 13 || e.which ==13) {
           
            e.preventDefault();

            $('#add_form').submit();
           
          }
    });

    $('#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 deliver_array                       =[];
          // var payments_array                      =[];
          var item_type_array                     =[];
          var height_array                        =[];
          var width_array                         =[];
          var decor_price_array                   =[];

          var check_products                      =[];
          var check_quantity                      =[];
          var check_price                         =[];
          var check_rolls                         =[];
          var check_rolls_all                     =[];
          var check_height                        =[];
          var check_width                         =[];
          var check_decor_price                   =[];
          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+"-ddi").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');
              var height_curt     = $("#curtain_height_"+i).val();
              var width_curt      = $("#curtain_width_"+i).val();
              var decor_price     = $("#buy_price_per_meter_decor_"+i).val();
              var deliver_name    = $("#sell_item_delivery_name_"+i).val();

              

              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.000001);
                
                
                // check if height and width elments are exists
                if($('#curtain_height_'+i).length >0 && $('#curtain_width_'+i).length >0){
                
                  check_height[k]           = Checks('curtain_height_'+i,'No',1);
                  check_width[k]            = Checks('curtain_width_'+i,'No',1);
                  // check_decor_price[k]      = Checks('buy_price_per_meter_decor_'+i,'No',0.000001);

                }
                //console.log(check_quantity)
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                notes_array[k]            = notes;
                deliver_array[k]          = deliver_name;
                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;

                height_array[k]           = height_curt;
                width_array[k]            = width_curt;
                decor_price_array[k]      = decor_price;


                // 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 =[];

                if($('#curtain_height_'+i).length ==0 && $('#curtain_width_'+i).length ==0){
                
                  // alert(height_curt)
                  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;
                  }

                }else{
                  for(var j=1; j<=quantityField; j++){
                    roll_length_array[j]      = height_curt + ";" + width_curt ;
                    
                    roll_id_fk_array[j]       = 'c';  // 0 havn't purchase; >0 have purchase item; c its curtain
                    
                  }

                }
                

                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 invoice_type_singular       = $("#invoice_type_singular").val();  //0 plural ; 1 single
          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                  = 0;
          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 checkheight = true;
          var checkwidth  = true;
          var checkdecor  = 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_height[m]==false){
              checkheight = false;
            }

            if(check_width[m]==false){
              checkwidth = false;
            }

            // if(check_decor_price[m]==false){
            //   checkdecor = 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                    ='';
             other_quantity_array              ='';
             other_price_array                 ='';
             other_discount_val_array          ='';
             other_discount_type_array         ='';
             other_discount_actual_array       ='';
             other_row_total_price_array       ='';
             other_notes_array                 ='';
             // other_payments_array              ='';
          }




        if(Check1 && Check2 && checkpriceOther && checkQtyOther && CheckPro && checkQty && checkrolls && checkprice && checkheight && checkwidth && checkdecor ){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_offer_curt.php",
                type:"POST",
                dataType: "JSON",
                data : {invoice_type              :invoice_type,
                        is_single                 :invoice_type_singular,
                        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                :'',

                        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,
                        sell_item_deivery         :deliver_array,
                        row_price                 :row_total_price_array,
                        // row_payments              :payments_array,
                        item_type                 :item_type_array,
                        original_length           :roll_original_length_total_array,
                        decor_price               :decor_price_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: 'success',
                    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 deliver_array                       =[];
          // var payments_array                      =[];
          var item_type_array                     =[];
          var height_array                        =[];
          var width_array                         =[];
          var decor_price_array                   =[];

          var check_products                      =[];
          var check_quantity                      =[];
          var check_price                         =[];
          var check_rolls                         =[];
          var check_rolls_all                     =[];
          var check_height                        =[];
          var check_width                         =[];
          var check_decor_price                   =[];
          var k=0;

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

              


              var productID       = $("#edit_product_id_fk_"+i).val();
              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     = $("#product_pay_"+i).val();
              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');
              var height_curt     = $("#edit_curtain_height_"+i).val();
              var width_curt      = $("#edit_curtain_width_"+i).val();
              var decor_price     = $("#edit_buy_price_per_meter_decor_"+i).val();
              var deliver_name    = $("#edit_sell_item_delivery_name_"+i).val();

              

              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.000001);
                
              

                // check if height and width elments are exists
                if($('#curtain_height_'+i).length >0 && $('#curtain_width_'+i).length >0){
                
                  check_height[k]           = Checks('edit_curtain_height_'+i,'No',0.1);
                  check_width[k]            = Checks('edit_curtain_width_'+i,'No',0.1);
                  // check_decor_price[k]      = Checks('buy_price_per_meter_decor_'+i,'No',0.000001);

                }


            
                // now i should check for rolls number and it should equal to quantity
                
                //console.log(check_quantity)
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                notes_array[k]            = notes;
                deliver_array[k]          = deliver_name;
                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;

                height_array[k]           = height_curt;
                width_array[k]            = width_curt;
                decor_price_array[k]      = decor_price;


                // 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 =[];


                if($('#edit_curtain_height_'+i).length ==0 && $('#edit_curtain_width_'+i).length ==0){
                
                  // alert(height_curt)
                  for(var j=1; j<=quantityField; j++){
                    check_rolls[j]           = Checks('edit_row_'+i+'_roll_'+j,'No',1,null,'badge');
                    var rolls                = $('#edit_row_'+i+'_roll_'+j).val();
                    var roll_id_fk           = $('#edit_row_'+i+'_roll_'+j).attr('data-roll-id-fk');
                    var roll_original_length = $('#edit_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('#edit_row_'+k+'_roll_'+j);

                    roll_length_array[j]    = rolls;
                  }

                }else{
                  for(var j=1; j<=quantityField; j++){
                    roll_length_array[j]      = height_curt + ";" + width_curt ;
                    
                    roll_id_fk_array[j]       = 'c';  // 0 havn't purchase; >0 have purchase item; c its curtain
                    
                  }

                }


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


          // 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();
          
          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_delivery_array                      =[];
          // var other_payments_array                      =[];
          
          
          var check_quantity_other                      =[];
          var check_price_other                         =[];
          var k=0;

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

              var productID       = $("#edit_other_id_fk_"+i).val();
              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');
              var deliver_name    = $("#edit_sell_item_delivery_name_other_"+i).val();




              

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

              
               

               
                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;
                other_delivery_array[k]         = deliver_name;
                
                
                k++;
              }
          }



          
          // console.log(sell_id_array);
          console.log(height_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 checkheight = true;
          var checkwidth  = 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_height[m]==false){
              checkheight = false;
            }

            if(check_width[m]==false){
              checkwidth = 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 there is no other in invoice we should make its value to be send in ajax
          var no_others = 0;

          if(other_id_array.length ==0){

            //     other_id_array                            =[];
            // other_quantity_array                      =[];
            // other_price_array                         =[];
            // other_discount_val_array                  =[];
            // other_discount_type_array                 =[];
            // other_discount_actual_array               =[];
            // other_row_total_price_array               =[];
            // other_notes_array                         =[];
            // other_delivery_array                      =[];

             other_id_array                    ='';
             other_quantity_array              ='';
             other_price_array                 ='';
             other_discount_val_array          ='';
             other_discount_type_array         ='';
             other_discount_actual_array       ='';
             other_row_total_price_array       ='';
             other_notes_array                 ='';
             other_delivery_array              = '';
             no_others                         = 1;

             // other_payments_array              ='';
          }
          


          if(Check1 && Check2 && CheckPro && checkQty && checkwidth && checkheight && checkprice && checkpriceOther && checkQtyOther){
              $("#submit_edit_btn").attr('disabled',true);
              $.ajax({
                  url: "models/crul_offer_curt.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,
                          
                          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_deliver_name        :other_delivery_array,
                          no_others                 :no_others,
                          
                          total_invoice             :total_invoice,
                          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,
                          sell_item_deivery         :deliver_array,
                          decor_price               :decor_price_array,
                          height                    :height_array,
                          width                     :width_array,



                          item_length               :roll_total_array,
                        
                        
                          roll_id_fk                :roll_id_fk_total_array,
                         
                          sell_item_deivery         :deliver_array,
                          row_price                 :row_total_price_array,
                         
                          item_type                 :item_type_array,
                          original_length           :roll_original_length_total_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',
                });
          }


            
            
    });
   

    
    $('#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 deliver_array                       =[];
          // var payments_array                      =[];
          // var payments_id_array                   =[];
          var height_array                        =[];
          var width_array                         =[];
          var decor_price_array                   =[];
          var sell_id_array                       =[];

          var check_quantity_other                =[];
          var check_price_other                   =[];

          var check_products                      =[];
          var check_quantity                      =[];
          var check_price                         =[];
          var check_height                        =[];
          var check_width                         =[];
          var check_decor_price                   =[];


          var k=0;

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

              var productID       = $("#edit_product_id_fk_"+i).attr('data-product-id');
              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');

              var height_curt     = '';
              var width_curt      = '';
              var decor_price     = '';
              var deliver_name    = $("#edit_sell_item_delivery_name_"+i).val();

              

              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);
                
                
                // check if height and width elments are exists
                if($('#edit_curtain_height_'+i).length >0 && $('#edit_curtain_width_'+i).length >0){
                
                  check_height[k]     = Checks('edit_curtain_height_'+i,'No',1);
                  check_width[k]      = Checks('edit_curtain_width_'+i,'No',1);
                  height_curt         = $("#edit_curtain_height_"+i).val();
                  width_curt          = $("#edit_curtain_width_"+i).val();
                  decor_price         = $("#edit_buy_price_per_meter_decor_"+i).val();
                }


                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;


                deliver_array[k]          = deliver_name;
                height_array[k]           = height_curt;
                width_array[k]            = width_curt;
                decor_price_array[k]      = decor_price;
                // 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');
              var deliver_name    = $("#edit_sell_item_delivery_name_other_"+i).val();

              

              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;

                deliver_array[k]          = deliver_name;
                height_array[k]           = '';
                width_array[k]            = '';
                decor_price_array[k]      = '';
                
                
                k++;
              }
          }



          
          console.log(sell_id_array);
          console.log(height_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 checkheight = true;
          var checkwidth  = 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_height[m]==false){
              checkheight = false;
            }

            if(check_width[m]==false){
              checkwidth = 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 && checkwidth && checkheight && checkprice && checkpriceOther && checkQtyOther){
              $("#submit_edit_btn").attr('disabled',true);
              $.ajax({
                  url: "models/crul_invoice_curt.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,
                          sell_item_deivery         :deliver_array,
                          decor_price               :decor_price_array,
                          height                    :height_array,
                          width                     :width_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_others_btn").on('click',function(e){
        e.preventDefault();
        // $("#add_other_modal").modal('toggle');
    });

    $('#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");
   var query_typ  = getQueryVariable("typ");


    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_offer_curt.php",
        "data": function(d){
          d.type = "load";
          if(query_ip !='not'){
            d.ip =query_ip ;
          }
          if(query_typ !='not'){
            d.typ =query_typ ;
          }
          
        }
        },
        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) {
                var btns = '';

                if(row[8] =='0' || row[8] == '2'){
                  btns = `
                          <li class='text-primary-600'>
                              <a  class='text-success-400' onclick="accept_offer(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('قبول العرض')+`'>
                                  <i class='icon-checkmark-circle2'></i>  `+Translation('قبول العرض وتحويله لوصل بيع')+` 
                              </a>
                          </li>

                          <li class='text-primary-600'>
                              <a  class='text-danger-600' onclick="reject_offer(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('رفض العرض')+`'>
                                  <i class='icon-cancel-circle2'></i> `+Translation('رفض العرض')+`
                              </a>
                          </li>

                          <li class='text-primary-600'>
                              <a  class='text-primary-400' onclick="edit_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('تعديل')+`'>
                                  <i class='icon-pencil7'></i> `+Translation('تعديل')+`
                              </a>
                          </li>

                  `;
                }

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


                            <!--
                            <li class='text-danger-600'>
                                <a href='#' onclick="add_payments(`+row[11]+`)" data-popup='tooltip' data-original-title='Add New Payments to this Invoice'>
                                    <i class='icon-cash text-primary-600'></i>
                                </a>
                            </li>
                           --> 
                            <li class="dropdown">
                              <a  class="dropdown-toggle" data-toggle="dropdown"  data-original-title='`+Translation('Actions')+`'>
                                <i class="icon-menu9"></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-popup='tooltip' data-original-title='`+Translation('عرض وصل البيع مع التفاصيل')+`'>
                                        <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='tooltip' data-original-title='`+Translation('طباعة الوصل مع التفاصيل')+`'>
                                        <i class='icon-printer2'></i> `+Translation('طباعة الوصل مع التفاصيل')+`
                                    </a>
                                </li>
                                
                                <li class='text-primary-600'>
                                    <a  class='text-orange-400' onclick="show_invoice(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('عرض وصل البيع بدون التفاصيل')+`'>
                                        <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-popup='tooltip' data-original-title='`+Translation('طباعة الوصل بدون التفاصيل')+`'>
                                        <i class='icon-printer4'></i> `+Translation('طباعة الوصل بدون التفاصيل')+`
                                    </a>
                                </li>

                                <li class='text-primary-600'>
                                    <a  class='text-purple-400' onclick="show_sticker(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('عرض ملصقات الوصل')+`'>
                                        <i class='icon-qrcode'></i> `+Translation('عرض ملصقات الوصل')+`
                                    </a>
                                </li>

                                `+btns+`
                                <!--<li class='text-primary-600'>
                                    <a  class='text-primary-400' onclick="edit_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('تعديل')+`'>
                                        <i class='icon-pencil7'></i> `+Translation('تعديل')+`
                                    </a>
                                </li>-->
                                
                                <li class='text-danger-600'>
                                    <a  class='text-danger-400' onclick="delete_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('حذف')+`'>
                                        <i class='icon-trash'></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] ==0 ){
                     status = '<span class="label bg-violet  btn-block "> '+Translation('عرض')+' </span>';
                   }else if(row[8] ==1){
                     status = '<span class="label bg-success-600  btn-block "> '+Translation('اصبح وصل بيع')+' </span>';
                   }else if(row[8] ==2){
                     status = '<span class="label bg-danger-400  btn-block "> '+Translation('تم رفض العرض')+' </span>';

                   }else{

                       return  row[8];
                   }
                   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"
                                      
                                      aria-controls="add-form-cont"
                                      aria-expanded="false"
                                      class="btn btn-warning"
                                      id="add_Item_Btn" onclick="elements_set_focus();">
                                        <i class="`+CURRENT_BTN_ICON+`"></i> `+Translation(CURRENT_BTN)+`
                                    </a>`); 

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


});



