<?php

$tot_balance=0;

?>

<?php $this->load->view("common/header"); ?>

<!-- end: HEAD -->

<!-- start: CSS REQUIRED FOR THIS PAGE ONLY -->
<link rel="stylesheet" type="text/css" href="<?php echo asset_url(); ?>plugins/select2/select2.css" />
<link rel="stylesheet" href="<?php echo asset_url(); ?>plugins/datepicker/css/datepicker.css">
<link rel="stylesheet" href="<?php echo asset_url(); ?>plugins/summernote/build/summernote.css">
<body>
<div class="panel">
  <div class="panel-body">
    <div class="alert alert-danger" style="display:none;">
      <button class="close" data-dismiss="alert"> × </button>
      <i class="fa fa-times-circle"></i> <strong></strong> <span class="errortxt"></span> </div>
    <div class="alert alert-success" style="display:none;">
      <button class="close" data-dismiss="alert"> × </button>
      <i class="fa fa-check-circle"></i> <strong></strong><span class="succetxt"></span> </div>
    <form role="form" class="form-horizontal" id="create_collection_form" action="#" method="post">
      <input type="hidden" id="supplier_id" class="form-control" name="supplier_id" value="<?php echo $supplier_details['supp_id']  ?>"  >
      <input type="hidden" id="warehouse_id" class="form-control " name="warehouse_id" value="<?php echo $warehouse_details['id'] ?>" />
      <div class="page-header">
        <h1 align="center">Supplier multiple payments</h1>
      </div>
      <div class="col-md-12">
        <label><strong>Supplier.. : <?php echo $supplier_details['supp_company_name']  ?> </strong></label><br/>
        <label><strong>Warehouse : <?php echo $warehouse_details['name'] ?> </strong></label><br/>
        <!-- <label><strong>Supplier Balance : Rs. <?php echo $supplier_balance ?></strong></label> -->
      </div>
      <div class="col-md-12">
        <div class="well well-sm">
          <div class="">
            <div class="col-sm-3">
              <div >
                <label>Date/Cheque realize *</label>
                <input id="sale_pymnt_date_time" name="sale_pymnt_date_time" type='text' class="form-control date-picker" value="<?php
