<?php
//die('test');
include("session.php");
include("connect.php");
global $con;
$pricePlanMode = false;
$isCustomer = false;

if (isset($_SESSION['isCustomer'])) {
	$isCustomer = $_SESSION['isCustomer'];
}else {
	header("Location: login2.php");
	return;
}
$language = "ES";

if ($isCustomer) {
	$customer = new Customer($_SESSION['AccountNumber']);	
	$language = $customer->Language;
} else {
	if (isset($_SESSION['SalesmanID'])) {
		$salesman = new Salesman($_SESSION['SalesmanID']);	
		$language = $salesman->Language;
		$pricePlanMode = $_SESSION['pricePlanMode'];
	}else {
		header("Location: login.php");
		return;
	}
	
}
if(isset($_REQUEST['sku'])){
	if($_REQUEST['sku'] == "" && $_REQUEST['line'] == "" && $_REQUEST['group'] == ""){
		header("Location: index.php");
		return;
	}
}
$_SESSION['LastSearch'] = array(
			"SKU" => "",
			"Line" => "",
			"Group" => "",
			"WC" => "",
			"Page" => ""
);

	

?>
 
 <!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">-->
     <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
	 <meta http-equiv="cache-control" content="max-age=0" />
	 <meta http-equiv="cache-control" content="no-cache" />
	 <meta http-equiv="expires" content="0" />
	 <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
	 <meta http-equiv="pragma" content="no-cache" />
	 
     <title><?= $config['CompanyName'] ?></title>
 
     <!-- Bootstrap -->
     <link href="css/bootstrap.min.css" rel="stylesheet">
     
     <!-- Icons -->
		<link rel="apple-touch-icon" sizes="57x57" href="img/apple-icon-57x57.png">
		<link rel="apple-touch-icon" sizes="60x60" href="img/apple-icon-60x60.png">
		<link rel="apple-touch-icon" sizes="72x72" href="img/apple-icon-72x72.png">
		<link rel="apple-touch-icon" sizes="76x76" href="img/apple-icon-76x76.png">
		<link rel="apple-touch-icon" sizes="114x114" href="img/apple-icon-114x114.png">
		<link rel="apple-touch-icon" sizes="120x120" href="img/apple-icon-120x120.png">
		<link rel="apple-touch-icon" sizes="144x144" href="img/apple-icon-144x144.png">
		<link rel="apple-touch-icon" sizes="152x152" href="img/apple-icon-152x152.png">
		<link rel="apple-touch-icon" sizes="180x180" href="img/apple-icon-180x180.png">
		<link rel="icon" type="image/png" sizes="192x192"  href="img/android-icon-192x192.png">
		<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
		<link rel="icon" type="image/png" sizes="96x96" href="img/favicon-96x96.png">
		<link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png">
		<link rel="manifest" href="img/manifest.json">
		<meta name="msapplication-TileColor" content="#ffffff">
		<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
		<meta name="theme-color" content="#ffffff">
     
     
     <link rel="stylesheet" href="css/bootstrap-combobox.css?date=13" />
 
     <!-- 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>
       <script src="js/functions.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?date=13"></script>
       	 <script src="js/bootstrap-combobox.js?date=13"></script>
           <script src="js/select2.full.min.js"></script>
     <![endif]-->
	<link rel="stylesheet" href="css/styles.css"/>
	<link rel="stylesheet" href="css/select2.min.css"/>
   </head>
   <body>
<?php 
	    
	include("navbar.php");

