<?php

include_once("connect.php");
include_once("session.php");

$isCustomer = $_SESSION['isCustomer'];
if ($isCustomer) {
	header("Location: index.php");
	exit();
}else {
	$salesman = new Salesman($_SESSION['SalesmanID']);
}

?>
<!DOCTYPE html>
 <html lang="en">
   <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
	 <meta name="viewport" content="width=device-width, initial-scale=1">
    
     <title><?= $config['CompanyName'] ?></title>
 
     <!-- Bootstrap -->
     <link href="css/bootstrap.min.css" rel="stylesheet">
     <link rel="stylesheet" href="css/bootstrap-combobox.css" />
 
     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
     <!--[if lt IE 9]>
       <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
       <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
       <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
           <!-- Include all compiled plugins (below), or include individual files as needed -->
           <script src="js/bootstrap.min.js"></script>
       	 <script src="js/bootstrap-combobox.js"></script>
         <script src="js/functions.js"></script>
           <script type="text/javascript">
             $(document).ready(function(){
              // $('.combobox').combobox();
               $('.toggleCheckbox').checkboxpicker();
       //        $('.grpline').css("width", "100px");
				
             });
           </script>
     <![endif]-->
	<link rel="stylesheet" href="css/styles.css"/>
   </head>
   <body>
       <?php
		include("navbar.php");
		$customer = new Customer($_REQUEST['an']);
	   ?>     
   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
     <div class="container " style="padding-top: 10px;">
     <div class="page-header">
       <h3>New Payment: <?= $customer->AccountNumber . " - " . $customer->Name . " <small>(" . $customer->City . ")</small>	" ?></h3>
     </div>
 </div>
     <?php
	 
     $invoices = $customer->getInvoices();
     $credits = $customer->getCredits();
     
	 if(isset($_REQUEST['prueba'])){
		
		var_dump($customer);
	 }
     ?>
    <div class="row">
        <div class="col-md-8">
            <span><h4>Facturas</h4></span>

    <table class="table table-condensed dataTable" id="paymentTable">

   <thead id="">
     <tr>
       <th style="width: 10%">Invoice Date</th>
       <th style="width: 10%;">Due Date</th>
       <th style="width: 6%;">Days</th>
	   <th style="width: 15%;">Invoice Number</th>
	   <th style="width: 10%;">Subtotal</th>
       <th style="width: 10%;">Discount</th>
       <th style="width: 6%">IVU</th>
       <th style="width: 10%">Total</th>
	   
       
	   <th style="width: 15%; min-width: 92px">Pay</th>
	   <th style="width: 15%; min-width: 92px">Partial Payment</th>
	   <th style="width: 10%; min-width: 92px">No<br>Disc</th>
     </tr>
   </thead>

	<tbody id="paymentTableBody">
	<?php 
	$dueDays = 30;
	$lineCount = 0;
	$totalDue = 0;
    foreach($invoices as $invoice){
        $days = ceil((time() - strtotime($invoice['InvoiceDate']))/(24*60*60));
		//$discount = ($days>45?0:round($invoice['Subtotal']*.05,2));
		$discount = 0;
		$invoiceTotal = $invoice['Subtotal']-$discount+$invoice['SalesTax'];
		$totalDue+= $invoiceTotal;
		$remarks = strtoupper($invoice['Reference']);
		$lockNet = false;
		if(stripos($remarks,"KYB") === false && stripos($remarks,"DHI") === false && stripos($remarks,"NIP") === false){
			$noDiscount = false;
		}else{
			$noDiscount = true;
		}
		if(stripos($remarks,"SO/") === false && stripos($remarks,"SO-") === false){
				
		}else{
			$lockNet = true;
		}
		
    ?>
        <tr data-line="<?= $lineCount ?>" class="paymentItem" id="row-<?= $lineCount ?>">
			<td>
				<span data-value="<?= $invoice['InvoiceDate'] ?>" data-line="<?= $lineCount ?>" class="" id="invoiceDate-<?= $lineCount ?>"><?= date("m/d/Y", strtotime($invoice['InvoiceDate'])) ?></span>
			</td>
			<td>
				<span data-line="<?= $lineCount ?>" class="" id="dueDate-<?= $lineCount ?>"><?= date("m/d/Y", strtotime($invoice['InvoiceDate']) + ($dueDays*24*60*60)) ?></span>
			</td>
			<td>
				<span data-line="<?= $lineCount ?>" class="" id="days-<?= $lineCount ?>"><?= $days ?></span>
			</td>
			<td>
				<span title="<?= $remarks ?>" data-remarks="<?= $remarks ?>" data-line="<?= $lineCount ?>" <?= ($noDiscount)?'style="background-color: #fff200;" ':"" ?> <?= ($lockNet)?'style="background-color: #00e600;" ':"" ?> class="" id="invoiceNumber-<?= $lineCount ?>"><?= $invoice['InvoiceNumber'] ?></span>
			</td> 			
			<td> 				
				<span data-value="<?= $invoice['Subtotal'] ?>" data-line="<?= $lineCount ?>" class="" id="invoiceSubtotal-<?= $lineCount ?>"><?= moneyFormat($invoice['Subtotal']) ?></span>
			</td>
            <td>
				<span data-value="<?= $discount ?>" data-line="<?= $lineCount ?>" class="" id="invoiceDiscount-<?= $lineCount ?>"><?= moneyFormat($discount) ?></span>
			</td>
			<td> 				
				<span data-value="<?= $invoice['SalesTax'] ?>" data-line="<?= $lineCount ?>" class="" id="invoiceTax-<?= $lineCount ?>"><?= moneyFormat($invoice['SalesTax']) ?></span>
			</td>
			<td> 	
				<span data-value="<?= $invoiceTotal ?>" data-line="<?= $lineCount ?>" class="" id="invoiceTotal-<?= $lineCount ?>"><?= moneyFormat($invoiceTotal) ?></span>
			</td> 			
			<td> 				
				<span data-line="<?= $lineCount ?>" class="" id="invoiceCheck-<?= $lineCount ?>"><input data-line="<?= $lineCount ?>" class="toggleCheckbox" type="checkbox" data-switch-always /></span>
			</td>
			<td>
				 <input data-line="<?= $lineCount ?>" type="text" class="form-control" id="partialPayment-<?= $lineCount ?>" name="partialPayment-<?= $lineCount ?>" placeholder="Amount"/>
			</td>
			<td>
				 <input data-line="<?= $lineCount ?>" type="checkbox" class="form-control" <?= ($lockNet)?"disabled checked":"" ?> id="noDiscount-<?= $lineCount ?>" name="noDiscount-<?= $lineCount ?>" />
			</td>
		</tr>
    <?php  
		$lineCount++;
	}
	 ?>
	</tbody>
	</table>
	
    <!--
	<input type="button" class="btn btn-primary" id="addNewInvoiceButton" value="Add New Invoice"/>
	-->
	
    <!-- Creditos -->
    <span><h4>Cr&eacute;ditos</h4></span>
            <table class="table table-condensed">
   <thead>
     <tr>
       <th style="width: 10%">Credit Date</th>
       <th style="width: 10%;">Credit Number</th>
       <th style="width: 15%; min-width: 92px">Refrerence</th>
	   <th style="width: 10%;">Subtotal</th>
	   <th style="width: 10%;">Discount</th>
	   <th style="width: 10%;">IVU</th>
	   <th style="width: 10%;">Total</th>
	   <th style="width: 15%;">Apply</th>
	   <th style="width: 10%;"></th>
     </tr>
   </thead>
	<tbody id="creditsTableBody">
	<?php 
	
	$lineCount = 0;
    foreach($credits as $credit){
		$creditSubtotal = $credit['Subtotal'];
		$creditDiscount = 0;
		$creditTax = $credit['SalesTax'];
		$creditTotal = $creditSubtotal-$creditDiscount+$creditTax;
		$totalDue+=$creditTotal;
    ?>
        <tr class="creditItem" data-line="<?= $lineCount ?>" id="row-<?= $lineCount ?>">
			<td>
				<span data-line="<?= $lineCount ?>" class="" id="creditDate-<?= $lineCount ?>"><?= date("m/d/Y", strtotime($credit['CreditDate'])) ?></span>
			</td>
			<td>
				<span data-line="<?= $lineCount ?>" class="" id="creditNumber-<?= $lineCount ?>"><?= $credit['CreditNumber'] ?></span>
			</td>
			<td>
				<span data-line="<?= $lineCount ?>" class="" id="creditReference-<?= $lineCount ?>"><?= $credit['Reference'] ?></span>
			</td>
			<td> 	
				<span data-line="<?= $lineCount ?>" data-value="<?= $creditSubtotal ?>" class="" id="creditSubtotal-<?= $lineCount ?>"><?= moneyFormat($creditSubtotal) ?></span>
			</td>
			<td> 	
				<span data-line="<?= $lineCount ?>" data-value="<?= $creditDiscount?>" class="" id="creditDiscount-<?= $lineCount ?>"><?= moneyFormat($creditDiscount) ?></span>
			</td>
			<td> 	
				<span data-line="<?= $lineCount ?>" data-value="<?= $creditTax?>" class="" id="creditTax-<?= $lineCount ?>"><?= moneyFormat($creditTax) ?></span>
			</td>
			<td> 	
				<span data-line="<?= $lineCount ?>" data-value="<?= $creditTotal?>" class="" id="creditTotal-<?= $lineCount ?>"><?= moneyFormat($creditTotal) ?></span>
			</td> 
			<td> 				
				<span id="creditCheckSpan-<?= $lineCount ?>"><input data-line="<?= $lineCount ?>" id="creditCheck-<?= $lineCount ?>" class="toggleCheckbox" type="checkbox" data-switch-always /></span>
			</td>
			<td>
				 <input data-line="<?= $lineCount ?>" type="checkbox" class="form-control" id="creditNoDiscount-<?= $lineCount ?>" name="creditNoDiscount-<?= $lineCount ?>" />
			</td>
		</tr>
    <?php  
		$lineCount++;
	}

	 ?>
	</tbody>
	</table> 
        </div>
    <div class="col-md-4" id="sidebar">
        <div>
            <button class="btn btn-primary" id="selectOlderThan60">60 Days</button>
			<button class="btn btn-primary" id="selectOlderThan45">45 Days</button>
			<button class="btn btn-primary" id="selectOlderThan30">30 Days</button>
			<button class="btn btn-primary" id="selectAllInvoices">All</button>
			<button class="btn btn-primary" id="clearSelection">Clear</button>
        </div>
        <div>
            <h4>Resumen de Pago</h4>
            <table class="table table-condensed">
                <thead>
                </thead>
                <tbody>
                    <tr>
                        <td>Subtotal</td>
                        <td id="paymentSubtotal">$0.00</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="form-inline">
                                Descuento
                                <div class="form-group">
                                    <div class="col-xs-6 input-group">
                                    
                                      <input class="form-control" id="paymentDiscount" name="paymentDiscount" max="10" type="number" value="0">
                                      <div class="input-group-addon">%</div>
                                    </div>
                                </div>
                            </div>
                            </td>
                        <td id="paymentDiscountAmount">$0.00</td>
                    </tr>
                    <tr>
                        <td>IVU</td>
                        <td id="paymentTax">$0.00</td>
                    </tr>
					<tr>
                        <td>Total de Creditos</td>
                        <td id="totalCredits">$0.00</td>
                    </tr>
                    <tr style="font-weight: bold;">
						
                        <td>Total a Cobrar</td>
                        <td id="paymentTotal">$0.00</td>
						
                    </tr>
                    <tr>
                        <td>Total a Aplicarse</td>
                        <td id="paymentApplyTotal">$0.00</td>
                    </tr>
                </tbody>
                
            </table>
            
            
        </div> 
	<button class="btn btn-primary" id="continueToPayment">Continue to Payment</button>
	<table class="" style="width: 50%; background-color: <?= ($totalDue >= $customer->CreditLimit)?"#ff4d4d":"#aaff80" ?>; border-radius: 5px; border: none; margin: 10px; padding: 15px;">
		<tr>
			<td style="padding: 5px;">Credit Limit</td>
			<td><?= moneyFormat($customer->CreditLimit) ?></td>
		</tr>
		<tr>
			<td style="padding: 5px;">Available Credit</td>
			<td><?= moneyFormat($customer->CreditLimit-$totalDue) ?></td>
		</tr>
		
	</table>
    </div>