echo date("Y-m-d");
?>" data-bv-field="date" />
              </div>
            </div>
            <div class="col-sm-3">
              <div class="payment">
                <div >
                  <label for="amount_1">Amount *</label>
                  <input required type="text" class="pa form-control kb-pad amount" id="sale_pymnt_amount" name="sale_pymnt_amount" value="" />
                </div>
              </div>
            </div>
            <div class="col-sm-3">
              <div class="payment">
                <div class="form-group">
                  <label for="amount_1">Paying by ..</label>
                  <select class="form-control paid_by" id="sale_pymnt_paying_by" name="sale_pymnt_paying_by" data-bv-field="paid_by" tabindex="-1" title="Paying by *" onChange="changePayingby(this.value)">
                    <option value="Cash">Cash</option>
                    <!-- <option value="Credit Card">Credit Card</option> -->
                    <option value="Cheque">Cheque</option>
                     <option value="Bank Deposit">Bank Deposit</option>
                     <option value="Online Transfer">Online Transfer</option>
                     
                     <option value="Deduction">Deduction</option>
                    
                  </select>
                </div>
              </div>
            </div>
            
            <!-- payment options start-->
            
            <div class="clearfix"></div>
            <div id="cheque_dtls" style="display:none;" class="paying_by_details col-sm-12">
              <label for="date"><span id="cheque_no_text">Cheque</span> No *</label>
              <input type="text" id="sale_pymnt_cheque_no" class="form-control" value="" name="sale_pymnt_cheque_no" data-bv-field="date">
              <label class="control-label"> Bank * </label>
              <!-- 
              <textarea id="sale_note"  class="ckeditor form-control" cols="10" rows="2" name="sale_note"></textarea>
             <!--  <select id="in_type" class="form-control" name="in_type"> -->
             
             <select id="warehouse_id" class="form-control text_box_height search-select" name="warehouse_id">
                        
                      <option value="">-- Select --</option>
                        
                        <?php 

																 $ss_warehouse_id=$this->session->userdata('ss_warehouse_id'); 

                                                              foreach ($bank_details as $row)

                                                              {

																  $sel='';

																 // if($ss_warehouse_id==$row->id)

																  {

																	 // $sel=' selected="selected"';

																  }

                                                              ?>
                        <option value="<?php echo $row->b_id; ?>" <?php echo $sel ?> > <?php echo $row->b_account_no; ?> | <?php echo $row->b_name; ?> | <?php echo $row->account_holder_name; ?>  </option>
                        <?php }?>
                      </select>
                  
                 
            </div>
            
            <!--cheque-->
            
            <div id="credit_card" style="display:none;" class="paying_by_details">
              <div class="col-sm-5">
                <div class="form-group">
                  <input type="text" id="sale_pymnt_crdt_card_no" class="form-control tip" value="" name="sale_pymnt_crdt_card_no" placeholder="Credit Card No *">
                </div>
              </div>
              <!--col-sm-5-->
              
              <div class="col-sm-5 pull-right">
                <div class="form-group">
                  <input type="text" id="sale_pymnt_crdt_card_holder_name" class="form-control tip" value="" name="sale_pymnt_crdt_card_holder_name" placeholder="Holder Name *">
                </div>
              </div>
              <!--col-sm-5-->
              
              <div class="col-sm-3" style="margin-right:60px;">
                <div class="form-group">
                  <select class="form-control paid_by" id="sale_pymnt_crdt_card_type" name="sale_pymnt_crdt_card_type" data-bv-field="paid_by">
                    <option value="">-- Select Credit Card Type --</option>
                    <option value="Visa">Visa</option>
                    <option value="MasterCard">MasterCard</option>
                    <option value="Amex">Amex</option>
                    <option value="Discover">Discover</option>
                  </select>
                </div>
              </div>
              <!--col-sm-3-->
              
              <div class="col-sm-3">
                <div class="form-group">
                  <input type="text" id="sale_pymnt_crdt_card_month" class="form-control tip" value="" name="sale_pymnt_crdt_card_month" placeholder="Month *">
                </div>
              </div>
              <!--col-sm-3-->
              
              <div class="col-sm-3 pull-right">
                <div class="form-group">
                  <input type="text" id="sale_pymnt_crdt_card_year" class="form-control tip" value="" name="sale_pymnt_crdt_card_year" placeholder="Year *">
                </div>
              </div>
              <!--col-sm-3--> 
              
            </div>
            <!--credit_card-->
            
            <div class="clearfix"></div>
            
            <!-- end payment optiones -->
            
            <div id="note_grid" class="form-group">
              <div class="col-sm-12">
                <label class="control-label"> Note </label>
                <textarea id="sale_note_two"  class="ckeditor form-control" cols="10" rows="2" name="sale_note_two"></textarea>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- end payments-->
      
      <div class="col-md-12">
        <input type='hidden' class="form-control" id="sale_reference_no" name="sale_reference_no" value="" readonly/>
        <div class="col-md-12">
          <div class="col-sm-4" id="cr_interest_div" style="display:none">
            <div class="form-group">
              <label for="cr_interest">Credit Interest</label>
              <select class="form-control" name="cr_interest" id="cr_interest" onChange="" style="display:none">
                <option value="">-- Select Credit Interest --</option>
                <?php
