<?php 
include("connect.php");
include("session.php");

$isCustomer = $_SESSION['isCustomer'];
if ($isCustomer) {
	header("Location: index.php");
	exit();
}else {
	$salesman = new Salesman($_SESSION['SalesmanID']);
}
 ?>
 <!DOCTYPE html>
 <html lang="en">
   <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
	 <meta name="viewport" content="width=device-width, initial-scale=1">
    
     <title><?= $config['CompanyName'] ?></title>
 
     <!-- Bootstrap -->
     <link href="css/bootstrap.min.css" rel="stylesheet">
     <link rel="stylesheet" href="css/bootstrap-combobox.css" />
 
     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
     <!--[if lt IE 9]>
       <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
       <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
       
       <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
           <!-- Include all compiled plugins (below), or include individual files as needed -->
           <script src="js/bootstrap.min.js"></script>
           <!--
           <script src="http://jsconsole.com/remote.js?FC169D2A-277F-4CB6-AAEC-5B69284D0069"></script>
           -->
       	 <script src="js/bootstrap-combobox.js"></script>
           <script type="text/javascript">
             $(document).ready(function(){
               
             });
           </script>
     <![endif]-->
	<link rel="stylesheet" href="css/styles.css"/>
   </head>
   <body>
       <?php include("navbar.php"); ?>     
   <!-- 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>Pickup Order</h3>
     </div>
 </div>
 <?php
 if (!$isCustomer) {
	$selectedCustomer = isset($_SESSION['pickupCustomer'])?$_SESSION['pickupCustomer']:'';
 	$sID = $salesman->ID;
 	//This IF will show salesman 25 all the customers (Salesman LIKE '%')
 	if ($sID === "25" || $sID === "99" || strtoupper($sID) === "PXX" || strtoupper($sID) === "AR" || strtoupper($sID) === "96") {
 		$sID = "%";
 	}
 	$query = "SELECT * FROM CUSTOMER WHERE Salesman LIKE '" . $sID . "' ORDER BY Name";
 	$result = mysqli_query($con, $query);
 ?>
 <div class="form-inline">
 	<label for="customerSelect">Customer:</label>
	<select <?= $selectedCustomer!=''?"readonly":'' ?> name="customer" id="customerSelect" class="form-control">
		<option value="-1">--Select a Customer--</option>
		<?php
			while ($row = mysqli_fetch_array($result)) {
		?>
				<option <?= $selectedCustomer==$row['AccountNumber']?"selected":'' ?> value="<?= $row['AccountNumber'] ?>"><?= $row['Name'] ?> - <?= $row['City'] ?></option>
	<?php
			}
	}
	?>
	</select>
	<input type="text" <?= $selectedCustomer!=''?"readonly":'' ?> id="custFilter" name="filter" class="form-control" placeholder="Name or Account Number" value="" />
	
