<script src="../js/jquery.mask.js" type="text/javascript"></script>
<div  class="panel panel-default">
  <div class="panel-heading form-inline">
  	<a class="btn btn-success" role="button" style="float: right;" href="#" download="Customers<?= "(" . date("m.d.Y") . ")" ?>.xls" href="#" onclick="return ExcellentExport.excel(this, 'customers', 'Customers');" data-toggle="tooltip" data-placement="left" title="Does not work with Internet Explorer">Export To Excel</a>
  	<div style="margin-right: 10px; float: right;">
  		<div class="input-group">
  		      <div id="clearButton" style="display: none;" class="input-group-addon" onclick="clearFilter()">
  		      	<span class="glyphicon glyphicon-remove" aria-hidden="true"></span></div>
  		      <input type="text"   class="form-control" name="filter" placeholder="Filter" value="" />
  		      <div class="input-group-addon" onclick="filter()">
  		      	<span class="glyphicon glyphicon-search" aria-hidden="true"></span></div>
  		    </div>
  		<button class="btn btn-primary" onclick="addCustomer()" >Add New Customer</button>
    </div>
    <h3 class="panel-title">Customers</h3>
    <small>Click on a row to edit the customer</small>

  </div>
  <div class="panel-body">
		<style>
			.emailCell {
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
		.cityCell {
			max-width: 120px;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
		.accountCell {
			max-width: 100px;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
		</style>
  <table class="table table-hover" id="customers">
    <thead>
    	<tr>
    		<th class="accountCell">Account Number</th>
    		<th>P</th>
    		<th>Name</th>
				<th>Terms</th>
    		<th>City</th>
    		<th>Email</th>
    		<!--<th>Last Login</th>-->
    		<th>Salesman</th>
    		<th>Phone</th>
    		<th>Contact</th>
				<th>Exempt</th>

    	</tr>
    </thead>
   <?php
   	$query = "SELECT CUSTOMER.*, UpdateDate FROM CUSTOMER LEFT JOIN CUSTOMER_UPDATE USING(AccountNumber) ORDER BY Name";
   	$result = mysqli_query($con, $query);
   	while ($row = mysqli_fetch_array($result)) {

   ?>
   		<tr onclick="editCustomer('<?= $row['AccountNumber'] ?>')">
   			<td class="accountCell"><?= $row['AccountNumber'] ?></td>
   			<td><?= $row['PriceLevel'] ?></td>
   			<td><?= $row['Name'] ?></td>
				<td><?= $row['Terms']==="0"?"COD":($row['Terms'] . " days") ?></td>
   			<td class="cityCell"><?= $row['City'] ?></td>
   			<td class="emailCell"><?= $row['Email'] ?></td>
   			<!-- <td><?= date("m/d/Y g:i a",strtotime($row['LastLogin'])) ?></td>-->
   			<?php
   				$salesman = new Salesman($row['Salesman']);

   			 ?>
   			<td><?= $salesman->Name ?></td>
   			<td style="white-space: nowrap;"><?= $row['Phone'] ?></td>
   			<td><?= $row['Contact'] ?></td>
				<td>
					<?php
					$tax1Exempt = false;
					$tax2Exempt = false;
					if($row['TaxID1'] != "" && strtotime($row['TaxIDExpiration1']) > time()){
						$tax1Exempt = true;
					}
					if($row['TaxID2'] != "" && strtotime($row['TaxIDExpiration2']) > time()){
						$tax2Exempt = true;
					}
					?>
					<?= ($tax1Exempt?"Y":"N") . " / " . ($tax2Exempt?"Y":"N") ?>
				</td>
   		</tr>
   <?php
   	}
    ?>
    </table>
  </div>
</div>


<div class="modal fade" id="AddEditCustomer">
  <div class="modal-dialog modal-lg">
    <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" id="AddEditTitle">Edit Customer</h4>
      </div>
      <div class="modal-body">
      	<form autocomplete="off">
				<div class="row">
					<div class="col-sm-6">
						<div class="form-group">
								<label for="CustomerAccount">AccountNumber</label>
								<input type="text" class="form-control" autocomplete="new-password" name="CustomerAccount" readonly id="CustomerAccount" placeholder="Account Number">
							</div>
					</div>
					<div class="col-sm-6">
						<div class="form-group">
								<label for="CustomerName">Name</label>
								<input type="text" autocomplete="new-password" class="form-control" name="CustomerName" id="CustomerName" placeholder="Name">
							</div>
					</div>
				</div>
				<ul class="nav nav-tabs">
					<li class="customerInfoMainTab customerInfoNavTab active"><a onclick="changeTab(this,'#GeneralTab');" href="#">General Information</a></li>
					<li class="customerInfoNavTab"><a onclick="changeTab(this,'#BillingTab');" href="#">Billing Information</a></li>
					<li class="customerInfoNavTab"><a onclick="changeTab(this,'#ShippingTab');" href="#">Shipping Information</a></li>
					<li class="customerInfoNavTab"><a onclick="changeTab(this,'#TaxTab');" href="#">Tax</a></li>
					<li class="customerInfoNavTab"><a onclick="changeTab(this,'#StatsTab');" href="#">Advanced</a></li>
				</ul>
				<br>
				<div class="row customerInfoTab" id="GeneralTab">
						<input type="hidden" id="isNew" name="isNew" value="" />
						<input id="username" style="display:none" type="text" name="fakeusernameremembered">
						<input id="password" style="display:none" type="password" name="fakepasswordremembered">
						<div class="col-sm-6">
								<div class="form-group">
								<label for="CustomerPhone">Phone</label>
								<input type="text" autocomplete="new-password" class="form-control" id="CustomerPhone" placeholder="">
							</div>
							<div class="form-group">
								<label for="CustomerContact">Contact</label>
								<input type="text" autocomplete="new-password" class="form-control" id="CustomerContact" placeholder="">
							</div>
							<div class="form-group">
								<label for="CustomerEmail">Email</label>
								<input type="text" autocomplete="new-password" class="form-control" id="CustomerEmail" placeholder="Email" autocomplete="off" value="">
							</div>
							<div class="form-group">
								<label for="CustomerPassword">Password</label>
								<input type="password" autocomplete="new-password" class="form-control" id="CustomerPassword" autocomplete="off" placeholder="Password">
							</div>
							<div class="form-group">
								<label for="CustomerComments">Comments</label>
								<textarea class="form-control" autocomplete="new-password" id="CustomerComments" name="CustomerComments"></textarea>
							</div>
						</div>
						<div class="col-sm-6">
								<div class="form-group">
								<label for="CustomerSalesman">Salesman</label>
								<select id="CustomerSalesman" autocomplete="new-password" class="form-control" name="CustomerSalesman">
									<option>--SELECT A SALESMAN--</option>
								<?php

									$query = "SELECT ID, FullName FROM SALESMAN ORDER BY FullName ASC";
									$result = mysqli_query($con, $query);
									while ($row = mysqli_fetch_array($result)) {
										?>
										<option value="<?= $row['ID'] ?>"><?= $row['ID'] . " - " . $row['FullName'] ?></option>
										<?php
									}

								 ?>
								</select>
							</div>
							<div class="form-group">
								<label for="CustomerPriceLevel">Price Level</label>
								<select id="CustomerPriceLevel" class="form-control" name="CustomerPriceLevel">
									<option value="A">Level A (Mayorista)</option>
									<option value="B">Level B (Mayorista + 20%)</option>
									<option value="C">Level C</option>
									<option value="D">Level D</option>
								</select>
							</div>
							<div class="form-group">
								<label for="CustomerCreditLimit">Credit Limit</label>
								<input type="text" class="form-control" id="CustomerCreditLimit" placeholder="">
							</div>
							<div class="form-group">
								<label for="CustomerDiscountDays">Discount Terms</label>
								<select id="CustomerDiscountDays" class="form-control" name="CustomerDiscountDays">
									<option value="-1">None</option>
									<option value="15">15 Days</option>
									<option value="30">30 Days</option>
									<option value="45">45 Days</option>
									<option value="60">60 Days</option>
									<option value="9999999">Open</option>
								</select>
							</div>
							<div class="form-group">
								<label for="CustomerTerms">Account Terms</label>
								<select id="CustomerTerms" class="form-control" name="CustomerTerms">
									<option value="0">COD</option>
									<option value="7">7 Days</option>
									<option value="15">15 Days</option>
									<option value="2/15 net 16">2 /15 Net 16 days</option>
									<option value="30">30 Days</option>
									<option value="45">45 Days</option>
									<option value="60">60 Days</option>
									<option value="90">90 Days</option>
									<option value="120">120 Days</option>
								</select>
							</div>
							<div class="checkbox">
										<label>
											<input id="active" name="active" type="checkbox"> <b>Active</b>
										</label>
							</div>
							<div class="checkbox">
										<label>
											<input id="disableCheck" name="disableCheck" type="checkbox"> <b>Disable Checks</b>
										</label>
							</div>
							<div class="checkbox">
										<label>
											<input id="sendOrderEmail" checked name="sendOrderEmail" type="checkbox"> <b>Send Order Email</b>
										</label>
							</div>
							<div class="form-group">
								<label for="LastLogin">Last Login</label>
								<p id="LastLogin" class="help-block">01/7/2015 7:33 pm</p>
							</div>
						</div>
				</div>
				<div class="row customerInfoTab" id="BillingTab">
						<div class="col-sm-6">
							<div class="form-group">
								<label for="CustomerAddress1">Address 1</label>
								<input autocomplete="new-password" type="text" class="form-control" id="CustomerAddress1" placeholder="Address 1">
							</div>
							<div class="form-group">
								<label for="CustomerAddress2">Address 2</label>
								<input type="text" class="form-control" id="CustomerAddress2" placeholder="Address 2">
							</div>
							<div class="form-group">
								<label for="CustomerCity">City</label>
								<input type="text" class="form-control" id="CustomerCity" placeholder="City">
							</div>
							<div class="form-group">
								<label for="CustomerState">State</label>
								<input type="text" class="form-control" id="CustomerState" placeholder="State">
							</div>
							<div class="form-group">
								<label for="CustomerZip">Zip Code</label>
								<input type="text" class="form-control" id="CustomerZip" placeholder="Zip">
							</div>
						</div>
						<div class="col-sm-6">

						</div>
				</div>
				<div class="row customerInfoTab" id="ShippingTab">
						<div class="col-sm-6">
							<div class="form-group">
								<label for="CustomerShipToAddress1">Address 1</label>
								<input type="text" class="form-control" id="CustomerShipToAddress1" placeholder="Address 1">
							</div>
							<div class="form-group">
								<label for="CustomerShipToAddress2">Address 2</label>
								<input type="text" class="form-control" id="CustomerShipToAddress2" placeholder="Address 2">
							</div>
							<div class="form-group">
								<label for="CustomerShipToCity">City</label>
								<input type="text" class="form-control" id="CustomerShipToCity" placeholder="City">
							</div>
							<div class="form-group">
								<label for="CustomerShipToState">State</label>
								<input type="text" class="form-control" id="CustomerShipToState" placeholder="State">
							</div>
							<div class="form-group">
								<label for="CustomerShipToZip">Zip Code</label>
								<input type="text" class="form-control" id="CustomerShipToZip" placeholder="Zip">
							</div>
						</div>
						<div class="col-sm-6">
							<button class="btn btn-primary" onclick="copyBillTo2ShipToAddress();return false;">Copy from Bill To</button>
						</div>
				</div>
				<div class="row customerInfoTab" id="TaxTab">
						<div class="col-sm-6">
							<div class="col-sm-6">
								<div class="form-group">
									<label for="CustomerTaxID1">Tax ID 1 (<?= getSetting('Tax1Name')['value'] ?>):</label>
									<input type="text" class="form-control" id="CustomerTaxID1" placeholder="Tax ID 1">
								</div>
							</div>
							<div class="col-sm-6">
								<div class="form-group">
									<label for="CustomerTaxID1Expiration">Expiration:</label>
									<input type="date" class="form-control" id="CustomerTaxID1Expiration" placeholder="">
								</div>
							</div>
							<div class="col-sm-6">
								<div class="form-group">
									<label for="CustomerTaxExempt1">Tax 1 Exempt:</label>
									<input type="checkbox" class="form-control" id="CustomerTaxExempt1" placeholder="">
								</div>
							</div>
						</div>
						<div class="col-sm-6">
							<div class="col-sm-6">
								<div class="form-group">
									<label for="CustomerTaxID2">Tax ID 2 (<?= getSetting('Tax2Name')['value'] ?>):</label>
									<input type="text" class="form-control" id="CustomerTaxID2" placeholder="Tax ID 2">
								</div>
							</div>
							<div class="col-sm-6">
								<div class="form-group">
									<label for="CustomerTaxID2Expiration">Expiration:</label>
									<input type="date" class="form-control" id="CustomerTaxID2Expiration" placeholder="">
								</div>
							</div>
							<div class="col-sm-6">
								<div class="form-group">
									<label for="CustomerTaxExempt2">Tax 2 Exempt:</label>
									<input type="checkbox" class="form-control" id="CustomerTaxExempt2" placeholder="">
								</div>
							</div>
						</div>
				</div>
				<div class="row customerInfoTab" id="StatsTab">
						<div class="col-sm-6">
							<button class="btn btn-primary" onclick="transferARToLoss();return false;">Send Account to Bad Debt Expense (Loss)</button>
						</div>
						<div class="col-sm-6">

						</div>
				</div>
				</form>
      </div>
      <div class="modal-footer">
      	<button type="button" class="btn btn-danger" id="deleteButton" onclick="deleteCustomer()" data-dismiss="modal">Delete</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="saveButton" onclick="saveCustomerInfo();">Save</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script type="text/javascript">
  function transferARToLoss(){
    if(prompt("**ALERT! IT IS HIGHLY RECOMMENDED TO REFRESH THE ACCOUNT RECEIVABLE LIST PRIOR TO MAKING THIS OPERATION.**\n\nAre you sure you want to transfer all the due invoices to the loss account? Please enter what's 2+2?")== "4"){
      $.post("mod.php", {
        "p" : "payment",
        "a" : "functions",
        "f" : "transferARToLoss",
        "an": $('#CustomerAccount').val()

      }, function(data){

        if(data == "true"){
          alert("Accounts Receivable Info Transfered");
        }else{
          alert("Error Transferring: \n" + data);
        }
      });
    }

  }
	function copyBillTo2ShipToAddress(){
		$('#CustomerShipToAddress1').val($('#CustomerAddress1').val());
		$('#CustomerShipToAddress2').val($('#CustomerAddress2').val());
		$('#CustomerShipToCity').val($('#CustomerCity').val());
		$('#CustomerShipToState').val($('#CustomerState').val());
		$('#CustomerShipToZip').val($('#CustomerZip').val());
	}
	function changeTab(nav_element, tab){
		$('.customerInfoNavTab').removeClass("active");
		$(nav_element).parent().addClass('active');
		$(".customerInfoTab").css("display", "none");
		$(tab).css("display", "");
	}
	$('#CustomerPhone').mask('(000) 000-0000');
	$('[name=filter]').on('keypress', function(e) {
		if (e.which == 13) {
			filter();
		}

	});
	$($('input[type=text]')[$('input[type=text]').length-1]).keydown(function(e){
			if(e.which == 13)
				$('#saveButton').click();

		});
	function clearFilter() {
		$('[name=filter]').val("");
		$('#clearButton').css('display', 'none');
		$('tr').css('display', '');

	}
	function filter() {
		var	name = $('[name=filter]').val();
		filterByName(name);
	}
	function filterByName(name) {
		$('#clearButton').css('display', '');
		for (var i = 0; i < $('tr').length; i++) {
			if (i != 0) {
				var result = $($('tr')[i]).text().toUpperCase().indexOf(name.toUpperCase());
				if (result < 0) {
					$($('tr')[i]).css('display', 'none');
				}else {
					$($('tr')[i]).css('display', '');
				}
			}
		}
	}
	function clearModal() {
		$('.customerInfoMainTab>a').click();
		$('#isNew').val("0");
		$('#CustomerAccount').val("");
		$('#CustomerAccount').prop("readonly", true);
		$('#CustomerName').val("");
		$('#CustomerCity').val("");
		$('#CustomerAddress1').val("");
		$('#CustomerAddress2').val("");
		$('#CustomerState').val("");
		$('#CustomerZip').val("");
		$('#CustomerEmail').val("");
		$('#CustomerPriceLevel').val("X");
		$('#CustomerPhone').val("");
		$('#CustomerContact').val("");
		$('#CustomerPassword').val("12345");
		$('#CustomerSalesman').val("");
		$('#CustomerComments').val("");
		$('#sendOrderEmail').prop('checked', false);
		$('#CustomerCreditLimit').val("0");
		$('#CustomerDiscountDays').val("45");
		$('#CustomerShipToAddress1').val("");
		$('#CustomerShipToAddress2').val("");
		$('#CustomerShipToCity').val("");
		$('#CustomerShipToState').val("");
		$('#CustomerShipToZip').val("");
		$('#CustomerTaxID1').val("");
		$('#CustomerTaxID1Expiration').val("");
		$('#CustomerTaxID2').val("");
		$('#CustomerTaxID2Expiration').val("");
		$('#CustomerTaxExempt1').prop("checked", false);
		$('#CustomerTaxExempt2').prop("checked", false);


		$('#LastLogin').text("");
		$('#active').prop('checked', true);
		$('#deleteButton').css('display', 'none');
	}
	function addCustomer() {
		<?php
			global $con;
			$query = "SELECT MAX(SUBSTRING(AccountNumber, 1,5))+1 NewAccountNumber FROM `CUSTOMER` WHERE AccountNumber < 90000";
			$result = mysqli_query($con, $query);
			$row = mysqli_fetch_array($result);

		?>
		clearModal();
		$('#isNew').val("1");
		$('#AddEditTitle').text("Add Customer");
		$('#deleteButton').css('display', 'none');
		$('#CustomerAccount').prop("readonly", null);
		$('#CustomerAccount').val('<?= $row[0] ?>');
		$('#AddEditCustomer').modal('toggle');
		$('#sendOrderEmail').prop('checked', true);

	}
	function editCustomer(AccountNumber) {
		clearModal();
		$.get("functions.php?action=getCustomerInfo&customer=" + AccountNumber, function(data){
		 	var customer;
			customer = JSON.parse(data);
			console.log(customer);
			var lastLogin = customer.LastLogin;
			if (lastLogin == null) {
				lastLogin = "Never";
			}else{
				lastLogin = new Date(lastLogin);
				lastLogin = lastLogin.format("M j, Y g:i a");
			}
			$('#isNew').val("0");
			$('#AddEditTitle').text("Edit Customer");
			$('#CustomerAccount').val(customer.AccountNumber);
			$('#CustomerName').val(customer.Name);
			$('#CustomerAddress1').val(customer.Address1);
			$('#CustomerAddress2').val(customer.Address2);
			$('#CustomerCity').val(customer.City);
			$('#CustomerState').val(customer.State);
			$('#CustomerZip').val(customer.ZipCode);
			$('#CustomerEmail').val(customer.Email);
			$('#CustomerPriceLevel').val(customer.PriceLevel);
			$('#CustomerDiscountDays').val(customer.DiscountDays);
			$('#CustomerPhone').val(customer.Phone);
			$('#CustomerContact').val(customer.Contact);
			$('#CustomerPassword').val("NOCHANGE");
			if(customer.SendOrderEmail == "1"){
				$('#sendOrderEmail').prop('checked', true);
			}else{
				$('#sendOrderEmail').prop('checked', false);
			}

			$('#CustomerComments').val(customer.Comments);
			$('#CustomerSalesman').val(customer.Salesman.ID);
			$('#active').prop('checked', parseInt(customer.Active));
			$('#disableCheck').prop('checked', parseInt(customer.DisableCheck));
			$('#CustomerCreditLimit').val(customer.CreditLimit);
			$('#LastLogin').text(lastLogin);
			$('#CustomerTerms').val(customer.Terms);


			$('#CustomerShipToAddress1').val(customer.ShipToAddress1);
			$('#CustomerShipToAddress2').val(customer.ShipToAddress2);
			$('#CustomerShipToCity').val(customer.ShipToCity);
			$('#CustomerShipToState').val(customer.ShipToState);
			$('#CustomerShipToZip').val(customer.ShipToZip);
			$('#CustomerTaxID1').val(customer.TaxID1);
			$('#CustomerTaxID1Expiration').val(customer.TaxIDExpiration1);
			$('#CustomerTaxID2').val(customer.TaxID2);
			$('#CustomerTaxID2Expiration').val(customer.TaxIDExpiration2);

			$('#CustomerTaxExempt1').prop("checked", (customer.TaxExempt1));
			$('#CustomerTaxExempt2').prop("checked", (customer.TaxExempt2));

			$('#AddEditCustomer').modal();
			$('#deleteButton').css('display', "");

		});
	}
	if(<?= isset($_REQUEST['autoedit'])?"true":"false" ?>){
		$(document).ready(function(){

			editCustomer("<?= $_REQUEST['autoedit'] ?>");

			});
	}


	function saveCustomerInfo() {

		var customerData = '{ \
		"AccountNumber" : "' + $('#CustomerAccount').val() + '", \
		"Name" : "' + $('#CustomerName').val() + '", \
		"City" : "' + $('#CustomerCity').val() + '", \
		"Phone" : "' + $('#CustomerPhone').val() + '", \
		"Contact" : "' + $('#CustomerContact').val() + '", \
		"Email" : "' + $('#CustomerEmail').val() + '", \
		"Password" : "' + $('#CustomerPassword').val() + '", \
		"PriceLevel" : "' + $('#CustomerPriceLevel').val() + '", \
		"Salesman" : "' + $('#CustomerSalesman').val() + '", \
		"Comments" : "' + $('#CustomerComments').val() + '", \
		"Active" : "' + $('#active').prop('checked') + '", \
		"IsNew" : "' + $('#isNew').val() + '", \
		"DisableCheck" : "' + $('#disableCheck').prop('checked') + '", \
		"CreditLimit" : "' + $('#CustomerCreditLimit').val() + '", \
		"DiscountDays" : "' + $('#CustomerDiscountDays').val() + '", \
		"SendOrderEmail" : ' + $('#sendOrderEmail').prop('checked') + ', \
		"Terms" : "' + $('#CustomerTerms').val() + '",\
		"Address1" : "' + $('#CustomerAddress1').val() + '", \
		"Address2" : "' + $('#CustomerAddress2').val() + '", \
		"State" : "' + $('#CustomerState').val() + '", \
		"ZipCode" : "' + $('#CustomerZip').val() + '", \
		"CustomerShipToAddress1" : "' + $('#CustomerShipToAddress1').val() + '", \
		"CustomerShipToAddress2" : "' + $('#CustomerShipToAddress2').val() + '", \
		"CustomerShipToCity" : "' + $('#CustomerShipToCity').val() + '", \
		"CustomerShipToState" : "' + $('#CustomerShipToState').val() + '", \
		"CustomerShipToZip" : "' + $('#CustomerShipToZip').val() + '", \
		"CustomerTaxID1" : "' + $('#CustomerTaxID1').val() + '", \
		"CustomerTaxID1Expiration" : "' + $('#CustomerTaxID1Expiration').val() + '", \
		"CustomerTaxID2" : "' + $('#CustomerTaxID2').val() + '", \
		"CustomerTaxID2Expiration" : "' + $('#CustomerTaxID2Expiration').val() + '",\
		"TaxExempt1" : "' + $('#CustomerTaxExempt1').prop('checked') + '",\
		"TaxExempt2" : "' + $('#CustomerTaxExempt2').prop('checked') + '"\
		}';
		console.log(customerData);
		if($('#CustomerAccount').val() == ""){
		  alert('Please enter an Account Number');
		  return;
		}
		if($('#CustomerPassword').val() == ""){
		  alert('Please enter a Password');
		  return;
		}
		if($('#CustomerCreditLimit').val() == ""){
		  alert('Please enter a Credit Limit');
		  return;
		}
		if($('#CustomerSalesman').val() == null){

		  alert('Please Select a Salesman');
		  return;
		}

		customerData = JSON.parse(customerData);
		$.post( "functions.php?action=saveCustomerInfo", customerData)
		  .done(function( data ) {
		  data = JSON.parse(data);
		  console.log(data);
		    if (data.result === true) {
		    	clearModal();
		    	$('#AddEditCustomer').modal('toggle')
		    	location.reload();
		    }else {
		    	alert("There has been an error saving the customer data.\r\n\r\nMySQL Error: " + data.error);
		    }
		  });
	}
	function deleteCustomer() {
		if (confirm("Are you sure you want to delete this customer from the database? This cannot be undone.")) {
			if (confirm("FINAL CHANCE! Are you sure you want to DELETE this customer from the database? This cannot be undone.")) {
				var AccountNumber = $('#CustomerAccount').val();
				$.post( "functions.php?action=deleteCustomer&accountNumber=" + AccountNumber, null)
					.done(function( data ) {
					data = $.parseJSON(data);
					console.log(data.result);
						if (data.result == true) {
							clearModal();
							$('#AddEditCustomer').modal('toggle')
							location.reload();
						}else {
							alert("There has been an error saving the customer data");
						}
					});
			}
		}
	}
	Date.prototype.format=function(e){var t="";var n=Date.replaceChars;for(var r=0;r<e.length;r++){var i=e.charAt(r);if(r-1>=0&&e.charAt(r-1)=="\\"){t+=i}else if(n[i]){t+=n[i].call(this)}else if(i!="\\"){t+=i}}return t};Date.replaceChars={shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],longMonths:["January","February","March","April","May","June","July","August","September","October","November","December"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],longDays:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],d:function(){return(this.getDate()<10?"0":"")+this.getDate()},D:function(){return Date.replaceChars.shortDays[this.getDay()]},j:function(){return this.getDate()},l:function(){return Date.replaceChars.longDays[this.getDay()]},N:function(){return this.getDay()+1},S:function(){return this.getDate()%10==1&&this.getDate()!=11?"st":this.getDate()%10==2&&this.getDate()!=12?"nd":this.getDate()%10==3&&this.getDate()!=13?"rd":"th"},w:function(){return this.getDay()},z:function(){var e=new Date(this.getFullYear(),0,1);return Math.ceil((this-e)/864e5)},W:function(){var e=new Date(this.getFullYear(),0,1);return Math.ceil(((this-e)/864e5+e.getDay()+1)/7)},F:function(){return Date.replaceChars.longMonths[this.getMonth()]},m:function(){return(this.getMonth()<9?"0":"")+(this.getMonth()+1)},M:function(){return Date.replaceChars.shortMonths[this.getMonth()]},n:function(){return this.getMonth()+1},t:function(){var e=new Date;return(new Date(e.getFullYear(),e.getMonth(),0)).getDate()},L:function(){var e=this.getFullYear();return e%400==0||e%100!=0&&e%4==0},o:function(){var e=new Date(this.valueOf());e.setDate(e.getDate()-(this.getDay()+6)%7+3);return e.getFullYear()},Y:function(){return this.getFullYear()},y:function(){return(""+this.getFullYear()).substr(2)},a:function(){return this.getHours()<12?"am":"pm"},A:function(){return this.getHours()<12?"AM":"PM"},B:function(){return Math.floor(((this.getUTCHours()+1)%24+this.getUTCMinutes()/60+this.getUTCSeconds()/3600)*1e3/24)},g:function(){return this.getHours()%12||12},G:function(){return this.getHours()},h:function(){return((this.getHours()%12||12)<10?"0":"")+(this.getHours()%12||12)},H:function(){return(this.getHours()<10?"0":"")+this.getHours()},i:function(){return(this.getMinutes()<10?"0":"")+this.getMinutes()},s:function(){return(this.getSeconds()<10?"0":"")+this.getSeconds()},u:function(){var e=this.getMilliseconds();return(e<10?"00":e<100?"0":"")+e},e:function(){return"Not Yet Supported"},I:function(){var e=null;for(var t=0;t<12;++t){var n=new Date(this.getFullYear(),t,1);var r=n.getTimezoneOffset();if(e===null)e=r;else if(r<e){e=r;break}else if(r>e)break}return this.getTimezoneOffset()==e|0},O:function(){return(-this.getTimezoneOffset()<0?"-":"+")+(Math.abs(this.getTimezoneOffset()/60)<10?"0":"")+Math.abs(this.getTimezoneOffset()/60)+"00"},P:function(){return(-this.getTimezoneOffset()<0?"-":"+")+(Math.abs(this.getTimezoneOffset()/60)<10?"0":"")+Math.abs(this.getTimezoneOffset()/60)+":00"},T:function(){var e=this.getMonth();this.setMonth(0);var t=this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/,"$1");this.setMonth(e);return t},Z:function(){return-this.getTimezoneOffset()*60},c:function(){return this.format("Y-m-d\\TH:i:sP")},r:function(){return this.toString()},U:function(){return this.getTime()/1e3}}

	</script>