foreach ($cr_limit_list as $row) {
?>
                <option value="<?php
    echo $row['cr_limit_value'];
?>">
                <?php
    echo $row['cr_limit_name'];
    echo " / ";
    echo $row['cr_limit_value'];
    echo "% ";
?>
                </option>
                <?php
}
?>
              </select>
            </div>
          </div>
        </div>
      </div>
      <!--col-md-8--> 
      
      <!-- item add box-->
      
      <div id="sticker" class="col-md-12">
        <div class="well well-sm">
          <div class="form-group"> 
            
            <!-- auto complete start -->
            
            <div class="input-group wide-tip" style="display:none">
              <div style="padding-left: 10px; padding-right: 10px;" class="input-group-addon"> <i class="fa fa-2x fa-barcode addIcon"></i> </div>
              <input type="text" placeholder="Please add products to order list" id="add_item" class="form-control input-lg" value="" name="add_item" style="border-radius: 6px;font-size: 18px;height: 46px;line-height: 1.33;padding: 10px 16px;">
              
              <!--<div style="padding-left: 10px; padding-right: 10px;" class="input-group-addon">

                                                            <i id="addIcon" class="fa fa-2x fa-plus-circle addIcon"></i>

                                                        </div>--> 
              
            </div>
            
            <!-- end auto complete end --> 
            
          </div>
          <div class="clearfix"></div>
          <div class="control-group table-group">
            <p id="loader" align="center" style="display:none">Loading...<i class="fa fa-spin fa-spinner"></i></p>
            <div class="controls table-controls">
              <table class="table items table-striped table-bordered table-condensed table-hover" id="cash_collect">
                <thead>
                  <tr>
                    <th class="">#</th>
                    <th class="col-md-1">GRN No</th>
                    <th class="col-md-2">Supplier Ref.No</th>
                    <th class="col-md-2">Date</th>
                    <th class="col-md-2">Total Amount</th>
                    <th class="col-md-2">Paid Amount</th>
                    <th class="col-md-2">Balance Amount</th>
                    <th class="col-md-2"> <input type="checkbox" id="select_all" />
                      Select </th>
                    <th class="col-md-2">Amount</th>
                    <th style="width: 30px !important; text-align: center;"><i class="fas fa-trash-alt"></i></th>
                  </tr>
                </thead>
                <tbody>
                  <?php //echo '<pre>'; print_r($issue_card_items_details);
?>
                  <?php
$tmpcount = 0;
$tmptot   = 0;
//$mod_sale = new Purchases_Model();

//echo '<pre>';
	//print_r($purchases_list);					//grn_paid_total
//	echo '</pre>';
foreach ($purchases_list as $row) {
    //if($tmpcount > 9) break;
    $balance_amount   = 0;
    $sale_tot_amount  = 0;
    $sale_id          = $row->id;
	
	//echo '<pre>';
	//print_r($row);					//grn_paid_total
	//echo '</pre>';
	
    $sale_info        = $this->Purchases_Model->getpurchases_by_id($sale_id);
    $sale_tot_amount  = $sale_info[0]->grand_total;
    $sale_paid_amount = $this->Purchases_Model->grn_pay_total($sale_id);
	$sale_paid_amount = floatval($sale_paid_amount[0]->grn_paid_total);
	//echo '<pre>';
	//print_r($sale_paid_amount);					//grn_paid_total
	//echo '</pre>';
	
	//echo '<pre>';
	//print_r($sale_paid_amount);					//grn_paid_total
	//echo '</pre>';
    $balance_amount   = $sale_tot_amount - $sale_paid_amount;
    $balance_amount   = (float) $balance_amount;
    //check allredy added 
    //$payment_des=$mod_sale->get_payment_des_by_sale_id_issue_card_id($sale_id , $issue_card_id);
    //if(!isset($payment_des->sale_pymnt_amount))
    if ($balance_amount > 0) {$tmpcount++;
?>
                  <tr id="row_c_<?php
        echo $tmpcount;
?>">
                    <td class="text-center"><?php
        echo $tmpcount;
?>
                      <input name="card_row[]" type="hidden" id="card_row_<?php
        echo $tmpcount;
?>" value="<?php
        echo $tmpcount;
?>"></td>
                    <td class="text-center"><?php
        echo $row->reference_no;
?>
                      <input style="text-align:right" name="row_c[<?php
        echo $tmpcount;
?>][sale_id][]" type="hidden" id="sale_id_<?php
        echo $tmpcount;
?>" value="<?php
        echo $row->id;
?>"></td>
                    <td class="text-left"><?php
        echo $row->supp_invocie_no;
?></td>				<td class="text-left"><?php
                            echo date("Y-m-d", strtotime($row->date));
                    ?></td>
                    <td class="text-right"><?php
        echo $row->grand_total;
?></td>
                    <td class="text-right"><?php //echo $row->paid_amount;
?>
                      <?php
        echo $sale_paid_amount;
?></td>
                    <td class="text-left"><?php //echo $balance_amount;
?>
                      <input style="text-align:right" name="balance_amount[]" type="text" id="balance_amount_<?php
        echo $tmpcount;
?>" value="<?php echo $balance_amount;?>">

<?php

// $tot_balance=$tot_balance+$balance_amount;

//echo "<br/> tot_balance:".$balance_amount;
$tot_balance=$tot_balance+$balance_amount;

//echo "<br/> tot_balance:".$tot_balance;

?>

<input style="text-align:right" name="row_c[<?php
        echo $tmpcount;
?>][sale_payment_type][]" type="hidden" id="sale_payment_type_<?php
        echo $tmpcount;