</div>
 <table class="table">
   <thead>
     <tr>
       <th style="width: 15%">Item Number</th>
       <th style="width: 8%;">Line</th>
	   <th style="width: 30%;">Description</th>
       <th style="width: 10%">Order Number</th>
	   <th style="width: 8%;">Qty</th>
       <th style="width: 15%">Reason</th>
       <!--<th style="width: 5%"></th>-->
       <th style="width: 5%"></th>
     </tr>
   </thead>
	<tbody id="pickupTableBody">
	<?php 
	
	$lineCount = 0;
	$query = "SELECT * FROM PICKUP_CART WHERE SalesmanID = '" . $salesman->ID . "'";
	$result = mysqli_query($con, $query);
	while ($row = mysqli_fetch_array($result)) {
	?>
		<tr class="pickupItem" id="row-<?= $lineCount ?>">
			<td>
				<input type="text" disabled id="sku-<?= $lineCount ?>" data-line="<?= $lineCount ?>" class="form-control" value="<?= $row['SKU']; ?>">
			</td>
			<td>
				<input maxlength="3" disabled type="text" id="line-<?= $lineCount ?>" data-line="<?= $lineCount ?>" class="form-control" value="<?= $row['Line']; ?>"> 
			</td>
			<td>
				<span data-line="<?= $lineCount ?>" class="" id="desc-<?= $lineCount ?>"><?= getProductDescription($row['Line'], $row['SKU']); ?></span>
			</td>
			<td>
				<div class="input-group">
					<span class="input-group-addon" id="invNumSearch-' + lineCount + '"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></span>
					<input type="text" disabled id="orderNum-<?= $lineCount ?>" data-line="<?= $lineCount ?>" class="form-control" value="<?= $row['OrderID']; ?>">
				<input type="hidden" id="invNum-<?= $lineCount ?>" data-line="<?= $lineCount ?>" class="form-control" value="<?= $row['InvoiceNumber']; ?>">
				</div>
			</td> 			
			<td> 				
				<input type="number" disabled id="qty-<?= $lineCount ?>" data-line="<?= $lineCount ?>" class="form-control" value="<?= $row['Qty']; ?>">
			</td> 			
			<td> 				
				<select class="form-control" disabled data-line="<?= $lineCount ?>" id="reason-<?= $lineCount ?>"> 
					<option selected value="<?= $row['Reason'] ?>"><?= getReasonText($row['Reason']); ?></option> 				
				</select>
				<?php 
 					$warrantyReasonDisplay = ($row['Reason'] == "GAR")?"":"display: none;";
 				 ?>
				<select disabled style="<?= $warrantyReasonDisplay ?>" class="form-control" data-line="' + lineCount + '" id="warrantyReason-' + lineCount + '">\
 					<option selected value="<?= $row['WarrantyReason'] ?>"><?= getWarrantyReasonText($row['WarrantyReason']); ?></option>
 				
 				</select>
			</td>
			<!--
			<td> 	
				<button data-line="<?= $lineCount ?>" disabled id="save-<?= $lineCount ?>" class="btn btn-success btn-save" onclick="saveLine(0)">Save</button>
			</td>
			-->
			<td> 				
				<button data-line="<?= $lineCount ?>" class="btn btn-danger" onclick="deleteLine(<?= $lineCount ?>)">Delete</button> 				
				<input type="hidden" data-line="<?= $lineCount ?>" id="valid-<?= $lineCount ?>" name="true" value=""> 				
				<input type="hidden" data-line="<?= $lineCount ?>" id="id-<?= $lineCount ?>" name="" value="<?= $row['id']; ?>"> 			
			</td> 		
		</tr>
	<?php 
		$lineCount++;
	}

	 ?>
	</tbody>
	</table>
	<button class="btn btn-success" style="margin-left: 10px;" onclick="addNewLine()">Add New Item</button>
     	<form method="post" id="pickupForm" action="processPickup.php">
     		
     	
     	
     	
    
 <div class="form-group" style="width: 70%; float: left; margin-top: 10px; margin-left: 10px;">
 		
 		
 		<label for="pickupNotes">Pickup Notes</label>
 		<textarea name="pickupNotes" class="form-control" id="pickupNotes" style="resize: none; height: auto;"><?php
 				if (isset($_SESSION['pickupNotes'])) {
 					echo trim($_SESSION['pickupNotes']);
 				}
 			?></textarea>
 	</div>
 	
 <div class="form-group" style="width: 15%; float: right;">
 		<?php	
 			$PickupTicket = "";
 			if (isset($_SESSION['pickupTicket'])) {
 				$PickupTicket = trim($_SESSION['pickupTicket']);
 				
 			}
 			
 		
 		?>
 	<!--<label for="pickupTicket">Pickup Ticket</label>
 	<input type="text" maxlength="12" name="pickupTicket" style="width: 180px;" class="form-control" id="pickupTicket" value="<?= $PickupTicket ?>">-->
 	<label for="requestedBy">Requested By</label>
 	<input type="text" maxlength="30" name="requestedBy" style="width: 180px;" class="form-control" id="requestedBy" value="">
 	<label for="packageAmount">Bultos</label>
 	<input type="text" maxlength="2" style="width: 60px;" name="packageAmount" class="form-control" id="packageAmount">
	<label for="pickupVia">Via</label>
	<select style="width: 180px;" name="pickupVia" class="form-control" id="pickupVia">
		
		<option value="Global">Global</option>
		<option value="Vendedor">Vendedor</option>
	</select>
 	
 	<input type="hidden" name="customerNumber" class="form-control" id="customerNumber">
 	 <button class="btn btn-primary" style="float: right; margin-right: 10px; margin-top: 15px;" name="Submit" id="finishButton" value="true">Save and Print</button>
 </div>

 </form>
