<?php
  if(stripos($_SERVER['SCRIPT_NAME'],"/admin/")===false?false:true){	
  }elseif(!$isCustomer){
?>

<!-- NEW PAYMENT CUSTOMER SELECT MODAL -->
    	<div class="modal fade" id="paymentCustomerSelectModal" tabindex="-1" role="dialog" aria-labelledby="paymentCustomerSelectModal" aria-hidden="true">
          <div class="modal-dialog modal-sm">
            <div class="modal-content">
              <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                      <h4 class="modal-title" id="paymentCustomerSelectModalTitle">Select Customer</h4>
              </div>
              <div class="modal-body">
                     <select class="form-control combobox" id="paymentCustomerSelect">
                     <option></option>
                     <?php
										 
                     	if ($salesman->ID == "JC" || $salesman->ID == "CC" || $salesman->ID == "ES") {
                     		$query = "SELECT * FROM CUSTOMER";
                     	}else{
                     		$query = "SELECT * FROM CUSTOMER WHERE Salesman LIKE '" . $salesman->ID . "'";
                     	}
                     	$result = mysqli_query($con, $query);
                     	while ($row = mysqli_fetch_array($result)) {
                     ?>
                     	<option value="<?= $row['AccountNumber'] ?>"><?= $row['AccountNumber'] . " - " . $row['Name'] . " - " . $row['City'] ?></option>
                     <?php
                     	}
                     ?>
                     </select>
	          </div>
              <div class="modal-footer">
	              <a id="newPaymentButton" class="btn btn-success">New Payment</a>
	              <br />
              </div>
                
            </div>
          </div>
        </div>
        <script type="text/javascript">
            $('#newPaymentButton').on('click', function(){
                var accountNumber = $('#paymentCustomerSelect').val();
                if(accountNumber !== null || accountNumber !== ""){
                    window.location = "mod.php?p=payment&a=new&an=" + accountNumber;
                }
                
                    
            });
            
            
        </script>
        <!-- END NEW PAYMENT CUSTOMER SELECT MODAL -->
				
				<!-- CREDIT SEARCH MODAL -->
    	<div class="modal fade" id="creditSearchModal" tabindex="-1" role="dialog" aria-labelledby="creditSearchModal" aria-hidden="true">
          <div class="modal-dialog modal-sm">
            <div class="modal-content">
              <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                      <h4 class="modal-title" id="creditSearchModalTitle">Enter Credit Number</h4>
              </div>
              <div class="modal-body">
									
                     <input type="text" class="form-control" name="creditSearchNumber" id="creditSearchNumber" />
	          </div>
              <div class="modal-footer">
	              <a id="creditSearchButton" class="btn btn-success">Search</a>
	              <br />
              </div>
                
            </div>
          </div>
        </div>
        <script type="text/javascript">
            $('#creditSearchButton').on('click', function(){
                $.get('mod.php?p=payment&a=functions&f=getPaymentByCredit&number=' + $('#creditSearchNumber').val(), function(data){
										if(data == "false"){
											alert("This Credit Number was not found.");
											$('#creditSearchNumber').focus();
										}else{
											window.open('mod.php?p=payment&a=receipt&id=' + data,'_blank','width=400,height=1000,toolbar=no');
											$('#creditSearchModal').modal('toggle');
											$('#creditSearchNumber').val('');
										}
										
								});
                
            });
            
            
        </script>
        <!-- END CREDIT SEARCH MODAL -->
		<?php } ?>
		<?php
		
		  if(isset($_REQUEST['p']) && isset($_REQUEST['a'])){
			if($_REQUEST['p'] == "payment" && ($_REQUEST['a'] == "new" || $_REQUEST['a'] == "newmobile")){
		?>
		<!-- NEW PAYMENT SAVE MODAL -->
    	<div class="modal fade" id="newPaymentSaveModal" tabindex="-1" role="dialog" aria-labelledby="newPaymentSaveModal" aria-hidden="true">
          <div class="modal-dialog modal-lg">
            <div class="modal-content">
              <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                      <h4 class="modal-title" id="newPaymentSaveModalTitle">Payment Information</h4>
              </div>
              <div class="modal-body">
				<div class="row">
					<div class="col-sm-6">
					   <h4>Resumen de Pago</h4>
            <table class="table table-condensed">
                <thead>
                </thead>
                <tbody>
                    <tr>
                        <td>Subtotal</td>
                        <td id="paymentSubtotalConf">$0.00</td>
                    </tr>
                    <tr>
                        <td>Descuento</td>
                        <td id="paymentDiscountAmountConf">$0.00</td>
                    </tr>
                    <tr>
                        <td>IVU</td>
                        <td id="paymentTaxConf">$0.00</td>
                    </tr>
					<tr>
                        <td>Total de Creditos</td>
                        <td id="totalCreditsConf">$0.00</td>
                    </tr>
                    <tr>
                        <td>Total a Cobrar</td>
                        <td id="paymentTotalConf">$0.00</td>
                    </tr>
                    <tr>
                        <td>Total a Aplicarse</td>
                        <td id="paymentApplyTotalConf">$0.00</td>
                    </tr>
                </tbody>
                
            </table>
			
					</div>
    				<div class="col-sm-6">
					  <h4>Metodo de Pago - <span id="paymentTypeTitle">Regular Payment</span></h4>
					  <style>
						.leftHeader {
						  width: 150px;
						}
						
						
					  </style>
            <table class="table table-condensed">
			  
                <thead>
                </thead>
                <tbody>
					<tr>
                        <td class="leftHeader">Cheques</td>
                        <td>
							<table id="checksTable">
							  <tr>
								<td>
								  <div class="input-group">
									<div class="input-group-addon">$</div>
									<input style="width: 100px;" class="form-control" type="number" name="paymentCheckAmount" id="paymentCheckAmount" placeholder="Cantidad"/>
								  </div>
								</td>
								<td>
								  <div class="input-group">
									<input style="width: 90px; margin-left: 5px;" class="form-control" type="text" name="paymentCheckNumber" id="paymentCheckNumber" placeholder="Numero"/>
								  </div>
								</td>
							  </tr>
							</table>
                        </td>
                    </tr>
                    <tr>
                        <td id="cashHeader" class="leftHeader">Cash</td>
                        <td>
							<div id="cpdDateDiv" class="input-group">
                                
                                <input style="width: 175px;" class="form-control" type="text" name="cpdDate" id="cpdDate" min="<?= date('Y-m-d', strtotime('tomorrow')) ?>" placeholder="CPD Date"/>
                            </div>
                            <div id="cashInputDiv" class="input-group">
                                <div class="input-group-addon">$</div>
                                <input style="width: 100px;" class="form-control" type="number" name="paymentCashAmount" id="paymentCashAmount" placeholder="Cantidad"/>
                            </div>
                        </td>
                    </tr>
                    
                    <tr>
                        <td class="leftHeader">Falta por Cobrar</td>
                        <td id="paymentReminder">$0.00</td>
                    </tr>
                    <tr>
                        <td class="leftHeader">Total</td>
                        <td id="currPaymentTotal">$0.00</td>
                    </tr>
                </tbody>
            </table>
			<div class="form-group">
			  <label for="paymentNotes">Notes</label>
			  <textarea class="form-control" rows="3" id="paymentNotes"></textarea>
			</div>
			
					</div>
				</div>
	          </div>
              <div class="modal-footer">
	              <a id="cpdButton" class="btn btn-warning">CPD</a>
				  <button id="saveAndPrintButton" class="btn btn-success">Save</button>
	              <br />
              </div>
                
            </div>
          </div>
        </div>
        <script type="text/javascript">
			var cpd = false;
			var totalChecks = 0;
			var checkRow = 0;
			$('#cpdDateDiv').hide();
            $('#newPaymentButton').on('click', function(){
                var accountNumber = $('#paymentCustomerSelect').val();
                if(accountNumber != null || accountNumber != ""){
                    window.location = "mod.php?p=payment&a=new&an=" + accountNumber;
                }
            });
			$('#saveAndPrintButton').on('click', function(){
			  $('#saveAndPrintButton').unbind("click");
			  $('#saveAndPrintButton').prop("disabled", true);
			  submitPayment();  
			});
			$('#saveAndPrintNoPaymentButton').on('click', function(){
			  $('#saveAndPrintNoPaymentButton').unbind("click");
			  $('#saveAndPrintNoPaymentButton').prop("disabled", true);
			});
			$('#paymentCashAmount').on('keyup', function(e){
				if(e.keyCode == 13){
					if(!validate()){
						
					}else{
						 $('#saveAndPrintButton').focus();
					}
				  }
			  });
			$('#paymentCheckAmount').on('keyup', function(e){
				if(e.keyCode == 13){
				  if($('#paymentCheckAmount').val() == ""){
					$('#paymentCashAmount').focus();	
				  }else{
					$('#paymentCheckNumber').focus();
				  }
				}
			  });
			$('#paymentCheckNumber').on('keyup', function(e){
				if(e.keyCode == 13){
				  if(addCheck()){
					if(cpd){
					  $('#cpdDate').focus();
					  return;
					}
					if(!validate()){
					 $('#paymentCheckAmount').focus();
					}else{
					  $('#saveAndPrintButton').focus();
					}
				  }else{
					
				  }
				  
				}
			  });
			$( "#newPaymentSaveModal" ).on('shown.bs.modal', function(){
			  $('#paymentCheckAmount').focus();
			});
			$('#cpdButton').on('click',function(e){
			  
			  if(cpd){
				cpd = false;
				$('#cashHeader').text('Cash');
				$('#paymentTypeTitle').text('Regular Payment');
				$('#cpdDateDiv').hide();
				$('#cashInputDiv').show();
			  }else{
				cpd = true;
				$('#paymentCashAmount').val('');
				$('#cashHeader').text('CPD Date');
				$('#paymentTypeTitle').text('CPD Payment');
				$('#cpdDateDiv').show();
				$('#cashInputDiv').hide();
				$('#paymentCheckNumber').focus();
				
			  }
			  recalculate();
			});
			$('#cpdDate').on('change', function(e){
			  recalculate();
			  $('#saveAndPrintButton').focus();
			});
            function addCheck(){
			  
			  var checkNumber = $('#paymentCheckNumber').val();
			  if(checkNumber == ""){
				alert("Please enter a valid check number");
				$('#paymentCheckNumber').focus();
				return false;
			  }else{
				var checkAmount = parseFloat($('#paymentCheckAmount').val());
				totalChecks += checkAmount;
				if(totalChecks > parseFloat(totalToPay.toFixed(2))){
				  alert('Check exceeds amount to pay');
				  totalChecks -= checkAmount;
				  return;
				}
				$('#checksTable').append("<tr data-row=\"" + checkRow + "\" style=\"text-align: center;\"><td data-value=\"" + checkAmount + "\">" + moneyFormat(checkAmount) + "</td><td>" + checkNumber + "</td><td style=\"width: 30px;\"><button type=\"button\" onclick=\"deleteCheck(" + checkRow + ")\" class=\"btn btn-danger btn-xs\">Delete</button></td></tr>");
				checkRow++;
				$('#paymentCheckNumber').val('');
				$('#paymentCheckAmount').val('');
			   
				
				recalculate();
				return true;
			  }	
			}
			 $('#paymentCashAmount').on("keyup",function(){
			  recalculate();    
			});
			$('#paymentCashAmount').on("change",function(){
			  recalculate();    
			});
			$('#cpdDate').on('change', function(){
				recalculate();
			  });
			function deleteCheck(row){
			  var amount = parseFloat($('tr[data-row=' + row + '] > td').attr('data-value'));
			  $('tr[data-row=' + row + ']').remove();
			  totalChecks -=amount;
			  
			  recalculate();
			}
			function validate(){
			  var returnValue = true;
			  if(paymentReminder < 0.01 && paymentReminder > -0.01 && ((invoiceSubtotal+invoiceTax) > 0 || $('.paymentItem input.toggleCheckbox').length > 0)){
					var currDate = new Date();
					var selectedCPDDate = new Date($('#cpdDate').val());
					selectedCPDDate = new Date(selectedCPDDate.getTime() + selectedCPDDate.getTimezoneOffset()*60*1000);
					if(currDate > selectedCPDDate){
						return false;
					}
					if($('#cpdDate').val() == "" && cpd != false){
						return false;
					}else{
						return true;  
					}
					
				}else{
					return false;	
				}
			  
			}
			function retryReceipt(data){
			  var receiptRetryWin = window.open("mod.php?p=payment&a=receipt&id=" + data, data ,'toolbar=no,width=415,height=1000');
			  if(!receiptRetryWin || receiptRetryWin.closed || typeof receiptRetryWin.closed=='undefined') {
				  alert("Popup blocker detected!");
			  }else{
				  window.location = "index.php";	
			  }
			}
			function submitPayment(){
			  if(validate()){
					var submitData = recalculate(true);
					submitData = JSON.stringify(submitData)
					$.post("mod.php?p=payment&a=process" , {"data" : submitData } )
						.done(function( data ) {
						
						//var receiptWin = window.open("mod.php?p=payment&a=receipt&id=" + data, data ,'toolbar=no,width=415,height=1000');					
						//if(!receiptWin || receiptWin.closed || typeof receiptWin.closed=='undefined') {
						//	alert("Popup blocker detected!");
						//	$('#saveAndPrintButton').on('click', function(){
						//	retryReceipt(data);
						//	});
						//	$('#saveAndPrintButton').text('Reprint');	
						//	$('#saveAndPrintButton').removeAttr("disabled");
						//}else{
						//	window.location = "index.php";	
						//}
						
						window.location = "index.php";	
					});
			  }else{
					if(invoiceSubtotal == 0 || $('.paymentItem input.toggleCheckbox').length == 0){
						alert("Please select at least 1 invoice to pay.");
					}else{
						alert('Invalid Payment Info!');  
					}
			  }
			}
            
        </script>
        <!-- END NEW PAYMENT CUSTOMER SELECT MODAL -->
		
		
		
			<!-- NEW NON-PAYMENT REMINDER  MODAL -->
    	<div class="modal fade" id="newPaymentReminderModal" tabindex="-1" role="dialog" aria-labelledby="newPaymentReminderModal" aria-hidden="true">
          <div class="modal-dialog modal-lg">
            <div class="modal-content">
              <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                      <h4 class="modal-title" id="newPaymentReminderModalModalTitle">Payment Reminder</h4>
              </div>
              <div class="modal-body">
				<div class="row">
					<div class="col-sm-6">
					   <h4>Facturas Sobre 60 dias</h4>
            <table class="table table-condensed">
                <thead>
									<tr>
										<th>Invoice Number</th>
										<th>Date</th>
										<th>Days</th>
										<th>Total</th>
									</tr>
                </thead>
                <tbody id="invoiceOver60Days">
                   
                </tbody>
                
            </table>
			
					</div>
    				<div class="col-sm-6">
					  <h4><span id="newPaymentReminderModalReasonTitle">Razon de No Pago</span></h4>
					  <style>
						.leftHeader {
						  width: 150px;
						}
						
						
					  </style>
            <table class="table table-condensed">
			  
                <thead>
                </thead>
                <tbody>
					<tr>
                        <td class="leftHeader">Razon</td>
                        <td>
													<select id="selectPaymentReminderReason" class="form-control">
															<option value="A">Cliente no se encuentra</option>
															<option value="F">Pasar en otra Fecha</option>
															<option value="D">Cliente no tiene facturas con mas de 45 dias</option>
															<option value="O">Otros</option>
													</select>
                        </td>
                    </tr>
                    <tr id="nextVisitDateRow" style="display: none;">
                        <td  class="leftHeader">Fecha</td>
                        <td>
										<div id="" class="input-group">
                                
                                <input style="width: 175px;" class="form-control"  type="text" name="nextVisitDate" id="nextVisitDate" min="<?= date('Y-m-d', strtotime('tomorrow')) ?>" placeholder="Proxima Visita"/>
                            </div>
                            
                        </td>
                    </tr>
                    
                    
                    <tr>
                        <td class="leftHeader">Total Past Due</td>
                        <td id="totalPastDue">$0.00</td>
                    </tr>
                </tbody>
            </table>
			<div class="form-group">
			  <label for="paymentReminderNotes">Notes</label>
			  <textarea class="form-control" rows="3" id="paymentReminderNotes"></textarea>
			</div>
			
					</div>
				</div>
	          </div>
              <div class="modal-footer">
	             
				  <button id=""onclick="submitPaymentReminder()" class="btn btn-success">Save and Print</button>
	              <br />
              </div>
                
            </div>
          </div>
        </div>
        <script type="text/javascript">
					$(document).ready(function(){
							
							
							$('#continueToPayment').after(
									$('<button/>')
										.text('No Payment')
										.attr('onclick', "fillPaymentReminderModal()")
										.addClass('btn')
										.addClass('btn-danger')
										.css('margin-left','5px')
										.attr('id', 'saveAndPrintNoPaymentButton')
								);
						});
					function fillPaymentReminderModal(){
						var rows = $('.paymentItem');
							var invoices = Array();
							var totalPastDue = 0;
							for(var i =0; i< rows.length;i++){
								if(parseInt($(rows[i]).find('td:nth-child(3)').text().trim())>= 60){
								
									var invoice = {};
									invoice.Number = $(rows[i]).find('td:nth-child(4)').text().trim();
									invoice.Date = $(rows[i]).find('td:nth-child(1)').text().trim();
									invoice.Days = $(rows[i]).find('td:nth-child(3)').text().trim();
									invoice.Total = $(rows[i]).find('td:nth-child(8)').text().trim();
									$(rows[i]).find('td:nth-child(9) input').prop('checked', true);
									$(rows[i]).find('td:nth-child(10) input').val(0);
									totalPastDue += parseFloat(invoice.Total.replace("$",''));
									invoices.push(invoice);
									$('#invoiceOver60Days').append($('<tr/>').append(
																															$('<td/>').text(invoice.Number),
																															$('<td/>').text(invoice.Date),
																															$('<td/>').text(invoice.Days),
																															$('<td/>').text(invoice.Total)
																														 ));
								}
							}
							recalculate();
							$('#totalPastDue').text(moneyFormat(totalPastDue));
							$('#newPaymentReminderModal').modal('show');
					}
					$('#selectPaymentReminderReason').on('change', function(e){
							if($('#selectPaymentReminderReason').val() == "F"){
								$('#nextVisitDateRow').show();
								$('#nextVisitDate').focus();
							}else{
								$('#nextVisitDateRow').hide();
							}
						})
					
					var fp_reminder = $( "#nextVisitDate" ),
						now = moment().subtract(1,"seconds");
					
					fp_reminder.filthypillow( { 
						initialDateTime: function( ) {
						return moment();
						}
						/*,
					  minDateTime: function( ) {
						return moment().add(1,'days');
					  }*/ 
						
					} );
					fp_reminder.on( "focus", function( ) {
						
						fp_reminder.filthypillow( "show" );
						$('.fp-clock').hide();
						
					} );
					fp_reminder.on( "blur", function( ) {
						
						
						
					} );
					fp_reminder.on( "fp:save", function( e, dateObj ) {
						
						fp_reminder.val( dateObj.format( "MM/DD/YYYY" ) );
						fp_reminder.filthypillow( "hide" );
					} );
				
				function submitPaymentReminder(){
					
					var paymentReminderReason = $('#selectPaymentReminderReason').val();
					var paymentReminderNotes = $('#paymentReminderNotes').val().trim();
					
					if(paymentReminderReason == "O"){
						if(paymentReminderNotes === ""){
							alert('Por favor de llenar el campo de Notas');
							$('#paymentReminderNotes').focus();
							return;
						}				
					}else if(paymentReminderReason == "F"){
						var paymentReminderNextVisit = fp_reminder.filthypillow('getDate');
						now = moment().add(12,"hours");
						if(paymentReminderNextVisit < now){
							alert('Por favor escoja una fecha despues de hoy');
							fp_reminder.filthypillow('show');
							return;
						}
						
					}
					
					var submitData = recalculate(true);
					submitData.Type = "reminder";
					submitData.Reminder = {};
					submitData.Reminder.Reason = $('#selectPaymentReminderReason option[value=' + $('#selectPaymentReminderReason').val() + ']').text();
					submitData.Reminder.Notes = $('#paymentReminderNotes').val();
					submitData.Reminder.NextVisitDate = fp_reminder.filthypillow('getDate').format('YYYY-MM-DD');
					submitData = JSON.stringify(submitData)
					$.post("mod.php?p=payment&a=processReminder" , {"data" : submitData } )
						.done(function( data ) {
						
						var receiptWin = window.open("mod.php?p=payment&a=receipt&id=" + data, data ,'toolbar=no,width=415,height=1000');					
						if(!receiptWin || receiptWin.closed || typeof receiptWin.closed=='undefined') {
							alert("Popup blocker detected!");
							$('#saveAndPrintButton').on('click', function(){
							retryReceipt(data);
							});
							$('#saveAndPrintButton').text('Reprint');	
							$('#saveAndPrintButton').removeAttr("disabled");
						}else{
							window.location = "index.php";	
						}
					});
					
					
				}
        </script>
        <!-- END NEW PAYMENT CUSTOMER SELECT MODAL -->
		
		
		
		
		<!-- NEW INVOICE SAVE MODAL -->
    	<div class="modal fade" id="addNewInvoiceModal" tabindex="-1" role="dialog" aria-labelledby="addNewInvoiceModal" aria-hidden="true">
          <div class="modal-dialog modal-md">
            <div class="modal-content">
              <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                      <h4 class="modal-title" id="addNewInvoiceModalTitle">New Invoice (Manual Entry)</h4>
              </div>
              <div class="modal-body">
				<form class="form-horizontal">
				   <div class="form-group">
					 <label for="addNewInvoiceDate" class="control-label col-sm-4">Invoice Date</label>
					 <div class="col-sm-6">
					   <input class="form-control" id="addNewInvoiceDate" type="date"  />
					 </div>
				   </div>
				   <div class="form-group">
					 <label for="addNewInvoiceID" class="control-label col-sm-4">Invoice Number</label>
					 <div class="col-sm-6">
					   <input class="form-control" id="addNewInvoiceID" type="text" placeholder="Invoice Number" />
					 </div>
				   </div>
				   <div class="form-group">
					 <label for="addNewInvoiceSubtotal" class="control-label col-sm-4">Subtotal</label>
					 <div class="col-sm-6">
					   <input class="form-control" id="addNewInvoiceSubtotal" type="number" placeholder="Subtotal" />
					 </div>
				   </div>
				   <div class="form-group">
					 <label for="addNewInvoiceTax" class="control-label col-sm-4">IVU</label>
					 <div class="col-sm-6">
					   <input class="form-control" id="addNewInvoiceTax" type="number" placeholder="Tax" />
					 </div>
				   </div>
				   <div class="form-group">
					 <label for="addNewInvoiceTotal" class="control-label col-sm-4">Total</label>
					 <div class="col-sm-6">
					   <input readonly class="form-control" id="addNewInvoiceTotal" type="text" placeholder="Total" />
					 </div>
				   </div>
				</form>
	          </div>
              <div class="modal-footer">
	              <a id="saveAddNewInvoiceButton" class="btn btn-primary">Add</a>
	              <br />
              </div>
            </div>
          </div>
        </div>
        <script type="text/javascript">
		  $(document).ready(function(){
			$("#addNewInvoiceSubtotal").on("change",function(){
				var subtotal = parseFloat($(this).val());
				if(isNaN(subtotal))
				  subtotal = 0;
				var tax = parseFloat($('#addNewInvoiceTax').val());
				if(isNaN(tax))
				  tax = 0;
				var total = subtotal + tax;
				$('#addNewInvoiceTotal').val(moneyFormat(total));
			});
			$("#addNewInvoiceTax").on("change",function(){
				var subtotal = parseFloat($('#addNewInvoiceSubtotal').val());
				if(isNaN(subtotal))
				  subtotal = 0;
				var tax = parseFloat($(this).val());
				if(isNaN(tax))
				  tax = 0;
				var total = subtotal + tax;
				$('#addNewInvoiceTotal').val(moneyFormat(total));
			});
			$("#saveAddNewInvoiceButton").on("click", function(){
			  var invoiceDate = $('#addNewInvoiceDate').val();
			  invoiceDate = new Date(invoiceDate);
			  invoiceDate = new Date(invoiceDate.getTime() + invoiceDate.getTimezoneOffset()*60*1000);
			  var invoiceNumber = $('#addNewInvoiceID').val();
			  var invoiceSubtotal = parseFloat($('#addNewInvoiceSubtotal').val());
			  if(isNaN(invoiceSubtotal))
				invoiceSubtotal = 0;
			  var invoiceTax = parseFloat($('#addNewInvoiceTax').val());
			  if(isNaN(invoiceTax))
				invoiceTax = 0;
			  var invoiceTotal = invoiceSubtotal+invoiceTax;
			  var invoiceDue = new Date(invoiceDate.getTime() + 30 * 86400000);
			  var invoiceDays = Math.floor((new Date().getTime() - invoiceDate.getTime())/86400000)
			  
			  console.log(invoiceDate);
			  console.log(invoiceDue);
			  var tableItem = new Object();
			  tableItem.InvoiceDate = pad((invoiceDate.getMonth()+1),2) + "/" + pad(invoiceDate.getDate(),2) + "/" + invoiceDate.getFullYear();
			  tableItem.InvoiceDateAttr = invoiceDate.getFullYear() + "-" + pad((invoiceDate.getMonth()+1),2) + "-" + pad(invoiceDate.getDate(),2);
			  tableItem.DueDate = (invoiceDue.getMonth()+1) + "/" + invoiceDue.getDate() + "/" + invoiceDue.getFullYear();
			  tableItem.DueDateAttr = invoiceDue.getFullYear() + "-" + pad((invoiceDue.getMonth()+1),2) + "-" + pad(invoiceDue.getDate(),2);
			  tableItem.Days = invoiceDays;
			  tableItem.Number = invoiceNumber;
			  tableItem.Subtotal = invoiceSubtotal;
			  tableItem.Discount = 0;
			  tableItem.Tax = invoiceTax;
			  tableItem.Total = invoiceTotal;
			  tableItem.LineCount = $('.paymentItem:last').attr('data-line');
			  if(tableItem.LineCount == undefined){
				tableItem.LineCount = 0;
			  }
			  var tableRow = $('<tr></tr>').attr('data-line', tableItem.LineCount).addClass("paymentItem").attr('id', "row-" + tableItem.LineCount);
			  var rowData = $('<td></td>').append($('<span></span>').attr('data-value', tableItem.InvoiceDateAttr).attr('data-line', tableItem.LineCount).attr('id', "invoiceDate-" + tableItem.LineCount).text(tableItem.InvoiceDate));
			  tableRow.append(rowData);
			  rowData = $('<td></td>').append($('<span></span>').attr('data-value', tableItem.DueDateAttr).attr('data-line', tableItem.LineCount).attr('id', "dueDate-" + tableItem.LineCount).text(tableItem.DueDate));
			  tableRow.append(rowData);
			  rowData = $('<td></td>').append($('<span></span>').attr('data-value', tableItem.Days).attr('data-line', tableItem.LineCount).attr('id', "days-" + tableItem.LineCount).text(tableItem.Days));
			  tableRow.append(rowData);
			  rowData = $('<td></td>').append($('<span></span>').attr('data-value', tableItem.Number).attr('data-line', tableItem.LineCount).attr('id', "invoiceNumber-" + tableItem.LineCount).text(tableItem.Number));
			  tableRow.append(rowData);
			  rowData = $('<td></td>').append($('<span></span>').attr('data-value', tableItem.Subtotal).attr('data-line', tableItem.LineCount).attr('id', "invoiceSubtotal-" + tableItem.LineCount).text(moneyFormat(tableItem.Subtotal)));
			  tableRow.append(rowData);
			  rowData = $('<td></td>').append($('<span></span>').attr('data-value', tableItem.Discount).attr('data-line', tableItem.LineCount).attr('id', "invoiceDiscount-" + tableItem.LineCount).text(moneyFormat(tableItem.Discount)));
			  tableRow.append(rowData);
			  rowData = $('<td></td>').append($('<span></span>').attr('data-value', tableItem.Tax).attr('data-line', tableItem.LineCount).attr('id', "invoiceTax-" + tableItem.LineCount).text(moneyFormat(tableItem.Tax)));
			  tableRow.append(rowData);
			  rowData = $('<td></td>').append($('<span></span>').attr('data-value', tableItem.Total).attr('data-line', tableItem.LineCount).attr('id', "invoiceTotal-" + tableItem.LineCount).text(moneyFormat(tableItem.Total)));
			  tableRow.append(rowData);
			  rowData = $('<td></td>').append($('<span></span>').attr('data-line', tableItem.LineCount).attr('id', "invoiceCheck-" + tableItem.LineCount).append($('<input />').attr('data-line', tableItem.LineCount).addClass("toggleCheckbox").attr('type','checkbox').prop('data-switch-always', true)));
			  tableRow.append(rowData);
			 $('#paymentTableBody').append(tableRow);
			 $('.toggleCheckbox').checkboxpicker();
			});
			
		  });
			
        </script>
        <!-- END NEW PAYMENT CUSTOMER SELECT MODAL -->
	  <?php
			}
		  }
	  ?>
	  <?php
		  
		?>
		
        <script type="text/javascript">
		  $('#hideProcessedPaymentsInputDivCustomer').hide();
		  $('#hideProcessedPaymentsInputDivSalesman').hide();
		  $('#hideProcessedPaymentsInputDivDate').hide();
		  $('#selectCustomer').on('hide.bs.modal',function(){
			$('#hideProcessedPaymentsInputDivCustomer').hide();
		  });
		  $('#selectSalesman').on('hide.bs.modal',function(){
			$('#hideProcessedPaymentsInputDivSalesman').hide();
		  });
		  $('#selectDate').on('hide.bs.modal',function(){
			$('#hideProcessedPaymentsInputDivDate').hide();
		  });
			function showPaymentModal(which) {
			  if (which == "customer") {
				  $('#hideProcessedPaymentsInputDivCustomer').show();
				  $('#modalGoCustomer').unbind('click');
				  $('#modalGoCustomer').on('click', function(e) {
					  viewPayment('customer');
				  });
				  $('#selectCustomer').modal('toggle');
			  } else if (which == "salesman") {
				  $('#hideProcessedPaymentsInputDivSalesman').show();
				  $('#modalGoSalesman').unbind('click');
				  $('#modalGoSalesman').on('click', function(e) {
					  viewPayment('salesman');
				  });
				  $('#selectSalesman').modal('toggle');
			  } else if (which == "date") {
				  $('#hideProcessedPaymentsInputDivDate').show();
				  $('#modalGoDate').unbind('click');
				  $('#modalGoDate').on('click', function(e) {
					  viewPayment('date');
				  });
				  $('#selectDate').modal('toggle');
			  } else if (which == "salesmancashbox") {
				  $('#modalGoSalesman').unbind('click');
				  $('#modalGoSalesman').on('click', function(e) {
					  viewPayment('salesmancashbox');
				  });
				  $('#selectSalesman').modal('toggle');
			  }
				
			  }
			function showCPDModal(which){
			  if (which == "salesman") {
				  $('#modalGoSalesman').unbind('click');
				  $('#modalGoSalesman').on('click', function(e) {
					  viewCPD('salesman');
				  });
				  $('#selectSalesman').modal('toggle');
			  } else if (which == "date") {
				  $('#modalGoDate').unbind('click');
				  $('#modalGoDate').on('click', function(e) {
					  viewCPD('date');
				  });
				  $('#selectDate').modal('toggle');
			  }
			}
			function viewPayment(filter) {
			  var customer, salesman, fromDate, toDate, showProcessed;
			  if (filter == "customer") {
				  fromDate = $('#fromDateCustomer').val();
				  toDate = $('#toDateCustomer').val();
				  var customer = $('#customerSelect').val();
				  showProcessed = $('#hideProcessedPaymentsCustomer').prop('checked');
				  window.location = "mod.php?p=payment&a=admin.paymenthistory&for=" + filter + "&customer=" + customer + "&fromDate=" + fromDate + "&toDate=" + toDate + "&hideProcessed=" + showProcessed;
			  }else if (filter == "salesman") {
				  fromDate = $('#fromDateSalesman').val();
				  toDate = $('#toDateSalesman').val();
				  var salesman = $('#salesmanSelect').val();
				  showProcessed = $('#hideProcessedPaymentsSalesman').prop('checked');
				  window.location = "mod.php?p=payment&a=admin.paymenthistory&for=" + filter + "&salesman=" + salesman + "&fromDate=" + fromDate + "&toDate=" + toDate + "&hideProcessed=" + showProcessed;
			  }else {
				  fromDate = $('#fromDate').val();
				  toDate = $('#toDate').val();
				  showProcessed = $('#hideProcessedPaymentsDate').prop('checked');
				  window.location = "mod.php?p=payment&a=admin.paymenthistory&for=" + filter + "&fromDate=" + fromDate + "&toDate=" + toDate + "&hideProcessed=" + showProcessed;
			  }    		
			}
			function viewCPD(filter) {
			  var customer, salesman, fromDate, toDate;
			  if (filter == "salesman") {
				  fromDate = $('#fromDateSalesman').val();
				  toDate = $('#toDateSalesman').val();
				  var salesman = $('#salesmanSelect').val();
				  window.location = "mod.php?p=payment&a=admin.cpdpayments&for=" + filter + "&salesman=" + salesman + "&fromDate=" + fromDate + "&toDate=" + toDate;
			  }else {
				  fromDate = $('#fromDate').val();
				  toDate = $('#toDate').val();
				  window.location = "mod.php?p=payment&a=admin.cpdpayments&for=" + filter + "&fromDate=" + fromDate + "&toDate=" + toDate;
			  }    		
			}
        </script>
        <!-- END NEW PAYMENT CUSTOMER SELECT MODAL -->
		<!-- PAYMENT HISTOY DATE SELECT -->
		  <div class="modal fade" id="paymentHistorySelectDate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-sm">
			  <div class="modal-content">
				<div class="modal-header">
				  <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
				  <h4 class="modal-title">Select Date</h4>
				</div>
				<div class="modal-body">
				  <form>
				  <div class="form-group">
					  <label for="fromDate">From Date:</label>
						  <input class="form-control" type="date" name="paymentHistorySelectDateFrom" id="paymentHistorySelectDateFrom" value="<?= date("Y-m-01") ?>" />
				  </div>
				  <div class="form-group">
					  <label for="fromDate">To Date:</label>
						  <input class="form-control" type="date" name="paymentHistorySelectDateTo" id="paymentHistorySelectDateTo" value="<?= date("Y-m-d") ?>" />
				  </div>
				  </form>
				</div>
				<div class="modal-footer">
				  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				  <button type="button" id="paymentHistorySelectDateGo" class="btn btn-primary">Go</button>
				</div>
			  </div>
			</div>
		  </div>
		  <script type="text/javascript">
			function paymentHistoryDateSelect(){
			  $('#paymentHistorySelectDate').modal();
			}
			$('#paymentHistorySelectDateGo').on('click', function(){
			  var fromDate = $('#paymentHistorySelectDateFrom').val();
			  var toDate = $('#paymentHistorySelectDateTo').val();
			  var url = "mod.php?p=payment&a=paymenthistory&from=" + fromDate + "&to=" + toDate;
			  window.location = url;
				
			  
			});
			
		  </script>
		<!-- END PAYMENT HISTOY DATE SELECT -->
		
		