?>" value="grn">
</td>
                    <td class="text-left"><center>
                        <div class='col-xs-12'>
                          <div class='col-xs-1' style="padding:0px">
                            <input row_n="<?php
        echo $tmpcount;
?>" class="checkbox" id="collection_c_<?php
        echo $tmpcount;
?>" name="row_c[<?php
        echo $tmpcount;
?>][collection][]" value="1" type="checkbox">
                            <!--onChange="add_payment('<?php
        echo $tmpcount;
?>')"--> 
                          </div>
                          &nbsp;Add Payment </div>
                      </center></td>
                    <td class="text-left"><input value="0" id="amount_<?php
        echo $tmpcount;
?>" name="row_c[<?php
        echo $tmpcount;
?>][amount][]" class="added_amount" type="text" style="text-align:right" onClick="this.select(); setTmpVal(this.value);" onChange="changeAmount(<?php
        echo $tmpcount;
?>)"></td>
                    <!-- -->
                    <td><a onClick="deleteCollectCashItem(<?php
        echo $tmpcount;
?>)"><i style="cursor:pointer;" title="Remove" id="1446800197032" class="fa fa-times tip podel"></i></a></td>
                  </tr>
                  <?php
    }
}

// /

?>

<tr>
    <td></td>
     <td colspan="2"><b>GRN RETURN</b> </td>
     
     <td></td>
     <td></td>
     <td></td>
     <td></td>
     <td></td>
     <td></td>
     <td></td>
</tr>
<?php
          //print_r($purchases_rtn_list);
          //$trn_count=0;
          
          foreach ($purchases_rtn_list as $row_r) {
              $tmpcount++;
              
              $grn_return_paid_amount=0;
	 $grn_return_paid_amount=$this->Sales_Model->get_total_paid_by_grn_return_id($row_r->pur_rtn_id);
	 
	  $balance_amount_rtn=$row_r->pur_rtn_inv_total+$grn_return_paid_amount;
	  if($balance_amount_rtn) $balance_amount_rtn=$balance_amount_rtn*-1;
 if($balance_amount_rtn) {            
?>
 <tr id="row_c_<?php
        echo $tmpcount;
?>">
    <td><?php echo $tmpcount;?>
     <input name="card_row[]" type="hidden" id="card_row_<?php
        echo $tmpcount;
?>" value="<?php
        echo $tmpcount;
?>">
</td>
     <td><?php echo $row_r->pur_rtn_reference_no;?>
     
     <input style="text-align:right" name="row_c[<?php
        echo $tmpcount;
?>][sale_id][]" type="hidden" id="sale_id_<?php
        echo $tmpcount;
?>" value="<?php
        echo $row_r->pur_rtn_id;
?>">
     </td>
     <td>
         
         
         
     </td>
     <td><?php //echo $row_r->pur_rtn_datetime;?>
     <?php
                            echo date("Y-m-d", strtotime($row_r->pur_rtn_datetime));
                    ?></td>
     <td style="text-align:right" ><?php echo $row_r->pur_rtn_inv_total;
     
    
     ?></td>
     <td style="text-align:right" >
         <?php echo number_format($grn_return_paid_amount, 2, '.', ',');;?>
         
     </td>
     
     <td><input style="text-align:right" name="balance_amount[]" type="text" id="balance_amount_<?php
        echo $tmpcount;
?>" value="<?php echo $balance_amount_rtn;?>">

<?php
$tot_balance=$tot_balance+$balance_amount_rtn;

?>


<input style="text-align:right" name="row_c[<?php
        echo $tmpcount;
?>][sale_payment_type][]" type="hidden" id="sale_payment_type_<?php
        echo $tmpcount;