<hr />

<div class="modal fade" id="purchaseHistoryModal" tabindex="-1" role="dialog">
  <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">Order History For: <span id="purchaseHistoryModalSKUTitle"></span></h4>
      </div>
      <div class="modal-body">
        <table class="table">
			<thead>
				<tr>
					<th>Order ID</th>
					<th>Order Date</th>
					<th>E/T (Days)</th>
					<th>Amount Ordered</th>
					<th>Returnable</th>
					<th>Price</th>
					<th>Invoice Number</th>
					<th></th>
				</tr>
			</thead>
			<tbody id="purchaseHistoryModalTbody">
				
			</tbody>
		</table>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

 <script type="text/javascript">
	function fillPurchaseHistoryModal(Line, SKU, row){
		var customer = $('#customerSelect').val();
		if(customer == "-1"){
			alert("Please choose a customer first!");
			return;
		}
		$.get('functions.php?action=getOrderHistory&an=' + customer + '&sku=' + SKU + '&line=' + Line, function(data){
			data = JSON.parse(data);
			if(data.length > 0){
				$('#purchaseHistoryModalSKUTitle').text(Line + "-" + SKU);
				$('#purchaseHistoryModalTbody').html('');
				for(var i = 0; i < data.length; i++){
					var invNum = data[i].InvoiceNumber;
					var invNumText = invNum;
					var textToFill = data[i].ID;
					if(invNum == null){
						invNum = "0";
						invNumText = "Not on File";
					}
					var orderDate = new Date(data[i].Date);
					var todayDate = new Date();
					var timeElapsed = todayDate.getTime() - orderDate.getTime();
					var daysElapsed = Math.ceil(timeElapsed/(1000*60*60*24));
					var buttonStyle = "success";
					var buttonDisabled = "";
					if(daysElapsed >= 31){
						buttonStyle = "warning";
					}
					if(data[i].ReturnableQty < 1){
						buttonDisabled = "disabled";
						buttonStyle = "danger";
					}
					orderDate = orderDate.getMonth()+1 + "/" + orderDate.getDate() + "/" + orderDate.getFullYear();
					$('#purchaseHistoryModalTbody').append('<tr><td>' + data[i].ID + '</td><td>' + orderDate + '</td><td>' + daysElapsed + '</td><td>' + data[i].Qty + '</td><td>' + data[i].ReturnableQty + '</td><td>' + data[i].Price + '</td><td>' + invNumText + '</td><td><button ' + buttonDisabled + ' class="btn btn-' + buttonStyle + '" onclick="selectOrderFromHistory(' + row + ',\'' + textToFill + '\',\'' + invNum + '\', \'' + data[i].Qty + '\')">Select</button></td></tr>');
				}
				if(Line == "KYB")
						$('#purchaseHistoryModalTbody').append('<tr><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>Manual Entry</td><td><button class="btn btn-' + buttonStyle + '" onclick="selectOrderFromHistory(' + row + ',\'NRA\',\'NRA\', \'99\')">Select</button></td></tr>');
				else
				$('#purchaseHistoryModalTbody').append('<tr><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>Manual Entry</td><td><button class="btn btn-' + buttonStyle + '" onclick="selectOrderFromHistory(' + row + ',\'NOF\',\'NOF\', \'99\')">Select</button></td></tr>');
			}else{
				$('#purchaseHistoryModalSKUTitle').text(Line + "-" + SKU);
				$('#purchaseHistoryModalTbody').html('');
				$('#purchaseHistoryModalTbody').append('<tr><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>Manual Entry</td><td><button class="btn btn-' + buttonStyle + '" onclick="selectOrderFromHistory(' + row + ',\'NOF\',\'NOF\', \'99\')">Select</button></td></tr>');
				if(Line == "KYB")
						$('#purchaseHistoryModalTbody').append('<tr><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>Manual Entry</td><td><button class="btn btn-' + buttonStyle + '" onclick="selectOrderFromHistory(' + row + ',\'NRA\',\'NRA\', \'99\')">Select</button></td></tr>');
				else
					$('#purchaseHistoryModalTbody').append('<tr><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>Manual Entry</td><td><button class="btn btn-' + buttonStyle + '" onclick="selectOrderFromHistory(' + row + ',\'NOF\',\'NOF\', \'99\')">Select</button></td></tr>');
				
			}
			$('#purchaseHistoryModal').modal('show');
			
		});
		
	}
	function selectOrderFromHistory(row,text, invNum, maxQty = 1){
		var promptText = "";
		if(text == "NOF" || text == "NRA"){
			while(promptText === ""){
				promptText = prompt("Numero de Factura");
				text = promptText;
				invNum = promptText;	
			}
			
				
		}
		$('#orderNum-' + row).val(text);
		$('#invNum-' + row).val(invNum);
		$('#purchaseHistoryModal').modal('hide');
		$('#qty-' + row).attr('min','1');
		$('#qty-' + row).attr('max',maxQty);
		$('#qty-' + row).focus();
	}
 	var salesmanID = "<?= $_SESSION['SalesmanID'] ?>";
 	$('#pickupForm').submit(function(event) {
 		
 		$('#customerNumber').val($('#customerSelect').val());
 		var rows = $('tr.pickupItem').length;
 		console.log("rows:" + rows);
 		for (var i = 0; i < rows; i++) {
 			if (i == rows-1) {
				if($("#sku-" + i).val() == "")
					continue;
            }
 			if (!$($('#sku-' + i)).prop('disabled')) {
 				event.preventDefault();
 				alert("Please Save all the lines before continuing");
 				console.log(i);
 				
 				console.log($('#save-' + (i)).prop('disabled'));
 				return;
 			}else {
 				console.log('everything was saved');
 			}
  		}
 		var requestedBy = $('#requestedBy').val();
 		var packages = parseInt($('#packageAmount').val());
		var pickupVia = $('#pickupVia').val();
 		if($('#customerSelect').val() == "-1"){
 			event.preventDefault();
 			alert("Please select a customer");
 			$('#customerSelect').focus();
 		}else if (requestedBy.length === 0) {
 			event.preventDefault();
 			alert("Error! Enter the name of the person requesting the Pickup and Return Order");
 			$('#requestedBy').focus();
 		}else if (isNaN(packages) || packages.length === 0 || packages < 0) {
 			event.preventDefault();
 			alert("Error! Invalid Package amount entered, please enter a numeric value.");
 			$('#packageAmount').focus();
 		} else {
 			$('#finishButton').prop('disabled', true);
 			$('#pickupForm').submit();
 		}	
 	});
 	
 	
 	$('#pickupTicket').change(function() {
 		savePickupFields();
 	});
 	$('#pickupNotes').change(function() {
 		savePickupFields();
 	});
	$('#requestedBy').change(function() {
 		savePickupFields();
 	});
	$('#customerSelect').change(function() {
 		savePickupFields();
 	});
 	var lineCount = <?= $lineCount ?>;
	
 	function addNewLine() {
 		//console.log('new line');
		
 		$('#pickupTableBody').append('\
 		<tr class="pickupItem" id="row-' + lineCount + '">\
 			<td>\
 				<input type="text" id="sku-' + lineCount + '" data-line="' + lineCount + '" class="form-control" value="" />\
 			</td>\
 			<td>\
 				<select id="line-' + lineCount + '" data-line="' + lineCount + '" class="form-control">\
 				</select>\
 			</td>\
 			<td>\
 				<span data-line="' + lineCount + '" class="" id="desc-' + lineCount + '"></span>\
 			</td>\
 			<td>\
				<div class="input-group">\
					<span class="input-group-addon" id="invNumSearch-' + lineCount + '"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></span>\
					<input type="text" readonly id="orderNum-' + lineCount + '" data-line="' + lineCount + '" class="form-control" value="" />\
					<input type="hidden" id="invNum-' + lineCount + '" data-line="' + lineCount + '" class="form-control" value="" />\
				</div>\
 			</td>\
 			<td>\
				<input type="number" id="qty-' + lineCount + '" data-line="' + lineCount + '" class="form-control" value="" />\
 			</td>\
 			<td>\
 				<select class="form-control" data-line="' + lineCount + '" id="reason-' + lineCount + '">\
 					<option value="-1">--Select a Reason--</option>\
 				<?php 
 					$query = "SELECT * FROM PICKUP_REASON";
 					$result = mysqli_query($con, $query);
 					while ($row = mysqli_fetch_array($result)) {
 						echo("<option value=\"" . $row['Key'] . "\">" . $row['Value'] . "</option>\\");
 					}
 				 ?>
 				</select>\
				<select style="display: none;" class="form-control" data-line="' + lineCount + '" id="warrantyReason-' + lineCount + '">\
 					<option value="-1">--Select Warranty Reason--</option>\
 				<?php 
 					$query = "SELECT * FROM PICKUP_WARRANTY_REASON";
 					$result = mysqli_query($con, $query);
 					while ($row = mysqli_fetch_array($result)) {
 						echo("<option value=\"" . $row['Key'] . "\">" . $row['Value'] . "</option>\\");
 					}
 				 ?>
 				</select>\
 			</td>\
 			<!--<td>\
 				<button data-line="' + lineCount + '" id="save-' + lineCount + '" class="btn btn-success btn-save" onclick="saveLine(' + lineCount + ')">Save</button>\
 			</td>-->\
 			<td>\
 				<button data-line="' + lineCount + '" class="btn btn-danger" onclick="deleteLine(' + lineCount + ')">Delete</button>\
 				<input type="hidden" data-line="' + lineCount + '" id="valid-' + lineCount + '" name="" value="" />\
 				<input type="hidden" data-line="' + lineCount + '" id="id-' + lineCount + '" name="" value="" />\
 			</td>\
 		</tr>');
 		var line = lineCount;
 		$('#sku-' + lineCount).on('change', function (e) {
 			getLines(line)
 		
 		});
 		$('#line-' + lineCount).on('change', function (e) {
 			writeDescription(line)
 		
 		});
 		$('#sku-' + lineCount).focus();
		addFormEvents(lineCount);
 		lineCount++;
		return lineCount-1;
		
 	}
	
 	function getLines(row) {
 		
 		$('#line-' + row).html("");
 		var currSKU = $("#sku-" + row).val().toUpperCase();
 		console.log('getting lines for:' + currSKU);
 		$.get('functions.php?action=getProductLines&sku='+ currSKU, function (data) {
 			if (data == "false") {
 				return false;
 			}else {
 				data = JSON.parse(data);
 				$.each(data, function(key, value) {   
 				     $('#line-' + row)
 				         .append($("<option></option>")
 				         .attr("value",value.Line)
 				         .text(value.Line)); 
 				     $('#sku-' + row).val(value.SKU);
					writeDescription(row); 
 				});
 			}
 			
 		});
 	}
	addNewLine()
	$('#custFilter').focus();
	$('#custFilter').on('keyup', function(e){
		if(e.keyCode == 13){
			$('#sku-0').focus();
		}
	});
	addEnterFocusEvent('#requestedBy', '#packageAmount');
	addEnterFocusEvent('#packageAmount', '#pickupVia');
	function addEnterFocusEvent(selector, selectorFocus){
		$(selector).on('keypress', function(e){
			if(e.keyCode == 13){
				e.preventDefault();
				$(selectorFocus).focus();
			}
		})
		
	}
	function addFormEvents(line){
		//$('#sku-' + line).unbind();
		$('#sku-' + line).on('keypress', function(e){
			if(e.keyCode == 13){
				if($(this).val() != ""){
					$('#line-' + line).focus();	
				}else{
					$('#requestedBy').focus();
				}
				
			}
		});
		$('#line-' + line).on('keypress', function(e){
			if(e.keyCode == 13){
				e.preventDefault();
				$('#orderNum-' + line).focus();
			}
		});
		$('#qty-' + line).on('keypress', function(e){
			if(e.keyCode == 13){
				$('#reason-' + line).focus();
			}
		});
		$('#qty-' + line).on('change', function(e){
			var maxQty = $('#qty-' + line).attr('max');
			maxQty = parseInt(maxQty);
				if(parseInt($('#qty-' + line).val()) > maxQty){
					alert('The max limit for this item is ' + maxQty);
					$('#qty-' + line).val(maxQty);
					$('#qty-' + line).focus();
				}
		});
		$('#invNum-' + line).on('keypress', function(e){
			if(e.keyCode == 13){
				if($('#orderNum-' + line).val() == ""){
					fillPurchaseHistoryModal($('#line-' + line).val(), $('#sku-' + line).val(), line);
				}else{
					$('#qty-' + line).focus();	
				}
				
			}
		});
		$('#reason-' + line).on('keypress', function(e){
			if(e.keyCode == 13){
				e.preventDefault();
				saveLine(line);
			}
		});
		$('#reason-' + line).on('change', function(e){
			var itemLine =$('#line-' + line).val();
			if($('#reason-' + line).val() == "GAR" && (itemLine == "KYB" || itemLine == "DHI")){
				$('#warrantyReason-' + line).show();
			}else{
				$('#warrantyReason-' + line).hide();
				saveLine(line);	
				
			}
			
		});
		$('#warrantyReason-' + line).on('change', function(e){
				saveLine(line);	
			
		});
		$('#orderNum-' + line).on('focus', function(e){
			if($('#orderNum-' + line).val() == ""){
				fillPurchaseHistoryModal($('#line-' + line).val(), $('#sku-' + line).val(), line);
			}
		});
		$('#invNumSearch-'+ line).on('click', function(e){
			fillPurchaseHistoryModal($('#line-' + line).val(), $('#sku-' + line).val(), line);
		});
		//if the Line code is DHI or KYB, hide the Defective option, else Show it.
		$('#reason-' + line).on('focus', function(e){
			if($('#line-' + line).val() == "DHI" || $('#line-' + line).val() == "KYB"){
				$('#reason-' + line + ' option[value="DEF"]').hide();
			}else{
				$('#reason-' + line + ' option[value="DEF"]').show();
			}
		});
	}
	/*
	 *function addFormEvents(line){
		$('#sku-' + line).unbind();
		$('#sku-' + line).on('keypress', function(){
			if(e.keyCode == 13){
				$('#line-' + line).focus();
			}
		});
	}
	*/
 	function writeDescription(line) {
 		$('#desc-' + line).text('');
 		var currLine = $("#line-" + line).val().toUpperCase();
		$("#line-" + line).val(currLine)
 		var currSKU = $("#sku-" + line).val().toUpperCase();
 		$("#sku-" + line).val(currSKU);

 		
 		$.get('functions.php?action=getProductDescription&line='+ currLine +'&sku=' + currSKU, function (data) {
 			if (data == "false") {
 				$('#valid-' + line).val('false');
 				$('#sku-' + line).focus();
 				return false;
 				
 			}else {
 				$('#valid-' + line).val('true');
 				$('#desc-' + line).text(data);
 			}
 			
 		});
 	}
	function validateRow(row) {
		var sku = $("#sku-" + row).val();
		var invoice = $("#orderNum-" + row).val();
		var reasonVal = $("#reason-" + row).val();
		var qty = parseInt($("#qty-" + row).val());
		if (sku.length == 0) {
			alert("Please enter an Item Number (SKU)");
			$("#sku-" + row).focus();
			return false;
		} else if (isNaN(qty) || qty.length == 0 || qty < 0) {
			alert("Quantity is not valid");
			$("#qty-" + row).focus();
		} else if (invoice.length == 0) {
			alert("The Invoice Number cannot be empty.");
			$("#orderNum-" + row).focus();
			return false;
		}else if (invoice.length < 1 && (invoice != salesmanID)){
			alert("The Invoice Number is not valid");
			$("#orderNum-" + row).focus();
			return false;
		}else if (reasonVal == "-1") {
			alert("Please select a valid reason");
			$("#reason-" + row).focus();
			return false;
		}else {
			return true;	
		}
		
	}
	function validatePickup() {
		
	
	}
 	function saveLine(row) {
		
 		if (!validateRow(row)) {
 			return;
 		}
		$('#customerSelect').attr('readonly',true);
		$('#custFilter').attr('readonly',true);
		
 		var reasonVal = $("#reason-" + row).val();
 		var warrantyReason = $("#warrantyReason-" + row).val();
		if(warrantyReason == "-1"){
			warrantyReason = "";
		}
 		var request = $.get( "functions.php", { 	
 			action: "savePickupLine",
 			line: $("#line-" + row).val().toUpperCase(),
 			sku: $("#sku-" + row).val().toUpperCase(),
 			qty: $("#qty-" + row).val(),
 			invoice: $("#invNum-" + row).val(),
			order: $("#orderNum-" + row).val(),
 			reason: $("#reason-" + row).val(),
 			warrantyReason: warrantyReason
 			}).done(function( data ) {
 				data = JSON.parse(data);
 				console.log("data saved");
 				console.log(data);
 				if (data.result == "true") {
 					$("#id-" + row).val(data.id);
	 				$("#sku-" + row).attr('disabled', 'true');
	 				$("#line-" + row).attr('disabled', 'true');
	 				$("#qty-" + row).attr('disabled', 'true');
	 				$("#orderNum-" + row).attr('disabled', 'true');
	 				$("#reason-" + row).attr('disabled', 'true');
	 				$("#save-" + row).attr('disabled', 'true');
					$("#warrantyReason-" + row).attr('disabled', 'true');
 				}
 			});
 		addNewLine();
 		
 	}
 	function deleteLine(row) {
		
		if(lineCount == 1){
			$('#customerSelect').attr('readonly',false);
			$('#custFilter').attr('readonly',false);
		}
		lineCount--;
 		if ($("#id-" + row).val() == "") {
 			$("#row-" + row).remove();
 		}else{
	 		var request = $.get( "functions.php", { 	
	 			action: "deletePickupLine",
	 			id: $("#id-" + row).val(),
	 			
	
	 			
	 			}).done(function( data ) {
	 				
	 				if (data == "true") {
						 $("#row-" + row).remove();
	 				}else {
	 					alert("There has been an error deleting the item. Please refresh the page.");
	 				}
	 			});
 		}
 		
		$('[id^=sku-]:last').focus();
 	}
 	function savePickupFields() {
 		var request = $.get( "functions.php", { 	
 			action: "savePickupFields",
 			pickupNotes: $('#pickupNotes').val(),
			pickupCustomer: $('#customerSelect').val(),
 			requestedBy: $('#requestedBy').val()
 			}).done(function( data ) {
 				
 			});
 	}
 	
 	jQuery.fn.filterByText = function(textbox) {
 	    return this.each(function() {
 	        var select = this;
 	        var options = [];
 	        $(select).find('option').each(function() {
 	            options.push({value: $(this).val(), text: $(this).text()});
 	        });
 	        $(select).data('options', options);
 	        $(textbox).bind('change keyup', function() {
 	            var options = $(select).empty().data('options');
 	            var search = $.trim($(this).val());
 	            var regex = new RegExp(search,"gi");
 	            $.each(options, function(i) {
 	                var option = options[i];
 	                if(option.text.match(regex) !== null || option.value.match(regex) !== null) {
 	                    $(select).append(
 	                        $('<option>').text(option.text).val(option.value)
 	                    );
 	                }
 	            });
 	        });
 	    });
 	};
 	$('#customerSelect').filterByText($('#custFilter'));
 	$('#customerSelect').width($('#customerSelect').width())
 </script>

   </body>
 </html>