<hr />
 <script type="text/javascript">
 	var salesmanID = "<?= $_SESSION['SalesmanID'] ?>";
	var accountNumber = "<?= $_REQUEST['an'] ?>";
	var disableCheck = "<?= $customer->DisableCheck ?>";
	var daysLimit = <?= $customer->DiscountDays ?>;
    var discountPercent = 0;
	var invoiceSubtotal = 0;
    var invoiceDiscountAmt = 0;
    var invoiceTax = 0;
	var invoiceTotal = 0;
	var creditSubtotal = 0;
    var creditDiscountAmt = 0;
    var creditTax = 0;
	var creditTotal = 0;
    var totalToPay = 0;
    var totalApply = 0;
	var totalCredits = 0;
	var cashPayment = 0;
	var checkPayment = 0;
	var cpdPayment = false;
	var cpdDate = null;
	var paymentReminder = 0;
	var paymentTotal = 0;
 	function recalculate(returnData = false){
		
		$('#paymentCheckAmount').prop('disabled',parseInt(disableCheck))
		$('#paymentCheckNumber').prop('disabled',parseInt(disableCheck))
		cpdPayment = cpd;
		
		if(cpdPayment && $('#checksTable tr:nth-child(n+2)').length > 0){
			$('#paymentCheckAmount').prop('disabled',true);
			$('#paymentCheckNumber').prop('disabled',true);
		}else if(parseInt(disableCheck)){
			
		}else {
			$('#paymentCheckAmount').prop('disabled',false);
			$('#paymentCheckNumber').prop('disabled',false);
		}
        invoiceSubtotal = 0;
        discountPercent = 0;
        invoiceDiscountAmt = 0;
        invoiceTax = 0;
		invoiceTotal = 0;
		creditSubtotal = 0;
		creditDiscountAmt = 0;
		creditTax = 0;
		creditTotal = 0;
        totalToPay = 0;
        totalApply = 0;
		totalCredits = 0;
		var paymentData = new Object();
		paymentData.Invoice = new Array();
		
		discountPercent = parseFloat($('#paymentDiscount').val())/100;
		if(isNaN(discountPercent)){
			discountPercent = 0;
		}
		var paymentRows = $('.paymentItem');
		for(var i=0;i < paymentRows.length;i++){
			var line = $(paymentRows[i]).attr('data-line');
			var row = new Object();
			row.Days = parseInt($('#days-' + line).text());
			row.Remarks = $('#invoiceNumber-' + line).attr('data-remarks');
			row.InvoiceNumber = $('#invoiceNumber-' + line).text();
			row.InvoiceDate = $('#invoiceDate-' + line).text();
			row.InvoiceDate = new Date(row.InvoiceDate);
			row.InvoiceDate = new Date(row.InvoiceDate.valueOf() + row.InvoiceDate.getTimezoneOffset() * 60000);
			row.InvoiceDate = row.InvoiceDate.getFullYear() + "-" + (row.InvoiceDate.getMonth()+1) + "-" + row.InvoiceDate.getDate();
			row.Subtotal = $($('#invoiceSubtotal-' + line));
			row.Discount = $($('#invoiceDiscount-' + line));
			row.Tax = $($('#invoiceTax-' + line));
			row.Total = $($('#invoiceTotal-' + line));
			row.Pay = $($('#invoiceCheck-' + line + ' input'));
			row.PartialPayment = $($('#partialPayment-' + line));
			row.NoDiscount = $($('#noDiscount-' + line));
			var originalTotal = parseFloat(row.Total.attr('data-value'));
			var subtotal = parseFloat(row.Subtotal.attr('data-value'));
			var tax = parseFloat(row.Tax.attr('data-value'));
			var partialPayment = parseFloat(row.PartialPayment.val());
			if(isNaN(partialPayment)){
				partialPayment = parseFloat(partialPayment);
			}
			var discount = 0;
			if(row.NoDiscount.prop('disabled')){
				row.Discount.attr('data-value', "0");
				row.Discount.text(moneyFormat(0));
			}else{
				if(row.Days > daysLimit){
					row.Discount.attr('data-value', "0");
					row.Discount.text(moneyFormat(0));
				}else if(row.NoDiscount.prop('checked')){
					row.Discount.attr('data-value', "0");
					row.Discount.text(moneyFormat(0));
				}else{
					discount = (subtotal*discountPercent);
					discount = parseFloat(discount.toFixed(2));
					
					row.Discount.attr('data-value', discount.toFixed(2));
					row.Discount.text(moneyFormat(discount));
				}
			}
			
			var total = parseFloat((subtotal-discount+tax).toFixed(2));
			row.Total.attr('data-value', total);
			row.Total.text(moneyFormat(total));
			var amountChange = false;
			if(originalTotal != total){
				amountChange = true;
			}
			if(row.Pay.prop('checked')){
				if(amountChange){
					partialPayment = total;
					row.PartialPayment.val(total.toFixed(2));	
				}
				if(partialPayment < total){
					if(partialPayment > subtotal){
						alert('Partial Payment is greater than the subtotal');
						$('#partialPayment-' + line).val(subtotal);
						partialPayment = subtotal;
					}
					invoiceSubtotal += partialPayment;	
				}else{
					invoiceSubtotal += subtotal;
					invoiceDiscountAmt += discount;
					invoiceTax += tax;
				}
				
			}
			
			
			if(row.Pay.prop('checked')){
				row.Discount = discount;
				row.NoDiscount = row.NoDiscount.prop('checked');
				row.PartialPayment = partialPayment;
				row.Subtotal = subtotal;
				row.Pay = row.Pay.prop('checked');
				row.Tax = tax;
				row.Total = total;
				paymentData.Invoice.push(row);
			}
			
		}
		
		invoiceTotal = invoiceSubtotal-invoiceDiscountAmt+invoiceTax;
		$('#paymentSubtotal').text(moneyFormat(invoiceSubtotal));
        $('#paymentDiscountAmount').text(moneyFormat(invoiceDiscountAmt));
        $('#paymentTax').text(moneyFormat(invoiceTax));
		
       
		paymentData.Credits = new Array();
        var checkedCreditRows = $('.creditItem');
        for(var i = 0;i < checkedCreditRows.length;i++ ){
            var line = $(checkedCreditRows[i]).attr('data-line');
			var subtotal = parseFloat($('#creditSubtotal-' + line).attr('data-value'));
			var tax = parseFloat($('#creditTax-' + line).attr('data-value'));
			var discount = subtotal * discountPercent;
			var total = parseFloat((subtotal-discount+tax).toFixed(2));
			
			var creditRow = new Object();
			
			
			if($('#creditNoDiscount-' + line).prop('checked')){
				discount =0;
				$('#creditDiscount-' + line).attr('data-value', 0);
				$('#creditDiscount-' + line).text(moneyFormat(0));
				$('#creditTotal-' + line).attr('data-value', subtotal+tax);
				$('#creditTotal-' + line).text(moneyFormat(subtotal+tax));
			}else{
				$('#creditDiscount-' + line).attr('data-value', discount.toFixed(2));
				$('#creditDiscount-' + line).text(moneyFormat(discount));
				$('#creditTotal-' + line).attr('data-value', total.toFixed(2));
				$('#creditTotal-' + line).text(moneyFormat(total));
			}

			if($("#creditCheck-" + line).prop('checked')){
				creditSubtotal += subtotal;
				creditDiscountAmt += discount;
				creditTax += tax;
				totalCredits += total;
				
				creditRow.CreditDate = $('#creditDate-' + line).text();
				creditRow.CreditDate = new Date(creditRow.CreditDate);
				creditRow.CreditDate = new Date(creditRow.CreditDate.valueOf() + creditRow.CreditDate.getTimezoneOffset() * 60000);
				creditRow.CreditDate = creditRow.CreditDate.getFullYear() + "-" + (creditRow.CreditDate.getMonth()+1) + "-" + creditRow.CreditDate.getDate();
				creditRow.CreditNumber = $('#creditNumber-' + line).text();
				creditRow.Reference = $('#creditReference-' + line).text();
				creditRow.Subtotal = subtotal;
				creditRow.Discount = discount.toFixed(2);
				creditRow.Tax = tax;
				creditRow.Total = total.toFixed(2);
				paymentData.Credits.push(creditRow);
			}
			
			
        }
        
        creditTotal = creditSubtotal-creditDiscountAmt+creditTax;
		
		totalApply = invoiceSubtotal+invoiceTax;
		totalToPay = invoiceTotal+creditTotal;
        $('#paymentApplyTotal').text(moneyFormat(totalApply));
        $('#paymentTotal').text(moneyFormat(totalToPay));
		$('#totalCredits').text(moneyFormat(creditTotal));
        
		paymentData.Summary = new Object();
		paymentData.Summary.AccountNumber = accountNumber;
		paymentData.Summary.Subtotal = invoiceSubtotal.toFixed(2);
		paymentData.Summary.Discount = (invoiceDiscountAmt).toFixed(2);
		paymentData.Summary.Tax = invoiceTax.toFixed(2);
		paymentData.Summary.TotalToPay = totalToPay.toFixed(2);
		paymentData.Summary.TotalToApply = totalApply.toFixed(2);
		paymentData.Summary.Credits = totalCredits.toFixed(2);
        
		
        //payment info
		
		if(cpdPayment){
			$('#paymentCheckAmount').prop('readonly',true);
			$('#paymentCheckAmount').val(totalToPay.toFixed(2));
		}else{
			$('#paymentCheckAmount').prop('readonly',false);
			$('#paymentCheckAmount').val('');
		}
        
         cashPayment = parseFloat($('#paymentCashAmount').val());
        //var checkPayment = parseFloat($('#paymentCheckAmount').val());
		 checkPayment = totalChecks;
        if(isNaN(cashPayment))
            cashPayment = 0;
        if(isNaN(checkPayment))
            checkPayment = 0;
         paymentReminder = totalToPay-cashPayment-checkPayment;
         paymentTotal = cashPayment + checkPayment;
        $('#paymentReminder').text(moneyFormat(paymentReminder));
        $('#currPaymentTotal').text(moneyFormat(paymentTotal));        
        
        paymentData.PaymentInformation = new Object();
		paymentData.PaymentInformation.Cash = cashPayment;
		paymentData.PaymentInformation.Check = checkPayment;
		paymentData.PaymentInformation.CheckDetail = new Array();
		var checks = $('#checksTable tr:not(:first)');
		for(var ii= 0; ii < checks.length; ii++){
			var checkRow = new Object();
			checkRow.Amount = $($(checks[ii]).children()[0]).attr('data-value');
			checkRow.Number = $($(checks[ii]).children()[1]).text();
			paymentData.PaymentInformation.CheckDetail.push(checkRow);
		}
		
		//CPD
		
		paymentData.PaymentInformation.CPD = cpdPayment;
		if(cpdPayment){
			paymentData.PaymentInformation.CPDDate = $('#cpdDate').val();	
		}else{
			paymentData.PaymentInformation.CPDDate = null;
		}
		
		//Notes
		paymentData.Notes = $('#paymentNotes').val();
		
		if(returnData){
			return paymentData;	
		}
		if(validate()){
			$('#saveAndPrintButton').removeAttr('disabled')
		}else{
			$('#saveAndPrintButton').attr('disabled', true);
		}
		
    }
    
    $(document).ready(function () {
		$('[id^=invoice] .toggleCheckbox').on('change', function(){
			var line = $(this).attr('data-line');
			var total = parseFloat($('#invoiceTotal-' + line).attr('data-value'));
			if($(this).prop('checked')){
				
				$('#partialPayment-' + line).val(total.toFixed(2));
			}else{
				var value = 0;
				$('#partialPayment-' + line).val(value.toFixed(2));
			}
			var remarks = $('#invoiceNumber-' + line).attr('data-remarks');
			if(remarks.indexOf("DHI") > -1 || remarks.indexOf("KYB") > -1 || remarks.indexOf("NIP") > -1){
				$('#noDiscount-' + line).prop('checked', true);
			}
			recalculate();
			
		});
		$('[id^=credit] .toggleCheckbox').on('change', function(){
			recalculate();
			
		});
		$('[name^=noDiscount-]').on('change', function(){
				
				var line = $(this).attr('data-line');
				var total = parseFloat($('#invoiceTotal-' + line).attr('data-value'));
				if($('#invoiceCheck-' + line + " input").prop('checked'))
					$('#partialPayment-' + line).val(total.toFixed(2));
				else
					$('#partialPayment-' + line).val("0.00");
				recalculate();
				
		});
		$('[name^=creditNoDiscount-]').on('change', function(){
				
				recalculate();
				
		});
        $('.paymentItem input').on("change", function(){
            recalculate(); 
        
        });
        $('.creditItem input').on("change", function(){
            recalculate(); 
        
        });
       
		$('#paymentDiscount').on('change', function(){
			var value = $('#paymentDiscount').val();
			if(value < 0){
				$('#paymentDiscount').val(0);
			}else if(value > 10){
				$('#paymentDiscount').val(10);
			}else if(isNaN(value)){
				$('#paymentDiscount').val(0);
			}
			recalculate();
		});
		$('#paymentDiscount').on('keyup', function(e){
			recalculate();
			if(e.keyCode == 13){
				$('#continueToPayment').focus();
			}
		});
        $('#selectOlderThan60').on('click', function(){
			$('.paymentItem input.toggleCheckbox').prop('checked', false);
            var paymentRows = $('.paymentItem input.toggleCheckbox');
            
            for(var i = 0;i < paymentRows.length;i++ ){
                var line = $(paymentRows[i]).attr('data-line');
                var days = parseInt($("#days-" + line).text());
                if(days>=60){
                   //$(paymentRows[i]).prop("checked", !$(paymentRows[i]).prop("checked"));
				   $(paymentRows[i]).prop("checked", true);
                }
            }
            
        });
		$('#selectOlderThan45').on('click', function(){
			$('.paymentItem input.toggleCheckbox').prop('checked', false);
            var paymentRows = $('.paymentItem input.toggleCheckbox');
            
            for(var i = 0;i < paymentRows.length;i++ ){
                var line = $(paymentRows[i]).attr('data-line');
                var days = parseInt($("#days-" + line).text());
                if(days>=45){
                   //$(paymentRows[i]).prop("checked", !$(paymentRows[i]).prop("checked"));
				   $(paymentRows[i]).prop("checked", true);
                }
            }
            
        });
		$('#selectOlderThan30').on('click', function(){
			$('.paymentItem input.toggleCheckbox').prop('checked', false);
            var paymentRows = $('.paymentItem input.toggleCheckbox');
            
            for(var i = 0;i < paymentRows.length;i++ ){
                var line = $(paymentRows[i]).attr('data-line');
                var days = parseInt($("#days-" + line).text());
                if(days>=30){
                   //$(paymentRows[i]).prop("checked", !$(paymentRows[i]).prop("checked"));
				   $(paymentRows[i]).prop("checked", true);
                }
            }
            
        });
		$('#selectAllInvoices').on('click', function(){
			$('.paymentItem input.toggleCheckbox').prop('checked', false);
            var paymentRows = $('.paymentItem input.toggleCheckbox');
            
            for(var i = 0;i < paymentRows.length;i++ ){
                $(paymentRows[i]).prop("checked", true);
            }
        });
		$('#clearSelection').on('click', function(){
            $('.paymentItem input.toggleCheckbox, .creditItem input.toggleCheckbox').prop('checked', false);
        });
		$('#continueToPayment').on('click', function(){
			$('#paymentSubtotalConf').text(moneyFormat(invoiceSubtotal));
			$('#paymentDiscountAmountConf').text(moneyFormat(invoiceDiscountAmt));
			$('#paymentTaxConf').text(moneyFormat(invoiceTax));
			$('#totalCreditsConf').text(moneyFormat(totalCredits));
			$('#paymentTotalConf').text(moneyFormat(totalToPay));
			$('#paymentApplyTotalConf').text(moneyFormat(totalApply));
			$('#newPaymentSaveModal').modal();
			
		});
		$('#addNewInvoiceButton').on('click', function(){
			$('#addNewInvoiceModal').modal();
		});
        var additionalOffset = 120;
        var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0)) - additionalOffset;
        $(window).scroll(function (event) {
            var y = $(this).scrollTop();
            //if y > top, it means that if we scroll down any more, parts of our element will be outside the viewport
            //so we move the element down so that it remains in view.
            if (y >= top) {
               var difference = y - top;
               $('#sidebar').css("top",difference);
			   $('#paymentHeading').css('top', difference);
           }
       });
    });
	
 </script>

   </body>
 </html>