?>" value="grn_return">
</td>
<td><center>
                        <div class='col-xs-12'>
                          <div class='col-xs-1' style="padding:0px">
                            <input row_n="<?php
        echo $tmpcount;
?>" class="checkbox" id="collection_c_<?php
        echo $tmpcount;
?>" name="row_c[<?php
        echo $tmpcount;
?>][collection][]" value="1" type="checkbox">
                            <!--onChange="add_payment('<?php
        echo $tmpcount;
?>')"--> 
                          </div>
                          &nbsp;Add Payment </div>
                      </center></td>
     <td><input value="0" id="amount_<?php
        echo $tmpcount;
?>" name="row_c[<?php
        echo $tmpcount;
?>][amount][]" class="added_amount" type="text" style="text-align:right" onClick="this.select(); setTmpVal(this.value);" onChange="changeAmount(<?php
        echo $tmpcount;
?>)"></td>
     <td><a onClick="deleteCollectCashItem(<?php
        echo $tmpcount;
?>)"><i style="cursor:pointer;" title="Remove" id="1446800197032" class="fa fa-times tip podel"></i></a></td>
</tr>

<?php }
}?>
                </tbody>
                <tfoot>
                  <tr>
                      <td colspan="" class="text-right"><strong> </strong></td>
                    <td colspan="" class="text-right"><strong> </strong></td>
                    <td colspan="" class="text-right"><strong> </strong></td>
                    <td colspan="" class="text-right"><strong> </strong></td>
                    <td colspan="" class="text-right"><strong> </strong></td>
                    <td colspan="" class="text-right"><strong> Supplier Balance</strong></td>
                    <td colspan="" class="text-right"><strong><?php echo number_format($tot_balance, 2, '.', ',');?> </strong></td>
                    <td colspan="" class="text-right"><strong> </strong></td>
                    <td class="text-right"><div id="tot_amount_div" style="font-weight:bold">0.00</div>
                      <input name="smp_amount" type="hidden" id="smp_amount" value="0"></td>
                    <td>&nbsp;</td>
                  </tr>
                </tfoot>
                
                
              </table>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-12">
          
          

        <div class="modal-footer" style="margin-bottom:10px;">
          <input type="submit" class="btn btn-primary" value="Add Payements" name="add_payments" id="add_payments" onClick="insertPaymentsData();">
          <button id="reset" class="btn btn-danger" type="button" onClick="javascript:window.location.reload(true);">Reset</button>
        </div>
      </div>
      <input name="sale_inv_discount_amount" type="hidden" id="sale_inv_discount_amount" value="0">
      <input name="sale_total" type="hidden" id="sale_total" value="0">
      <input name="sale_paid" type="hidden" id="sale_paid" value="0">
      <input name="sale_balance" type="hidden" id="sale_balance" value="0">
      <input name="rowCount" type="hidden" id="rowCount" value="<?php