?>
  <br />
   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
     <div class="container " style="padding-top: 10px;">
     
     <h2 class="centered"><?= $language=="ES"?"SEARCH":"SEARCH" ?><br>
     <?php 
     //if is a salesman
     if (!$_SESSION['isCustomer']) {
     	if ($pricePlanMode) {
     		$customer = new Customer($_SESSION['AccountNumber']);
     		echo("<small>Price Plan Mode - <i>" . $customer->AccountNumber . " - " . $customer->Name . "</i></small>");
     	}elseif(isset($_SESSION['setCustomerMode']) && $_SESSION['setCustomerMode']) {
     		$customer = new Customer($_SESSION['setCustomer']);
     		echo("<small><i>" . $customer->AccountNumber . " - " . $customer->Name . "</i></small>");
     	}
     }
     
      ?>
     
     </h2>
     <div class="well well-sm">
       <form name="inventorySearch" role="form" novalidate="novalidate" class="form-inline">
       	 
       	 <?php 
       	 	if ($isCustomer) {
       	 		
       	 	
       	  ?>
       	 
       	 
       	 <?php 
       	 	}
       	  ?>
       	 
         <div class="form-group">
           <label class="comboboxLabel">Category</label>
		   <select name="line"  id="lineSelect" class="form-control combobox">
           
             <option></option>
             <?php 
             		global $con;
             		$name = "Name";
             		if ($language == "EN") {
             			$name = "NameEN";
             		}
             		
             		$query = "SELECT * FROM `LINE` ORDER BY `$name` ASC";
             		$result = mysqli_query($con, $query);
             		while ($row = mysqli_fetch_array($result)) {
             ?>
             			<option <?= (isset($_REQUEST['line']) && $_REQUEST['line'] == $row['Code'])?"selected":"" ?> value="<?=$row['Code']?>"><?=$row[$name]?></option>
             <?php
             		}
             		
              ?>
           </select>
         </div>
         <div class="form-group">
           <label class="comboboxLabel">Subcategory</label>
           <select name="group" id="groupSelect" class="form-control combobox">
             <option></option>
             <?php 
             		$name = "Name";
             		if ($language == "EN") {
             			$name = "NameEN";
             		}
					$query = "SELECT * FROM `GROUP` ORDER BY `$name` ASC";
             
             		$result = mysqli_query($con, $query);
             		while ($row = mysqli_fetch_array($result)) {
             ?>
             			<option <?= (isset($_REQUEST['group']) && $_REQUEST['group'] == $row['Code'])?"selected":"" ?> value="<?=$row['Code']?>"><?= $row[$name] ?></option>
             <?php
             		}
              ?>           </select>
           
         </div>
         <div class="form-group">
           <label>Stock #</label>
           <input autocomplete="off" class="form-control" type="text" name="sku" value="<?= (isset($_REQUEST['sku'])?$_REQUEST['sku']:"") ?>" />
         </div>
         <button class="btn btn-primary">Search</button>
		<div class="form-group">
		  
		  <?php 
		  $wc = isset($_REQUEST['wc'])?$_REQUEST['wc']:"0";
		   ?>
		 <input class="form-control" type="checkbox" <?= ($wc == "1")?"checked":"" ?> name="wc" value="1" /> <label>Wildcard</label>
		</div>
		<img style="display: none; width: 50px;" class="pull-right" src="img/pr_flag.png" id="updateIndicator" />
       </form>
     </div>
	
 </div>

 
 <?php 
 
 
 if(isset($_REQUEST['sku'])){
 	
	
	$part = strtoupper(mysqli_real_escape_string($con, trim($_REQUEST['sku'])));
	$isSalesman = (!$isCustomer) ? 'true' : 'false';
	$account = ($isCustomer)?$_SESSION['AccountNumber']:$_SESSION['SalesmanID'];
	$query = "INSERT INTO SEARCH_QUERY (`Group`, `Line`, `SKU`, `AccountNumber`, `Salesman`, `QueryDate`) VALUES ('" . $_REQUEST['group'] . "', '" . $_REQUEST['line'] . "', '" . $part . "', '" . $account . "', " . $isSalesman . ", NOW())";
	mysqli_query($con, $query);

 $line = ($_REQUEST['line'] != '')?" AND INVENTORY.`Line`  LIKE '" . mysqli_real_escape_string($con, $_REQUEST['line']) . "'":'';
 $group = ($_REQUEST['group'] != '')?" AND INVENTORY.`Group`  LIKE '" . mysqli_real_escape_string($con, $_REQUEST['group']) . "'":'';
 
 $_SESSION['LastSearch'] = array(
 			"SKU" => $part,
 			"Line" => mysqli_real_escape_string($con, $_REQUEST['line']),
 			"Group" => mysqli_real_escape_string($con, $_REQUEST['group']),
 			"WC" => (isset($_REQUEST['wc']))?$_REQUEST['wc']:"0",
 			"Page" => (isset($_REQUEST['p']))?$_REQUEST['p']:"1"
 );
 
 /*
 if(isset($_REQUEST['wc'])){
	$parts = explode(" ", $part);
	$query = "";
	foreach ($parts as $term) {
		$query1 = "SELECT * FROM `INVENTORY` WHERE `SKU` LIKE '%$term%'" . $line . $group;
		$query2 = "SELECT * FROM `INVENTORY` WHERE REPLACE(`SKU`,\"-\",\"\") LIKE '" . str_ireplace("-", "", $term) . "'" . $line . $group;
		$query3 = "SELECT * FROM `INVENTORY` WHERE `Interchange` LIKE '%$term%'" . $line . $group;
		$query4 = "SELECT * FROM `INVENTORY` WHERE `Description` LIKE '%$term%'" . $line . $group;
		$query5 = "SELECT * FROM `INVENTORY` WHERE `Notes` LIKE '%$term%'" . $line . $group;
		$query = $query . $query1 . " UNION " . $query2 . " UNION " . $query3 . " UNION " . $query4 . " UNION " . $query5 . " UNION ";
	}
		$query = $query . "SELECT * FROM `INVENTORY` WHERE `SKU` LIKE '$term'" . $line . $group . " ORDER BY `sku`";
			
 }else{
 	$query1 = "SELECT * FROM `INVENTORY` WHERE `SKU` LIKE '$part'" . $line . $group;
 	$query2 = "SELECT * FROM `INVENTORY` WHERE REPLACE(`SKU`,\"-\",\"\") LIKE '" . str_ireplace("-", "", $part) . "'" . $line . $group;
 	$query3 = "SELECT * FROM `INVENTORY` WHERE `Interchange` LIKE '%$part%'" . $line . $group;
 	$query4 = "SELECT * FROM `INVENTORY` WHERE `Description` LIKE '%$part%'" . $line . $group;
 	$query5 = "SELECT * FROM `INVENTORY` WHERE `Notes` LIKE '%$part%'" . $line . $group;
 	$query = $query1 . " UNION " . $query2 . " UNION " . $query3 . " UNION " . $query4 . " UNION " . $query5 . " ORDER BY `sku`";
 }
 
 */
 
 /**/
 	$AccountNumber = ($_SESSION['isCustomer'])?$_SESSION['AccountNumber']:$_SESSION['SalesmanID'];
 	if(isset($_REQUEST['wc'])){
 		if ($_REQUEST['wc'] == "1") {
 			$part = "%" . str_ireplace(" ", "%", $part) . "%";
 		}
 		
 	}
 	$query1 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 1 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` LEFT JOIN SHOPPING_CART  
 			ON `INVENTORY`.SKU = SHOPPING_CART.SKU 
 				AND INVENTORY.`Group` = SHOPPING_CART.`Group` 
 				AND `INVENTORY`.Line = SHOPPING_CART.Line 
 				AND SHOPPING_CART.`AccountNumber` = '$AccountNumber' WHERE INVENTORY.`SKU` LIKE '$part'" . $line . $group;
 	$query2 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` LEFT JOIN SHOPPING_CART  
 			ON `INVENTORY`.SKU = SHOPPING_CART.SKU 
 				AND INVENTORY.`Group` = SHOPPING_CART.`Group` 
 				AND `INVENTORY`.Line = SHOPPING_CART.Line 
 				AND SHOPPING_CART.`AccountNumber` = '$AccountNumber' WHERE REPLACE(INVENTORY.`SKU`,\"-\",\"\") LIKE '" . str_ireplace("-", "", $part) . "'" . $line . $group;
 	$query3 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` LEFT JOIN SHOPPING_CART  
 			ON `INVENTORY`.SKU = SHOPPING_CART.SKU 
 				AND INVENTORY.`Group` = SHOPPING_CART.`Group` 
 				AND `INVENTORY`.Line = SHOPPING_CART.Line 
 				AND SHOPPING_CART.`AccountNumber` = '$AccountNumber' WHERE `Interchange` LIKE '%$part%'" . $line . $group;
	$query3 .= "UNION SELECT 
			INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 1.5 SortOrder, `Reference`, Supplier
		FROM `INVENTORY` 
			LEFT JOIN SHOPPING_CART ON `INVENTORY`.SKU = SHOPPING_CART.SKU AND INVENTORY.`Group` = SHOPPING_CART.`Group` AND `INVENTORY`.Line = SHOPPING_CART.Line AND SHOPPING_CART.`AccountNumber` = '$AccountNumber' 
			LEFT JOIN 
			`INTERCHANGE` ON `INVENTORY`.SKU = INTERCHANGE.SKU
				
		WHERE 
			
			REPLACE(INTERCHANGE.Reference, \"-\", \"\") LIKE '" . str_ireplace("-", "", $part) . "'" . $line . $group;
	
 	$where = "";
 	$index = 0;
 	if (isset($_REQUEST['wc'])) {
 		$partGroup = explode("%", $part);
 	}else{
 		$partGroup = explode(" ", $part);
 	}
 	
 	$partCount = count($partGroup);
 	foreach ($partGroup as $key => $value) {
 		$index++;
 		$where .= "CONCAT_WS(' ', `Description`, `Notes`) LIKE '%$value%'";
 		if ($index < $partCount) {
 			$where .= " AND ";
 		}
 	}
 	/*
 	$query4 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder FROM `INVENTORY` LEFT JOIN SHOPPING_CART  
 			ON `INVENTORY`.SKU = SHOPPING_CART.SKU 
 				AND INVENTORY.`Group` = SHOPPING_CART.`Group` 
 				AND `INVENTORY`.Line = SHOPPING_CART.Line 
 				AND SHOPPING_CART.`AccountNumber` = '$AccountNumber' WHERE `Description` LIKE '%$part%'" . $line . $group;
 	*/
 	$query4 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` LEFT JOIN SHOPPING_CART  
 			ON `INVENTORY`.SKU = SHOPPING_CART.SKU 
 				AND INVENTORY.`Group` = SHOPPING_CART.`Group` 
 				AND `INVENTORY`.Line = SHOPPING_CART.Line 
 				AND SHOPPING_CART.`AccountNumber` = '$AccountNumber' WHERE " . $where . $line . $group;
	
 	$query5 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` LEFT JOIN SHOPPING_CART  
 			ON `INVENTORY`.SKU = SHOPPING_CART.SKU 
 				AND INVENTORY.`Group` = SHOPPING_CART.`Group` 
 				AND `INVENTORY`.Line = SHOPPING_CART.Line 
 				AND SHOPPING_CART.`AccountNumber` = '$AccountNumber' WHERE `Notes` LIKE '%$part%'" . $line . $group;
 	$query = $query1 . " UNION " . $query2 . " UNION " . $query3 . " UNION " . $query4 . " UNION " . $query5 . " ORDER BY SortOrder, `sku`";
 /**/
	$queryPLS = $query2 . " UNION " . $query3 . " UNION " . $query4 . " UNION " . $query5 . " ORDER BY SortOrder, `sku`";
	$queryPLS = str_ireplace(" UNION ", " AND INVENTORY.Qty <= 0 GROUP BY `Group`, SKU UNION ",$queryPLS);
	$queryPLS = str_ireplace(" ORDER BY ", " AND INVENTORY.Qty <= 0 GROUP BY `Group`, SKU ORDER BY ",$queryPLS);
	
	
 if (isset($_REQUEST['debug'])) {
	//echo($query);
	echo("<BR />");
	echo($queryPLS);
 }

 $result = mysqli_query($con, $query);
 if (!(isset($_REQUEST['p']))) {
 	$pagenum = 1;
 } else {
 	$pagenum = $_REQUEST['p'];
 }
 
$rows = mysqli_num_rows($result);
 
 if ($rows < 2) {
 	$query1 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 1 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` LEFT JOIN SHOPPING_CART ON `INVENTORY`.SKU = SHOPPING_CART.SKU AND INVENTORY.`Group` = SHOPPING_CART.`Group` AND `INVENTORY`.Line = SHOPPING_CART.Line AND SHOPPING_CART.`AccountNumber` = '$AccountNumber' WHERE INVENTORY.`SKU` LIKE '$part%'" . $line . $group;
 	$query2 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` LEFT JOIN SHOPPING_CART  
 			ON `INVENTORY`.SKU = SHOPPING_CART.SKU 
 				AND INVENTORY.`Group` = SHOPPING_CART.`Group` 
 				AND `INVENTORY`.Line = SHOPPING_CART.Line AND SHOPPING_CART.`AccountNumber` = '$AccountNumber' WHERE REPLACE(INVENTORY.`SKU`,\"-\",\"\") LIKE '" . str_ireplace("-", "", $part) . "%'" . $line . $group;
 	$query = $query1 . " UNION " . $query2 . " UNION " . $query3 . " UNION " . $query4 . " UNION " . $query5 . " ORDER BY `sku`"; 	
	$result = mysqli_query($con, $query);
	$rows = mysqli_num_rows($result);
 }
 
 
 $page_rows = 50;
 if($rows > 0){
 	$last = ceil($rows/$page_rows);
 	if ($pagenum < 1) { 
 		$pagenum = 1; 
 	} elseif ($pagenum > $last) { 
 		$pagenum = $last; 
 	} 
 	$max = ' LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows; 
 	$query .= $max;
 	$result = mysqli_query($con, $query);
	
	
	include_once('./modules/lostsale/lostsale.addon.php');
?>
	
		<div class="container">
			<div class="row">
   			<script type="text/javascript">
				var cursor = 0;
				
				function nextItem() {
					cursor += 1;
					console.log(cursor);
					length = $('table tr').length;
					cursor = cursor % length;
					if (cursor == 0) {
						$($('table tr')[length-1]).removeClass("active");
						if (hymen) {
							alert("end of page")
							hymen = false;
						}
					}else{
						console.log("length: " + $('table tr').length);
						console.log("cursor:" + cursor);
						$($('table tr')[cursor-1]).removeClass("active");
						$($('table tr')[cursor]).addClass("active");
					}
				}
				function previousItem() {
					if (cursor == 0) {
						alert("go back");
					} else if (cursor < 0) {
						return;
					}else{
						cursor -= 1;
						if (cursor == 0) {
							alert("go back");
						}else{
							$($('table tr')[cursor+1]).removeClass("active");
							$($('table tr')[cursor]).addClass("active");
						}
					}
				}
				/*
				$(document).keydown(function(e) {
					
					//alert(e.which);
					switch (e.which) {
						case 13:
							//enter pressed
							if (typeof($("#qtyBox").data('bs.modal')) == "undefined") {
								askQty(cursor-1);	
								break;
							}
							if ($("#qtyBox").data('bs.modal').isShown) {
								break;
							}else {
								askQty(cursor-1);	
							}
							
							break;
						case 38:
							//up arrow
							previousItem();
							break;
						case 40:
							//down arrow
							$('[name=sku]').blur();
							nextItem();
							break;
					}
				});
				*/
   			</script>
<?php 
   $index = 0;
   $listingArray = array();
 	while($row = mysqli_fetch_array($result)){
		$product = new Item($row['Group'], $row['Line'], $row['SKU']);
		
 		if (in_array($row['Line'] . $row['SKU'], $listingArray)) {
 			continue;
 		}
 		array_push($listingArray, $row['Line'] . $row['SKU']);
 		echo "<script type=\"text/javascript\">\n";
 		echo "Line.push('" . $row['Line'] . "');\n";
 		echo "Group.push('" . $row['Group'] . "');\n";
 		echo "SKU.push('" . $row['SKU'] . "');\n";
 		echo "OnOrder.push('" . $row['OnOrder'] . "');\n";
 		echo "</script>";
		$qty = ($row['Qty'] > 50)?"50+":$row['Qty'];
		$qty = ($qty < 0)?"0":$qty;
		if($index%4 == 0){
			echo "<div class=\"row\">";
		}
?>
	
				<div class="col-md-3">
					<div class="thumbnail">
						<a href="" onclick="getProductDetails('<?= $row['Line'] ?>', '<?= $row['SKU'] ?>'); return false;"><img style="max-height: 252px;" src="<?= $product->getImage() ?>" alt=""></a>
					
						<div class="caption">
						  <h4 class="pull-right"><?php
								if(isQtyBreakSpecial($row['Line'], $row['SKU'])){
								  echo "<del>";
								}
								if ($isCustomer || $pricePlanMode) {
								 echo moneyFormat(getCustomerPrice($row['Group'], $row['Line'], $row['SKU']) * (getPricePlanCalculatedRate($_SESSION['AccountNumber'])));	
								} else {
								 echo moneyFormat(getCustomerPrice($row['Group'], $row['Line'], $row['SKU']));
								}
								if(isQtyBreakSpecial($row['Line'], $row['SKU'])){
								  echo "</del>";
								}
								?></span>
								<?php 
									 if(floatval($row['Core'])>0){
										 echo "<br><i><b>Core:</b> ".$row['Core'] . "</i>";
									 }
								?></h4>
						  <h4><a href="#" onclick="getProductDetails('<?= $row['Line'] ?>', '<?= $row['SKU'] ?>'); return false;"><?= $product->SKU ?></a></h4>
						  <p>
							<?= $product->Description . " " . $product->Notes ?>
							<br>
							 
							
							
						  </p>
						</div>
						<p>
							<div class="row">
								<div class="col-xs-6">
									
								</div>
								<div class="col-xs-6">
									
								<?php
									if($product->getAttribute('Barcode')){
								?>
									<a onclick="openBarcode('<?= $row['Line'] . " " . $row['SKU'] . "<br><small>" . $row['Description'] . " " . $row['Notes'] ?>', '<?= $product->getAttribute('Barcode') ?>');"><img style="width: 28px;" src="img/barcode.png"></a>
								<?php
									}
								?>
								
								</div>
								
							</div>
							<div class="row">
								<div class="col-xs-6">
									<button id="<?= $index; ?>AddButton" class="btn <?= $row['OnOrder'] > 0 ? "btn-warning":"btn-success" ?>" id="item<?= $index; ?>" onclick="askQty(<?= $index; ?>)" type="button"><?= $row['OnOrder'] > 0 ? "Update":"Add" ?></button>
								</div>
								
								<div class="col-xs-6">
									<br>
									On Hand: <?= $qty ?>
								</div>
								
							  
							</div>
						</p>
					</div>
				</div>
     <?php
	 if($index%4 == 3){
			echo "</div>";
		}
     $index++;
     } ?>
		</div>
	</div>


 <div style="width: 100%; text-align: center;" class="pagination">
 <?php 
 if($last > 1){
 	$wc = isset($_REQUEST['wc'])?$_REQUEST['wc']:"0";
 	$queryString = $_SERVER['PHP_SELF'] . "?group=" . $_REQUEST['group'] . "&line=" . $_REQUEST['line'] . "&sku=" . $_REQUEST['sku'] . "&wc=" . $wc;
 	if(!isset($_REQUEST['p'])){
 		$_REQUEST['p'] = "1";
 	}
  ?>
	<ul class="pagination">
	<?php 
	//disable prev button in first page
	 ?>
	<li <?= ($_REQUEST['p'] == "1")?"class=\"disabled\"":"" ?>>
		<a href="<?= $queryString . "&p=". (intval(mysqli_real_escape_string($con, $_REQUEST['p']))-1)?>">Prev</a>
     </li>
     <?php 
     //create each page button
     	for($i = 1; $i<=$last; $i++){ 
     		$p = (isset($_REQUEST['p']))?$_REQUEST['p']:"1";
     ?>
     <li <?= ($p == "$i")?"class=\"active\"":"" ?>>
       <a href="<?= $queryString . "&p=". $i ?>"><?= $i ?></a>
     </li>
             <?php } ?>
     <li <?= ($_REQUEST['p'] == $last)?"class=\"disabled\"":"" ?>>
 	<?php 
 		
 		$p = (isset($_REQUEST['p']))?(intval($_REQUEST['p'])+1):"2";
 		$link = $queryString . "&p=" . $p;
 	?>
       <a href="<?= $link; ?>">Next</a>
     </li>
   </ul>
   <?php } ?>
 </div>
 <?php
		
 	}else {
?>
		<div class="well well-sm"><?php
		//($language=="ES")?"Lo sentimos, no encontramos lo que est&aacute; buscando.":"We are sorry, we couldn't find the part you are looking for."
		?><br />
		<?php
			include_once('./modules/lostsale/lostsale.addon.php');
			if ($_SESSION['isCustomer']) {
		?>
				<?= ($language=="ES")?"Si tiene duda con respecto a la disponibilidad de una pieza no dude en contactar a su vendedor.":"If you have any questions regarding the availability of a part, don't hesitate to contact us." ?>
		
		<?php
			}
			
		 ?></div>

<?php
 	}
 }
 
?>
	
<script type="text/javascript">
      $(document).ready(function(){
        $('[name=sku]').select();
//        $('.grpline').css("width", "100px");
		
      });
      function setLanguage(Language) {
		$('#LanguageButton').text(Language);
		
      	$.get('functions.php?action=setLanguage&language=' + Language, function(data) {
      		if (data == "true") {
      			location.reload();
      		}else {
      			console.log("ERROR: " + data);
      		}
      	});
      
      }
      
      function showPromo() {
      	$('iframe').attr('src', 'http://www.youtube.com/embed/NWSXO0-zpqQ?rel=0&autohide=1&autoplay=1&showinfo=0&html5=1');
      	$('#promoModal').modal('show');
      	
      }
      var promoModal = $("#promoModal");
      promoModal.on('hide.bs.modal', function (e) {
      	$('iframe').attr('src', '');
      });
      
      
      /************************** /
      *							  *
      *	  BUYER'S GUIDE ADDON	  *
      *							  *
      / **************************/
	  loadBGLinks();
	  function loadBGLinks(){
		var BGsku, BGtype, BGline;
		for (var i = 0; i < SKU.length; i++) {
		  BGsku = $($('.SKU')[i]).text();
		  switch (Line[SKU.lastIndexOf(BGsku)]) {
		  <?php 
		  
		  $query = "SELECT * FROM BUYERS_GUIDE_DEFINITIONS WHERE `Line` != ''";
		  $result = mysqli_query($con, $query);
		  while ($row = mysqli_fetch_array($result)) {
			  echo "\tcase \"" . $row['Line'] . "\":\n";
			  echo "\t\t\t\tBGtype = '" . $row['Type'] . "';\n";
			  echo "\t\t\t\tbreak;\n";
		  }
		   ?>
			  default: {
				  switch (Group[SKU.lastIndexOf(BGsku)]) {
			<?php 
					  
					  $query = "SELECT * FROM BUYERS_GUIDE_DEFINITIONS WHERE `Group` != ''";
					  $result = mysqli_query($con, $query);
					  while ($row = mysqli_fetch_array($result)) {
						  echo "\tcase \"" . $row['Group'] . "\":\n";
						  echo "\t\t\t\tBGtype = '" . $row['Type'] . "';\n";
						  echo "\t\t\t\tbreak;\n";
					  }
					?>
					   default:
						  BGtype = 'cross';
						  break;
				  }
			  }
		  }
		  if (Line[SKU.lastIndexOf(BGsku)] != "") {
			  $($('.SKU')[i]).html('<a href="javascript:getProductDetails(\'' + Line[SKU.lastIndexOf(BGsku)] + '\', \'' + BGsku + '\')">' + BGsku + '</a>');
			  
		  }
				  
		}
	  }
	  
	  
      function getBG(type, line, group, sku) {
            	var	sku2 = sku;
            	$('#applicationsTable').html('');
            	$('#images').html('');
            	$('#detailsTable').html('');
            	$('#detailsTab').css('display', '');
            	$('#imagesTab').css('display', '');
            	
       		$.get('./smtpengine.php?type=' + type + '&line=' + line + '&group=' + group + '&action=applications&part=' + sku2, function(data) {
       			if (data != "false") {
       				var applications = JSON.parse(data);
       				for (var i = 0; i < applications.length; i++) {
       					$('#applicationsTable').append("<tr style=\"overflow: hidden;\"><td>" + applications[i].year + "</td><td>" + applications[i].make + "</td><td>" + applications[i].model + "</td><td>" + applications[i].engine + "</td><td style=\"overflow: hidden;\">" + applications[i].parttype + "</td></tr>");
       				}
       				$('#skuBG').text(sku);
       				$('#BGModal').modal('show')
       				$('#applicationsTab').click();
       			}else {
       				alert("Lo sentimos, no tenemos imagen disponible para esta pieza.\nWe are sorry, we don't have an image for this part.");
       			}
       			
       		});
       		
       		$.get('./smtpengine.php?type=' + type + '&line=' + line + '&group=' + group + '&action=images&part=' + sku2, function(data) {
       			var images = JSON.parse(data);
       			if (images.length > 0) {
           			for (var i = 0; i < images.length; i++) {
           				$('#images').append('<img src="' + images[i].id + '" alt="" />');
           			} 			
           		}else {
           			$('#imagesTab').css('display', 'none');
           		}
       		});
       		$.get('./smtpengine.php?type=' + type + '&line=' + line + '&group=' + group + '&action=details&part=' + sku2, function(data) {
       			var details = JSON.parse(data);
       			if (details.length > 0) {
       				for (var i = 0; i < details.length; i++) {
       					$('#detailsTable').append('<tr><td>' + details[i].attribute + '</td><td>' + details[i].value + '</td></tr>');
       				} 
       			}else {
       				$('#detailsTab').css('display', 'none');
       			}
       						
       		});
       		
      
            }
			$('[name=line]').on('change', function(){
				$.get('functions.php?action=getGroupsByLine&line=' + $('[name=line]').val(), function (data){
					data = JSON.parse(data);
					$('[name=group]').html('');
					for(var i = 0; i < data.length; i++){
						$('[name=group]').append('<option value="' + data[i].Code + '">' + data[i].Name + '</option>');
					}
				});
			});
      
    </script>

 
 
    
     
   </body>
 </html>