<?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']);
}
if($detect->isMobile()){
			
			header("Location: mod.php?p=payment&a=newmobile");
		}
?>
<!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>
		 
		 <link rel="stylesheet" href="css/jquery.filthypillow.css" type="text/css" />
		 <script src="js/jquery.filthypillow.min.js" type="text/javascript"></script>
		 <script src="js/moment.js" type="text/javascript"></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"/>
	<style>
		.tooltip-inner {
			white-space:pre-wrap;
		}
	</style>
   </head>
   <body>
       <?php
		include("navbar.php");
		
		
		
		if(!isset($_SESSION['setCustomer'])){
			$customer = new Customer($_REQUEST['an']);
		}else{
			$customer = new Customer($_SESSION['setCustomer']);	
		}
		//var_dump($customer);
	   ?>     
   <!-- 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();
	 //var_dump($invoices);
     $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>
	   <?php
	   if($customer->DiscountDays>0){
		?>
       <th style="width: 10%;">Discount</th>
	   <?php
	   }
	   ?>
       <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){
		$invoiceObj = new Invoice($invoice['InvoiceID']);
		//var_dump($invoiceObj);
        $days = round((time()-14400 - strtotime($invoice['InvoiceDate']))/(24*60*60),0);
		//$discount = ($days>45?0:round($invoice['Subtotal']*.05,2));
		$discount = 0;
		$invoiceTotal = $invoice['Subtotal']-$discount+$invoiceObj->TotalTax;
		$totalDue+= $invoiceTotal;
		$remarks = strtoupper($invoice['Reference']);
		$lockNet = false;
		$lockBC = false;
		if(stripos($remarks,"KYB") === false && stripos($remarks,"DHI") === false && stripos($remarks,"NIP") === false){
			$noDiscount = false;
		}else{
			$noDiscount = true;
		}
		if(stripos($remarks,"COD") === false && stripos($remarks,"C O D") === false && stripos($remarks,"C  O  D") === false && $invoice['Terms'] != "COD"){
			$cod = false;
		}else{
			$cod = true;
		}
		if(stripos($remarks,"SO/") === false && stripos($remarks,"SO-") === false && stripos($remarks,"NIP") === false){
				
		}else{
			$lockNet = true;
		}
		if(is_numeric(substr($invoice['InvoiceID'],0,1)) === true){
				
		}else{
			//BANK CHARGES
			$lockBC = true;
		}
		
		
    ?>
        <tr data-line="<?= $lineCount ?>" class="paymentItem" id="row-<?= $lineCount ?>">
			<td>
				<span data-value="<?= $invoiceObj->InvoiceDate ?>" data-line="<?= $lineCount ?>" class="" id="invoiceDate-<?= $lineCount ?>"><?= date("m/d/Y", strtotime($invoiceObj->InvoiceDate)) ?></span>
			</td>
			<td>
				<span data-line="<?= $lineCount ?>" class="" id="dueDate-<?= $lineCount ?>"><?= date("m/d/Y", strtotime($invoiceObj->DueDate)) ?></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;" ':"" ?> <?= ($lockBC)?'style="background-color: #F88379;" ':"" ?> class="" id="invoiceNumber-<?= $lineCount ?>"><a href="mod.php?p=invoice&a=view&id=<?= $invoice['InvoiceID'] ?>&key=<?= $invoiceObj->getTokenKey() ?>" target="_blank"><?= $invoice['InvoiceID'] ?></a></span>
				<?php
				if(isset($invoice['Reasons'])){
					?>
				<a href="#" data-toggle="tooltip" title="<?= $invoice['User'] . " applied " . $invoice['Overpayment'] . "\n" . $invoice['Reasons'] ?>"><span class="badge">i</span></a><br>
				<?php }
				
				if($cod){
				?>
					<img src="img/cod_icon.jpg" style="width: 30px;"/>
				<?php
				}?>
			</td> 			
			<td> 				
				<span data-value="<?= $invoice['Subtotal'] ?>" data-line="<?= $lineCount ?>" class="" id="invoiceSubtotal-<?= $lineCount ?>"><?= moneyFormat($invoice['Subtotal']) ?></span>
			</td>
			<?php
				if($customer->DiscountDays>0){
			?>
            <td>
				<span data-value="<?= $discount ?>" data-line="<?= $lineCount ?>" class="" id="invoiceDiscount-<?= $lineCount ?>"><?= moneyFormat($discount) ?></span>
			</td>
			<?php
				}
			?>
			<td> 				
				<span data-value="<?= $invoiceObj->TotalTax ?>" data-line="<?= $lineCount ?>" class="" id="invoiceTax-<?= $lineCount ?>"><?= moneyFormat($invoiceObj->TotalTax) ?></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" <?= ($noDiscount)?'checked':'' ?> <?= ($lockNet)?"disabled checked":"" ?> <?= ($lockBC)?"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>
	   <?php
	   if($customer->DiscountDays>0){
		?>
	   <th style="width: 10%;">Discount</th>
	   <?php
	   }
	   ?>
	   <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){
		$days = ceil((time() - strtotime($credit['CreditDate']))/(24*60*60));
		if($days < 3){
			continue;
		}
		$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="selectAutoInvoices">Auto</button>
			<button class="btn btn-primary" id="selectAllInvoices">All</button>
			<button class="btn btn-primary" id="clearSelection">Clear</button>
        </div>
        <div>
            <h4>Payment Summary</h4>
            <table class="table table-condensed">
                <thead>
                </thead>
                <tbody>
                    <tr>
                        <td>Subtotal</td>
                        <td id="paymentSubtotal">$0.00</td>
                    </tr>
					<?php
					if($customer->DiscountDays>0){
					?>
					
                    <tr>
                        <td>
                            <div class="form-inline">
                                Discount
                                <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>
					<?php
					}
					?>
                    <tr>
                        <td>IVU</td>
                        <td id="paymentTax">$0.00</td>
                    </tr>
					<tr>
                        <td>Credit Subtotal</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 = "<?= $customer->AccountNumber ?>";
	var disableCheck = "<?= $customer->DisableCheck ?>";
	var daysLimit = <?= $customer->DiscountDays ?>;
	var discountLimit = <?= "11.5" ?>;
    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;
	
	
	var fp = $( "#cpdDate" ),
	    now = moment().subtract(1,"seconds");
		
		fp.filthypillow( { 
		  initialDateTime: function( ) {
			return moment();
		  }//,
		 // minDateTime: function( ) {
		//	return moment().add(1,'days');
		//  } 
		  
		} );
		fp.on( "focus", function( ) {
			
		  fp.filthypillow( "show" );
		  $('.fp-clock').hide();
		  
		} );
		fp.on( "blur", function( ) {
			
		  recalculate();
		  
		} );
		fp.on( "fp:save", function( e, dateObj ) {
			
		  fp.val( dateObj.format( "MM/DD/YYYY" ) );
		  fp.filthypillow( "hide" );
		  recalculate();
		} );
	
	
	
	
 	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.InvoiceID = $('#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));
        
		
       
		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;
		$('#paymentDiscountAmount').text(moneyFormat(invoiceDiscountAmt+creditDiscountAmt));
        $('#paymentTax').text(moneyFormat(invoiceTax+creditTax));
        $('#paymentApplyTotal').text(moneyFormat(totalApply));
        $('#paymentTotal').text(moneyFormat(totalToPay));
		$('#totalCredits').text(moneyFormat(creditSubtotal));
        
		paymentData.Summary = new Object();
		paymentData.Summary.AccountNumber = accountNumber;
		paymentData.Summary.Subtotal = invoiceSubtotal.toFixed(2);
		paymentData.Summary.Discount = (invoiceDiscountAmt+creditDiscountAmt).toFixed(2);
		paymentData.Summary.Tax = (invoiceTax+creditTax).toFixed(2);
		paymentData.Summary.TotalToPay = totalToPay.toFixed(2);
		paymentData.Summary.TotalToApply = totalApply.toFixed(2);
		paymentData.Summary.Credits = creditSubtotal.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){
			var date = fp.filthypillow('getDate')._d;
				
			date = date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate();
			console.log(date);
			
			paymentData.PaymentInformation.CPDDate = date;	
		}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 () {
		$('[data-toggle="tooltip"]').tooltip(); 
		$('[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 > discountLimit){
				$('#paymentDiscount').val(discountLimit);
			}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);
            }
        });
		$('#selectAutoInvoices').on('click', function(){
			$('.paymentItem input.toggleCheckbox').prop('checked', false);
			var data = recalculate(true)
			var balance = parseFloat(data.Summary.Credits) + parseFloat(data.Summary.Tax);
			var goal = parseFloat(prompt("Entre cantidad a pagar"));
			for(var i=0; i <= $('[id^=invoiceTotal-]').length; i++){
				var invoiceTotal = parseFloat($($('[id^=invoiceTotal-]')[i]).attr('data-value'));
				var thisInvoiceSubtotal = parseFloat($($('[id^=invoiceSubtotal-]')[i]).attr('data-value'));
				if(invoiceTotal > goal-balance){
					if(goal-balance > thisInvoiceSubtotal){
						$($('[id^=invoiceCheck-] input')[i]).prop('checked', true);
						$($('[id^=partialPayment-]')[i]).val(thisInvoiceSubtotal);
						balance += thisInvoiceSubtotal;
						balance = Math.round((balance)*100)/100;
						//alert(balance)
						continue;
					}else{
						$($('[id^=invoiceCheck-] input')[i]).prop('checked', true);
						$($('[id^=partialPayment-]')[i]).val(Math.round((goal-balance)*100)/100);
						balance = 0
						break;
					
					}
			   }else{
					balance += invoiceTotal;
					balance = Math.round((balance)*100)/100;
					//alert(balance)
					$($('[id^=invoiceCheck-] input')[i]).prop('checked', true);
					continue;
			   }
			}
			recalculate();
		});
		$('#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+creditDiscountAmt));
			$('#paymentTaxConf').text(moneyFormat(invoiceTax+creditTax));
			$('#totalCreditsConf').text(moneyFormat(creditSubtotal));
			$('#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>