echo $tmpcount;
?>">
      <input name="cost_total" type="hidden" id="cost_total" value="0">
      <input name="cus_credit_limit" type="hidden" id="cus_credit_limit" value="0">
      <input name="base_url" type="hidden" id="base_url" value="<?php
echo base_url();
?>">
      <input name="full_amount" type="hidden" id="full_amount">
    </form>
    <input name="" type="hidden" id="tmpVal">
    
    <!-- end: DYNAMIC TABLE PANEL --> 
    
    <!-- footer amount details -->
    
    <div style="margin-bottom: 0px; position: fixed; bottom: 0px; width: 1082px; z-index: 50000;" class="well well-sm" id="bottom-total">
      <table style="margin-bottom:0;" class="table table-bordered table-condensed totals">
        <tbody>
          <tr class="warning">
            <td class="credit_limit_td_class" style="float:right">Total Amount :&nbsp;<span style="min-width:70px; text-align:right" id="total_amount-txt" class="credit_limit_val pull-right">0.00</span></td>
            <td class="credit_limit_td_class" style="float:right">Available Amount :&nbsp;<span style="min-width:70px; text-align:right" id="avl_amount-txt" class="credit_limit_val pull-right">0.00</span></td>
            <td class="credit_limit_td_class" style="float:right"> Supplier Balance : <span style="min-width:70px; text-align:right" id="customer_balance" class="credit_limit_val pull-right"><?php echo number_format($tot_balance, 2, '.', ',');?></span></td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <!-- end footer amount details --> 
    
  </div>
</div>
</div>
</body>


<!-- start: MAIN JAVASCRIPTS -->

<?php
$this->load->view("common/footer");
?>
<script src="<?php echo asset_url(); ?>js/jquery-ui.js" ></script> 
<script src="<?php echo asset_url(); ?>js/moment-with-locales.js"></script> 
<script type="text/javascript" src="<?php echo asset_url(); ?>js/bootstrap-datetimepicker.js"></script> 
<script type="text/javascript" src="<?php echo asset_url(); ?>js/bootbox.min.js"></script> 
<script type="text/javascript" src="<?php echo asset_url(); ?>js/accounting.js"></script> 
<script type="text/javascript" src="<?php echo asset_url(); ?>js/accounting.min.js"></script> 
<!-- end: MAIN JAVASCRIPTS --> 
<script type="text/javascript" src="<?php echo asset_url(); ?>js/jquery.dataTables.min.js"></script> 
<script type="text/javascript" src="<?php echo asset_url(); ?>js/dataTables.bootstrap.min.js"></script> 


<script type="text/javascript" src="<?php echo asset_url();?>js/accounting.js"></script>
<script type="text/javascript" src="<?php echo asset_url();?>js/accounting.min.js"></script>

<!-- end: MAIN JAVASCRIPTS -->

<!-- start: JAVASCRIPTS REQUIRED FOR THIS PAGE ONLY VALIDATION-->

<!--<script src="<?php echo asset_url();?>js/collect_cash.js"></script>-->

<!-- end: JAVASCRIPTS REQUIRED FOR THIS PAGE ONLY  VALIDATION-->

<script>
$("#checkAll").click(function() {
    $('input:checkbox').not(this).prop('checked', this.checked);
});

$('#sale_pymnt_amount').keyup(function(){
	$('#avl_amount-txt').text(this.value);
	});
