<?php
//ini_set("display_errors",1);
//error_reporting(E_ALL);
///include_once("connect.php");
//include_once("session.php");
//var_dump($_SESSION['SalesmanID']);
$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']);
		}
	?>
		<!-- 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 = [];
	 if(substr($customer->AccountNumber,-3) == "-00"){
		$query = "SELECT * FROM CUSTOMER WHERE AccountNumber LIKE '" . substr($customer->AccountNumber, 0,5) . "%' ORDER BY AccountNumber";
		$result = mysqli_query($con, $query);
		while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
			$chainCustomer = new Customer($row['AccountNumber']);
			$invoices = array_merge($chainCustomer->getInvoices(), $invoices);
		}
		//$invoices = sort($invoices);
		sort($invoices);
	 }else{
		$invoices = $customer->getInvoices();
	 }



	 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);
							$dateDays = $invoice['DeliveryDate'];
							if(!$dateDays){
								$dateDays = $invoice['InvoiceDate'];
							}
				      $days = round((time()-14400 - strtotime($dateDays))/(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,"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<0?0:$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>
			</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="20" type="number" value="0">
										  <div class="input-group-addon">%</div>
										</div>

									</div>
									<button class="btn btn-primary" id="btnAutoDiscount">Auto</button>
								</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 = <?= "10.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();
	// 	} );

	$('#btnAutoDiscount').click(function(){
		var discountedPayment = prompt("Cuanto te pagó");
		discountedPayment = parseFloat(discountedPayment);
		if(discountedPayment){
			paymentData = recalculate(true);
			var newDiscount = (paymentData.Summary.TotalToApply-discountedPayment)/paymentData.Summary.Subtotal;

			$('#paymentDiscount').val((newDiscount*100));
			$('#paymentDiscount').trigger('change');
		}



	});


 	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(Math.abs(partialPayment) < Math.abs(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 = new Date($('#cpdDate').val() + " 0:00:00");

			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){
					/* THIS REGION IS COMMENTED TO REMOVE THE PROTECTION AGAINST PARTIAL TAX PAYMENTS */
					// 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;
					//
					// }
					/* END OF REGION THAT IS COMMENTED TO REMOVE THE PROTECTION AGAINST PARTIAL TAX PAYMENTS */
					/* THIS REGION ALLOWS PARTIAL TAX PAYMENTS */
						{
							$($('[id^=invoiceCheck-] input')[i]).prop('checked', true);
							$($('[id^=partialPayment-]')[i]).val(Math.round((goal-balance)*100)/100);
							balance = 0
							break;
						}
						/* END OF REGION THAT ALLOWS PARTIAL TAX PAYMENTS */
			   }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>