$('.checkbox').bind('change', function(e) {
    if (!e.target.checked) {
        var id_num;
        var str = e.target.name;
        if (str) {
            str = str.replace('row_c[', '');
            str = str.replace('][collection][]', '');
            id_num = str;
        }
        $('#amount_' + id_num).val('0');
        calculateTotalAmount();
    } else {
        var pay_amount = $('#sale_pymnt_amount').val();
        var arr = $('.added_amount'),
            sum = 0;
        $.each(arr, function() {
            sum += parseFloat($('#' + this.id).val()) || 0;
        });
        var id_num;
        var str = e.target.name;
        if (str) {
            str = str.replace('row_c[', '');
            str = str.replace('][collection][]', '');
            id_num = str;
        }
        var has_to_pay = $('#balance_amount_' + id_num).val();
        var balance_to_continue = pay_amount - sum;
        if (balance_to_continue >= has_to_pay) {
            $('#amount_' + id_num).val(has_to_pay);
        } else if (balance_to_continue > 0) {
            $('#amount_' + id_num).val(balance_to_continue);
        } else {
            $('#' + e.target.id).prop('checked', false);
        }
        calculateTotalAmount();
    }
    if (false == $(this).prop("checked")) {
        $("#select_all").prop('checked', false);
    }
    if ($('.checkbox:checked').length == $('.checkbox').length) {
        $("#select_all").prop('checked', true);
    }
});
$('input:text').click(function() {
    this.select();
});
$("#select_all").change(function(e) {
    if (e.target.checked) {
        var pay_amount = $('#sale_pymnt_amount').val();
        $(".checkbox").prop('checked', function(index) {
            var arr = $('.added_amount'),
                sum = 0;
            $.each(arr, function() {
               // alert(this.value);
                sum += parseFloat(this.value) || 0;
            });
            var id_num;
            var str = $(".checkbox")[index].name;
           // alert(str);
            if (str) {
                str = str.replace('row_c[', '');
                str = str.replace('][collection][]', '');
                id_num = str;
            }
            var has_to_pay = $('#balance_amount_' + id_num).val();
            var balance_to_continue = pay_amount - sum;
            if (balance_to_continue >= has_to_pay) {
                //alert(1);
                $('#amount_' + id_num).val(has_to_pay);
                $('#' + $(".checkbox")[index].id).attr('checked', '');
                
            } else if (balance_to_continue > 0) {  //alert(1);
               //   alert(2);
                $('#amount_' + id_num).val(balance_to_continue);
                $('#' + $(".checkbox")[index].id).attr('checked', '');
            }
            calculateTotalAmount();
        });
    } else {
        var pay_amount = $('#sale_pymnt_amount').val();
        $(".checkbox").prop('checked', function(index) {
            var id_num;
            var str = $(".checkbox")[index].name;
            if (str) {
                str = str.replace('row_c[', '');
                str = str.replace('][collection][]', '');
                id_num = str;
            }
            $('#amount_' + id_num).val(0);
            $('#' + $(".checkbox")[index].id).removeAttr('checked');
            calculateTotalAmount();
        });
    }
});

function calculateTotalAmount() {
    var tot_amount = 0;
    var tot_visiting_charge = 0;
    $('input[name^="card_row"]').each(function() {
        var id = $(this).val();
        var amount_fld = "#amount_" + id;
       // alert(amount_fld);
        tot_amount = tot_amount + parseFloat($(amount_fld).val());
        var visiting_charge_fld = "#visiting_charge_" + id;
        tot_visiting_charge = tot_visiting_charge + parseFloat($(visiting_charge_fld).val());
    });
    $("#tot_amount_div").text(convertToAmount(tot_amount));
    $("#total_amount-txt").text(convertToAmount(tot_amount));
    $("#avl_amount-txt").text(convertToAmount($('#sale_pymnt_amount').val() - tot_amount));

    $("#smp_amount").val((tot_amount));
    $("#tot_vist_charge_div").text(convertToAmount(tot_visiting_charge));
    $("#tot_amount_all").text(convertToAmount(tot_amount + tot_visiting_charge));
}

function convertToAmount(val) {
    var disval = val;
    return accounting.formatMoney(disval, "", 2, ",", ".");
}

function convertToAmount2Des(val) {
    var disval = val;
    return accounting.formatMoney(disval, "", 2, "", ".");
}

function changeAmount(row) {
    var collection_fld = "#collection_c_" + row;
    var amount_fld = "#amount_" + row;
    var amount_val = parseFloat($(amount_fld).val());
    if (amount_val) {
        var pay_amount = $('#sale_pymnt_amount').val();
        var arr = $('.added_amount'),
            sum = 0;
        $.each(arr, function() {
            sum += parseFloat(this.value) || 0;
        });
        sum -= amount_val;
        var has_to_pay = amount_val;
        var balance_to_continue = pay_amount - sum;
        if (balance_to_continue >= has_to_pay) {
            $(collection_fld).prop("checked", true);
        } else {
            $(collection_fld).prop("checked", false);
            $(amount_fld).val('0');
        }
    } else {
        $(collection_fld).prop("checked", false);
    }
    calculateTotalAmount();
}
$("form").submit(function(e) {
    return false;
});

function insertPaymentsData() {
     var smp_amount = $('#smp_amount').val();
     if(smp_amount!=''){
    
    $("#add_payments").val('Please wait...');
    $("#add_payments").prop("disabled", true);
    calculateTotalAmount();
    setTimeout(function() {
        var fields = $("#create_collection_form").serialize();
        var rowCount = $('#rowCount').val();
        var supplier_id = $('#supplier_id').val();
        var smp_amount = $('#smp_amount').val();
        if (!supplier_id) {
            bootbox.alert('Please select supplier', function() {
                $('#supplier_id').focus();
            });
            $("#add_payments").prop("disabled", false);
            $("#add_payments").val('Add Payments...');
        } else if (!smp_amount) {
            bootbox.alert('Please select pending invoice', function() {
                $('#add_item').focus();
            });
            $("#add_payments").prop("disabled", false);
            $("#add_payments").val('Add Payments...');
        } else if (rowCount != 0) {
            $.post("<?php
echo base_url();
?>supplier_multiple_payment/save_sasupplier_multiple_payment", fields).done(function(data) {
                var obj = jQuery.parseJSON(data);
                if (obj.error == 1) {
                    $('.alert-success').hide();
                    $('.alert-danger').show();
                    $(".errortxt").text(obj.disMsg);
                    window.scrollTo(500, 0);
                }
                if (obj.error == 0) {
                    window.scrollTo(500, 0);
                    $("#cash_collect > tbody").empty();
                    
                    displayNotice('page', 'Payment successfully added!'+obj.sale_id);
                    setTimeout(function() {
                        sendUrl = 'sale_multiple_payment';
                       // window.location.reload();
                       location.href = 'supplier_multiple_payment_print/'+obj.sale_id;
                    }, 1000);
                }
            });
            return false;
        } else {
            bootbox.alert('Please select invocie no.', function() {
                $('#add_item').focus();
            });
        }
    }, 1000);
     }
}

function change_customer(val) {
    $('body').modalmanager('loading');
    sendUrl = 'supplier_multiple_payment/manage/' + val;
    location.href = "<?php
echo base_url();
?>" + sendUrl;
}
<!--start:add items-->
<!--end:add items-->

function deleteCollectCashItem(row_id) {
    var val = '#row_c_' + row_id;
    $(val).remove();
    calculateTotalAmount();
}
$(document).ajaxStart(function() {
    $('#loader').show('fast');
});
$(document).ajaxStop(function() {
    $('#loader').hide('fast');
});

function setTmpVal(val) {
    $('#tmpVal').val(val);
}

function changePayingby(val) {
    $('.paying_by_details').hide();
    if (val == 'Credit Card') {
        $('#credit_card').show();
    }
    if (val == 'Cheque') {
        $('#cheque_dtls').show();
    }
    
    if (val == 'Bank Deposit') {
        $('#cheque_dtls').show();
        $('#cheque_no_text').hide();
    }
    
    if (val == 'Online Transfer') {
        $('#cheque_dtls').show();
        $('#cheque_no_text').hide();
    }
}


function load_customer_balance() {}

 var currentDate = new Date();
				
					$('#sale_pymnt_date_time').datetimepicker({
					defaultDate: currentDate,
					format:'YYYY/MM/DD'
				});
				
                </script>
</body>

<!-- end: BODY -->

</html>