<?php
$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
//$domain = str_replace('www.', '', $domain);
session_set_cookie_params($lifetime = 86400, $path = "/", $domain, $secure = true, $httponly = true); // for one day
session_start();
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
//$noCookiePassThrough = "Y";

// Shop not show the powered by php version info
if (function_exists('header_remove')) {
    header_remove('X-Powered-By');
} else {
    @ini_set('expose_php', 'off');
}

global $cart;

if(isset($_SESSION['match_criteria'])){	
	$match_criteria = $_SESSION['match_criteria'];
	unset($_SESSION['match_criteria']);	
}
//print_r($_POST);
//echo $requestURI = $_SERVER['REQUEST_URI'];
// for sanitize
$requestURI = htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES);
$script_tag_found = 0;
$invalid_vals = ["%3Cscript%3E", '<script>'];
foreach($invalid_vals as $key => $val) {
	if(stristr($requestURI, $val)) { // <script>
		$script_tag_found = 1;
	}
}

if(strpos($requestURI,"/searchCat/")){
	$rs_searchCat = explode("/searchCat/",$requestURI);
	$searchCat = $rs_searchCat[1];
	$requestURI =  $rs_searchCat[0];
}
if(strpos($requestURI,"/match_criteria/")){
	$rs_match_criteria = explode("/match_criteria/",$requestURI);
	$match_criteria = $rs_match_criteria[1];
	$requestURI =  $rs_match_criteria[0];
}

if(strpos($requestURI,"search/")){
	$rs_keywords = explode("search/",$requestURI);
	$keywords = urldecode($rs_keywords[1]);
	$KEYWORDS = $keywords;
} elseif(isset($_REQUEST['keywords'])){
	$keywords = urldecode($_REQUEST['keywords']);
}

if(isset($keywords)){
	$keywords = strip_tags($keywords);
	$keywords = str_replace(["\"", ",","\'"],"",$keywords);
	if(strlen(trim($keywords)) < 2){ // if search < 2
		$keywords = "";
		$KEYWORDS = "";	
	}

	$full_search = 'N';
	if(strpos($keywords,"?opt=all")) {
		$full_search = 'Y';
		$keywords = str_replace('?opt=all', '', $keywords);
	}
}

// srtip the trailing s in the search words like for flags
if(!empty($keywords))
	$keywords = addslashes(htmlentities(rtrim($keywords, 's')));


$noCookiePassThrough = (!isset($noCookiePassThrough)) ? "" : $noCookiePassThrough;
$shop = isset($_REQUEST['shop']) ? htmlspecialchars($_REQUEST['shop'], ENT_QUOTES) : (isset($shop) ? $shop : 1);
$cart = isset($_REQUEST['cart']) ? htmlspecialchars($_REQUEST['cart'], ENT_QUOTES) : $cart;
$cat = isset($_REQUEST['cat']) ? htmlspecialchars($_REQUEST['cat'], ENT_QUOTES) : (isset($cat) ? $cat : 1);
$deja = isset($_REQUEST['deja']) ? htmlspecialchars($_REQUEST['deja'], ENT_QUOTES) : (isset($deja) ? $deja : $cart);

$cat  = (isset($searchCat) AND is_numeric(($searchCat))) ? abs($searchCat) : $cat;
$multi_product_counter = array(); #add_to_cart_per_page
	
if(isset($match_criteria) && ($match_criteria !='all' && $match_criteria !='whole' && $match_criteria !='any')){
	$match_criteria = 'all';
}
if(isset($keywords)){
	if(stristr($keywords,"103131lala") && $match_criteria =='whole'){
		$match_criteria = 'all';
		$whole_for_specific = 1;
	}
}
header('Content-type: text/html; charset=utf-8');
#require_once("func_mobile_detector.php");
include_once("global.php");
include_once('promocode.php');

if(function_exists('fileExistOnServer')) {
	fileExistOnServer();
}

// redirect to https if url is http and shop settings for https
$protocol = isset($_SERVER['HTTPS']) ? "https" : "http";

/*if (stripos($url_start, "https") !== false  && $protocol == 'http') {
	$url_ssl = str_replace("http:", "https:", $_SERVER['SCRIPT_URI']);
	header("Location:".$url_ssl,TRUE,301);
	die;
}

if (stripos(URL_START_ALIAS, $_SERVER['HTTP_HOST']) !== false) {
	header("Location:".URL_START);
	die;
}*/


if(strpos($requestURI,"/shop/search") !== false){
	$search_url = str_replace('shop/', '', $url_start).str_replace('/shop', '', $requestURI);
	$search_url = str_replace('//search', '/search', $search_url);
	header("Location:".$search_url);
	die;
}

if (function_exists('bannedIP')) {
	bannedIP();
}

if(isset($_GET['keywords'])){
	if(isset($_GET['match_criteria'])) $_SESSION['match_criteria']=$_GET['match_criteria'];
	$search_redirect = str_replace('shop//','shop/',URL_START.SEARCH_ALIAS.$_GET['keywords']);
	header("Location:".$search_redirect);
	die;
}

// Get Page ID
$page_call = 0;
$path = parse_url($requestURI, PHP_URL_PATH);
$filename = basename($path);

/* This code helps prevent calls to non-PHP pages. 
It ensures that only URLs ending with .php files, such as /shop/file.php, 
are processed, while requests like /shop are ignored.
*/
if (stripos($filename, ".php") !== false) {
	$condition = ['fields' => 'page_url LIKE ?','param_type' => 's','values' => ["%$requestURI%"]];
	$page_id = getTableData('pages', 'id', $condition);

	if($page_id){
		$cat = getMainCatName();
		$page_call = 1;
	}
}


if(stristr($_SERVER['HTTP_REFERER'],"facebook")){
	sendOKacknowledgement();
}


if(strpos($requestURI,"itemid=")){
  $url_start_without_shop 	= str_replace("/shop/","",$url_start);
  $prodname		= showItemName($_GET['itemid']);
  $url 			= $url_start_without_shop.URL_SHOP_ALIAS_ITEM."$prodname-".$_GET['itemid'];
  header("HTTP/1.1 301 Moved Permanently" );
  header("Location: $url" );
  exit();
}
elseif(strpos($requestURI,"cat=")){
	$cat = validateInput($cat, 'int');

	// Get cat id
 $condition = ['fields' => 'id = ? AND id <> parentcatid AND is_deleted = ?','param_type' => 'is','values' => [$cat,'N']];
 $cat_slug = getTableData('category', 'slug', $condition);

  if(empty($cat_slug)){
  	header("HTTP/1.1 404 Not Found");
		exit("<META HTTP-EQUIV='Refresh' CONTENT='0; URL=".URL_START."'>");
  } else {
  	
  	$url_start_without_shop 	= str_replace("/shop/","",$url_start);
		$cat_display = getTableData('shop', 'cat_display');
  	if($cat_display == 'slug') {
  		header("HTTP/1.1 301 Moved Permanently" );
			header("Location:". $url_start_without_shop.URL_SHOP_ALIAS_CATEGORY."$cat_slug");
			exit;
		}
		$catname = showCategoryNameDisplay($cat);
	  $url = $url_start_without_shop.URL_SHOP_ALIAS_CATEGORY."$catname-$cat";
	  header("HTTP/1.1 301 Moved Permanently" );
	  header("Location: $url" );
	  exit();
  }
}

if(isset($_REQUEST['source'])){
	$redirect_url = $_REQUEST['redirect_url'];
	// redirect only for that input via shop admin so commented below
	//setSoruceIntoDB($_REQUEST['source'], $_REQUEST['cat'], $_REQUEST['itemid'], $redirect_url);
}
$varList = "";
$varList = $_COOKIE;
if($_COOKIE){
	fnValidateInputs($varList);
}

$varList =  $_GET;
if($varList){
	 fnValidateInputs($varList);
}

$varList = $_POST;
if($varList){
	 fnValidateInputs($varList);
}

include_once "iparam_eater.php";

pageBanned();

// get shop values
$shop_db_values = "html_before_category_links,display_subcategory_link_thumbnail, display_subcategory_link_thumbnail_column,
	catalog3col,item_sort,item_sort_features, cat_display, display_cat_name_page_links, show_index, show_one_result_per_sku,
	show_searched_terms, adminemail, background, dividercellcolor, displaycatlinks, itemsperpage, globalcats, search_displayfull,
	show_top_pager, display_category_in_searchbox, thumbnail_display, thumbnail_title_display, 
	thumbnail_price_display,thumbnail_total_columns, display_celldividerbar,main_category_separator, main_category_columns, 
	category_separator,category_columns,totalMainCategories, totalCategories, display_items_alignment,checkouttype, paypalthirdoption, 
	currency,  add_to_cart_per_page, addtocart_as_image, addcartimagename, category_width, header, footer, display_breadcrumbs_list,
	display_parent_category_link, custom_text_parent_category, limit_link_categories, text_link_categories, thumbnail_sku_display,
	add_to_cart_option, quick_view, displaycatlinks_item_page, thumbnail_view_style, pixel_width_thumbnail, no_thumbnail_to_display,
	pixel_height_thumbnail, thumbnail_slider, mobile_resolution, mobile_version_enable, tablet_layout, col_4, search_item_name_first, 
	item_rating";
$options_shop = ['full_row' => true];
$shop_data = getTableData('shop', $shop_db_values, [], $options_shop);

// Assign values to variables as previously defined
foreach($shop_data as $key => $val) {
	$$key = $val;
}

if(strstr($html_before_category_links,'./') === false && trim($html_before_category_links) != ""){
	$html_before_category_links = str_ireplace('<a href="','<a href="./',$html_before_category_links);
	$html_before_category_links = str_ireplace('<a href=\"','<a href=\"./',$html_before_category_links);
	$html_before_category_links = str_ireplace("<a href='","<a href='./",$html_before_category_links);
	$html_before_category_links = str_ireplace("<a href=\'","<a href=\'./",$html_before_category_links);
	$condition = [
		'fields' => 'id = ?',
		'param_type' => 'i',
		'values' => [1]
	];
	updateTableValues('shop', "html_before_category_links='{$html_before_category_links}'", $condition);
}

/*if(strstr($html_before_category_links,"?shop=1&")){
		$html_before_category_links = str_replace("?shop=1&","?",$html_before_category_links);
		mysql_query_("UPDATE `shop` SET `html_before_category_links` = '$html_before_category_links' WHERE `id` = 1");
}*/

$shop = validateInput($shop, 'int');
$deja = validateInput($deja, 'int');
$cart = validateInput($cart, 'int');

//$parameters= "";

if(!isset($calledfrom))
	$calledfrom = "";

if(!isset($parameters)){
	$parameters = "";
	$arrParameters = array();
}

//If this has been called from sitemap page. This is made for search engine
if($parameters){
	$arrParameters = explode("/",$parameters);
	$catid 	= $arrParameters[0];
	$catid  = validateInput($catid, 'int');
	$itemdesc = $arrParameters[1];
}

$catid = (!isset($catid) || !is_numeric($catid)) ? $cat : $catid;

$shop = (!$shop or is_null($shop)) ? 1 : $shop;
$shop = setshop($shop); 
if (!validshop($shop)){ 
	error(2); 
	exit;
}

if(!isset($HTTP_REFERER))
$HTTP_REFERER = "";

$shopuserid  = validateInput($shopuserid, 'int');
if ($shopuserid && $HTTP_REFERER == ''){
	// Handle direct links to shop, make sure cart ID is valid
 	$condition = ['fields' => 'customerid = ?','param_type' => 'i','values' => [$shopuserid]];
	$cart = getTableData('cart', 'id', $condition);
}

if (!is_numeric($cat) && $cat <> ""){
	$condition = ['fields' => 'name = ? AND is_deleted = ? AND category_list = ?','param_type' => 'sss','values' => [mysql_real_escape_string_($cat),'N','Y']];
	$cat = getTableData('category', 'id', $condition);
	$cat  = validateInput($cat, 'int');
}

if(!$cat){
	$cat = getFirstParentCatId();
}
 
#---------------------------START THE CODE FOR THE PROMOTIONAL CODE TRACKER----------------------
$promocodeurl = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
$promoobj = new  MyPromocode($mysql_link,$shop,$promocodeurl);
if($promoobj->PutCookieForPromocodes() == "Y"){
	if($ExpCookieDBVal){
		setcookie ("MyPromocodeCookie", "", time()+$ExpCookieDBVal, $path = "/", $domain);
		setcookie ("MyPromocodeCookie", $promoobj->GetPromocode(), time()+$ExpCookieDBVal, $path = "/", $domain);
	} else {
		setcookie ("MyPromocodeCookie", "", time() + (86400 * 30), $path = "/", $domain);
		setcookie ("MyPromocodeCookie", $promoobj->GetPromocode(), time() + (86400 * 30), $path = "/", $domain);
	}
}
#---------------------------END CODE FOR THE PROMOTIONAL CODE TRACKER----------------------

if($show_one_result_per_sku=='Y')
	$show_one_result_per_sku_query=" GROUP BY product.`id`,sku_pno ";
else
	$show_one_result_per_sku_query=" GROUP BY product.`id`  ";

$index_string = "./";
$index_string1 = "";

if(isset($_REQUEST['ddCats'])){
	$newDDCats = validateInput($_REQUEST['ddCats'], 'int');
}

if(strpos($requestURI,"?")){
  $rs_cat = explode("?",$requestURI);
  $requestURI = $rs_cat[0];
}

$catAlias = $cat;
$recAlias = (isset($rec)) ? $rec : 0;
$itemid = (!isset($itemid)) ? "" : $itemid;
$searchbotArray = (DetectBrowserInfo());
$searchbot 		= $searchbotArray[0];
if($searchbot != ""){
  $array_alias = explode("/",$requestURI);
  #echo $array_alias[1];
	if($array_alias[1] != "shop"){
	  if($itemid == ""){
		  if(strstr(URL_SHOP_ALIAS_ITEM,$array_alias[1])){
			  $itemidArray = explode("-",$requestURI);
			  $itemid = $itemidArray[(count($itemidArray)-1)];
		  }
	  }
  
	  if(strstr(URL_SHOP_ALIAS_CATEGORY,$array_alias[1])){
			  $catidArray = explode("-",$requestURI);
			  $catid = $catidArray[(count($catidArray)-1)];
			  if(strpos($catid, '/rec') === false) {
			  	$catid = $cat = str_replace('/', '', $catid);  // if catid has trailing slash
			  }
			  

			  if(!isset($catid) || !is_numeric($catid)){
				  if(strstr($catid,"rec/")){
					$catidArray1 = explode("/",$catid);
					$catid = $cat = $catidArray1[0];
				  }
				  else{
					if($cart){
					//echo $catid;
					$catidArray2 = explode("cat=",$catid);
					$catidArray2 = explode("&",$catidArray2[1]);
					$catid = $cat = $catidArray2[0];
					 if($catid == ''){
					 	$catid = $cat = 1;
					 }
					}
					else{
						if(is_numeric($catAlias)){
							$catid = $cat = $catAlias;
						}
						else{
							$catid = $cat = 1;
						}
					}
				  }
			  }
	  }		  
  } // end if shop
  
  if($array_alias[1] == "shop" && trim($keywords) == ""){
  	unset($_SESSION['item_sort_option']);
  }
  $requestURI_rec = htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES);
  if(strstr($requestURI_rec,"rec/")){
		  $racArray = explode("/",$requestURI_rec);
		  $rec = $racArray[(count($racArray)-1)];
		  if(!is_numeric($rec)){
			  $rec = $recAlias;
			  $cat = $catAlias;
		  }
  }
if(isset($rec) && $rec == 0) {
	$url_start_without_shop = str_replace("/shop/", "", $url_start);
	$category_name_display  = showCategoryNameDisplay($catid);
	$url = $url_start_without_shop . URL_SHOP_ALIAS_CATEGORY . "$category_name_display-$catid";
  header("HTTP/1.1 301 Moved Permanently" );
  header("Location: $url" );
  exit();
}

if(isset($_REQUEST['ddCats'])){
	$cat = $newDDCats;
	$catid =  $newDDCats;
	if($cat_display == 'slug') {
		header("Location:".URL_SHOP_ALIAS_CATEGORY."$cat");
	} else {
		$category_name_display  = showCategoryNameDisplay($catid);
		header("Location:".URL_SHOP_ALIAS_CATEGORY."$category_name_display-$catid");
	}
}
} // end $searchbot
$itemdesc = (!isset($itemdesc)) ? "" : $itemdesc;

//echo $itemdesc='Hello';
//echo $cat = 1;
if($itemdesc != "" ){
	$itemid = mysql_result_(mysql_query_("SELECT id FROM product, product_category WHERE category_pc_id = '{$cat}' AND product_pc_id = id AND name LIKE '%". mysql_real_escape_string_(urldecode($itemdesc))."%' AND is_deleted ='N'"), 0);

/*	$query =  "SELECT id FROM product, product_category WHERE category_pc_id = ? AND product_pc_id = id AND name LIKE ? AND is_deleted = ?";
  $options = [
        'param_type' => 'iss',
        'values' => [$cat, mysql_real_escape_string_(urldecode($itemdesc)), 'N']
  ];
  $result = executeQuery($query, $options);*/
}

$rec = (isset($rec)) ? validateInput($rec, 'int') : "";
$goback = (isset($_REQUEST['goback'])) ? $_REQUEST['goback'] : "";

if(!isset($keywords))
	$keywords = "";
if(!isset($passedfrom))
	$passedfrom = "";
if(!isset($numprods))
	$numprods = 0;
if(!isset($thumbval))
	$thumbval = "";
if(!isset($noCookiePassThrough))
	$noCookiePassThrough = "";
if(!isset($titemid))
	$titemid = "";
if(!isset($nocookiepass))
	$nocookiepass = "";
if(!isset($showFullImage))
	$showFullImage = "";
if($showFullImage == "false")
	$showFullImage = "";

if(isset($cat) && !$page_call){
	$cat = validateInput($cat, 'int');
  //$is_category_exist = mysql_query_("SELECT id FROM category WHERE id=$cat AND id<>parentcatid AND is_deleted='N' ");
  $condition = ['fields' => 'id = ? AND id<>parentcatid AND is_deleted = ?','param_type' => 'is','values' => [$cat,'N']];
	$cat_id = getTableData('category', 'id', $condition);
  if(empty($cat_id)) {
			header("HTTP/1.1 404 Not Found");
			exit("<META HTTP-EQUIV='Refresh' CONTENT='0; URL=".URL_START."'>");
  }
}

# ------ show header for shop... ----------
# if they've not got a valid existing cart,
# create them one and redirect to this page again
//define("URL_START","http://logicool.precisionweb.net/shop/");
//$index_string = "./";
//$index_string1 = "";

if ($cart == 0){
	$cart = createcart($shop, $shopuserid);
	
	if ($cat != '')
		$tcat = "&cat=$cat";
	
	if ($itemid != '')
		$titemid = "&itemid=$itemid";
	
	if ($noCookiePassThrough == "Y")
		$nocookiepass .= "&noCookiePassThrough=Y";
	
	if ($passedfrom){
		$searchbotArray = (DetectBrowserInfo());
		$searchbot 		= $searchbotArray[0];
		
		if($searchbot != ""){
			$category_name_display  = showCategoryNameDisplay($cat);
			$item_name_display		= showItemName($itemid);
			if ($sid != '') $sid = "&$sid";
			$tcat = "$category_name_display-$cat"; // URL friendly links				
			header("location:".URL_SHOP_ALIAS_ITEM."$item_name_display-$itemid");
		}
		else{
			header("location:".URL_START.$index_string1."?cart=".$cart.$tcat.$titemid.$nocookiepass."&".sid."&thumbval=thumb&showFullImage=$showFullImage");
		}
		exit;
	} else{
		$adl_search_vars = (isset($searchCat)) ? "&search=Search&searchCat=".$searchCat : ""; #capture vars come from search / outside search
		$url_check = (isset($_SERVER['SCRIPT_URI'])) ? strtolower($_SERVER['SCRIPT_URI']) : "";		
		$url = strtolower('/sitepreview/');
		$result = strpos($url_check, $url);
		  $searchbotArray = (DetectBrowserInfo());
		  $searchbot 		= $searchbotArray[0];
		  if($searchbot != ""){
			//$tcat = "?cat=$cat";
			if (isset($sid)) $sid = "&$sid";
			$category_name_display  = showCategoryNameDisplay($cat);
			$item_name_display		= showItemName($itemid);
			$tcat = "$category_name_display-$cat"; // URL friendly links			 
			if ($itemid != '') $titemid = str_replace("&itemid=",URL_SHOP_ALIAS_ITEM."$item_name_display-",$titemid);  // URL friendly links			
			if($result || $url_check == ''){	
				// nothing
			} else {
				$pos = strrpos($url_check,'/');
				$url_check = substr($url_check,0,$pos+1);
			}
		  }
		  else{		
			if($result || $url_check == ''){
				if ($keywords){ // Search Redirection (External Link)
					exit("<META HTTP-EQUIV='Refresh' CONTENT='0; URL=".URL_START.$index_string1."?cart=$cart&match_criteria=$match_criteria".$nocookiepass."&rec=".$rec."&keywords=" . urlencode($keywords) . $adl_search_vars ."&". sid . "'>");
				} else {
					exit("<META HTTP-EQUIV='Refresh' CONTENT='0; URL=".URL_START.$index_string1."?cart=$cart" . $tcat . $titemid . $nocookiepass. "&" . sid . "'>");
				}
			} else {
				$pos = strrpos($url_check,'/');
				$url_check = substr($url_check,0,$pos+1);
				if ($keywords){	// Search Redirection (External Link)
					exit("<META HTTP-EQUIV='Refresh' CONTENT='0; URL=".$url_check.$index_string1."?cart=$cart&match_criteria=$match_criteria".$nocookiepass."&rec=".$rec."&keywords=" . urlencode($keywords) . $adl_search_vars ."&". sid . "'>");
				}else{
					exit("<META HTTP-EQUIV='Refresh' CONTENT='0; URL=".$url_check.$index_string1."?cart=$cart" . $tcat . $titemid . $nocookiepass. "&" . sid . "'>");
				}
			}
		  
		  }
	}
}

if (!validcart($cart,$shop,$shopuserid)){
	error(5);
	exit;
}
updateReferrer($cart, validateInput($_SERVER['HTTP_REFERER']));

#------------------------------START CODE FOR AFFILIATE TRACKING ----------------------
//then set the affiliate code value in the cookie.
$affiliateCode = "";
include_once('affiliate_tracking.php');
$obj  = new AffiliateTracking($mysql_link,$shop);
$affiliateurl = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
$obj->SetUrl($affiliateurl);
if($obj->PutAffiliateCookie() == "Y"){
	if($ExpCookieDBVal){
		setcookie ("AffiliateSource", "", time() + $ExpCookieDBVal, $path = "/", $domain);
		setcookie ("AffiliateSource", $obj->GetAffiliateSource(), time() + $ExpCookieDBVal, $path = "/", $domain);
	} else {
		setcookie ("AffiliateSource", "", time() + (86400 * 30), $path = "/", $domain);
		setcookie ("AffiliateSource", $obj->GetAffiliateSource(), time() + (86400 * 30), $path = "/", $domain);
	}
	$affiliateCode = $obj->GetAffiliateSource();
	//echo "UPDATE cart SET AffiliateSource='$affiliateCode' WHERE id=$cart;";
	mysql_query_("UPDATE cart SET AffiliateSource='$affiliateCode' WHERE id=$cart;");

	if( strlen(trim($redirect_url)) ) {
		$parsedURL = parse_url(URL_START); 
		$posURL = strpos($redirect_url, $parsedURL['host']);
		header("location: $redirect_url");
		exit;
	}	
}
unset($obj);
#------------------------------END CODE FOR AFFILIATE TRACKING ----------------------

if(trim($keywords) != ''){
	$showSR = '';
	if($sst == 'alphabetic'){
		$invalidChr = array('#','^','!','~','`','%','*','@',"'",',','?','|',trim("\ "),'"',')','(','&','!','$','[',']','{','}','=','<','>','/','+',':',';','_');
		$keywords	= str_replace($invalidChr, "", $keywords);
	}
	elseif($sst == 'never'){
		$showSR = 'yes';
	}
	$query = mysql_query_("SELECT ban_word FROM banned_search WHERE ban_action = 'ban_filter'");
		while($row_banned = mysql_fetch_row_($query)){
       		$keywords = str_replace($row_banned[0], '', $keywords);
   		}
	
	$query_ban = "SELECT id, ban_word FROM banned_search";
	$rs_banned_search = mysql_query_($query_ban);
	while($row_banned = mysql_fetch_row_($rs_banned_search)){
       $ban_array[$row_banned[0]] = $row_banned[1];
   }
   foreach($ban_array as $key => $val){
	  $replace_keywords_array = array("x","X");
	  $keywords_array = explode(" ", $keywords);
	  $keywords_array = str_replace($replace_keywords_array, " ", $keywords_array);
	  //print_r($keywords_array);
	  //if(stristr($keywords, $val)){
		if(in_array($val, $keywords_array)){
		  $query1 = "SELECT ban_action, ban_minutes FROM banned_search WHERE id=$key";
		  $rs1 = mysql_query_($query1);
		  $result1 = mysql_fetch_array_($rs1);
		  $ban_minutes = $result1[1];
		  $ban_start_time = date("Y-m-d H:i:s");
		  if($result1[0] == 'ban_no_search'){
			  $sst = 'never';
		  } elseif($result1[0] == 'ban_ip'){			  
			  $ban_ip = getenv('REMOTE_ADDR');
			  if(!stristr($ban_ip,'69.16.180')) {
				$mail_html_headers = "Content-type: text/html\r\nMIME-Version: 1.0 \r\nFrom:$adminemail";
				$invalidParamaterIs = "\n\r<br />Refferer: ".$_SERVER['HTTP_REFERER'];
				$invalidParamaterIs .= "\n\r<br />Search: ".$keywords;			  
				//mail("billing@precisionweb.net","Banned Search - ".URL_START,$invalidParamaterIs,$mail_html_headers);
				//mail("josh@precisionweb.net","Banned Search - ".URL_START,$invalidParamaterIs,$mail_html_headers);
			  }			  
		  }
	  }
   }
	
}

if(!strstr($_SERVER['HTTP_REFERER'],"rechargemycard.php") && !strstr($requestURI_rec,"/rec")){ // use for WGC
	//unset($_SESSION['variable_price']);
	unset($_SESSION['card_number']);
}


#--------------------------------CODE FOR AFFILIATE TRACKING COMES HERE --------------------------------------
//update affiliate code to cart database so that it can be accessed to other pages
//check if affiliate is not passed to querystring but set in cookie var
$itemtitle = "";
if(!isset($affiliateCode) && isset($_COOKIE['AffiliateSource']))
	$affiliateCode = $_COOKIE['AffiliateSource'];

$categoryNameForMetaDesc = showCategoryName($cat);
		
//UpdateAffiliateSourceToCart($affiliateCode, $cart);
$stockcontrolmode = getstockcontrolmode($shop);
$itemid =  (!isset($itemid)) ? "" :  validateInput($itemid, 'int');

if($itemid != '' ){
	unset($_SESSION['item_sort_option']);
	$results = mysql_query_("SELECT name, description FROM product WHERE id ='{$itemid}' AND is_deleted='N'");
	if($results && mysql_num_rows_($results)>0){
		$rs = mysql_fetch_array_($results);
		$itemtitle = $rs['name'];
		$itemdescription = $rs['description'];
		mysql_free_result_($results);
		unset($rs);
	}
	echo showhead($shop,$cat,$cart,'',$itemtitle);
} else{
	echo showhead($shop,$cat,$cart);
}
 
if($cat_display == 'slug') { 
	$request_uri = explode('/', $requestURI);
	$slug = $request_uri[count($request_uri)-1]; 
	$cat = $catid = mysql_result_(mysql_query_("SELECT id FROM category WHERE slug='$slug'"),0);
}

// if no cat id is set
$cat = !empty($cat) ? $cat : 1;

// revert the changes
//$search_item_name_first = 'N';

/*if(($quick_view == 'Y' && stristr($requestURI, URL_SHOP_ALIAS_CATEGORY) !== false && $col_4 != 'Y' && $thumbnail_display == 'Y') || isset($_SESSION['insert_jquery_files'])){
	echo "<script language='javascript' async=\"true\" type='text/javascript' src=\"/shop/thickbox/plugins/jquery.form-minify.js\"></script>";
	echo "<script language='javascript' async=\"true\" type='text/javascript' src=\"/shop/thickbox/thickbox.js\"></script>";
			
}*/

//if ($thumbnail_slider == 1 && ($thumbnail_display == 'N' || stristr($requestURI, URL_SHOP_ALIAS_ITEM) !== false)) {
if ($thumbnail_slider == 1  || $item_rating == 'Y') {
	if ($itemid != ''){
		$product_images_rs = mysql_query_("SELECT image_id FROM product_images WHERE image_product_id='{$itemid}'");
		if(mysql_num_rows_($product_images_rs) < $no_thumbnail_to_display){
			$no_thumbnail_to_display = mysql_num_rows_($product_images_rs);
		}
	}
	$thumbnail_slider_width = ($no_thumbnail_to_display*$pixel_width_thumbnail)+30;
	if($pixel_height_thumbnail == 0){
		$thumbnail_slider_height = "'auto'";
	}	else {
		$thumbnail_slider_height = $pixel_height_thumbnail+7;
	}
	echo  "<link rel=\"stylesheet\" href=\"/shop/thumbnail-slider/image-slider-style.css\" type=\"text/css\" media=\"all\" />";
	echo "\n<script language=\"javascript\" type=\"text/javascript\" src=\"https://cdn-script.com/ajax/libs/jquery/1.8.3/jquery.js\"></script>";
	echo "\n<script language='javascript' async=\"true\" type='text/javascript' src=\"/shop/thickbox/plugins/jquery.form-minify.js\"></script>";
	echo "\n<script language='javascript' async=\"true\" type='text/javascript' src=\"/shop/thickbox/thickbox.js\"></script>";
  echo "\n</script><script type=\"text/javascript\" language=\"javascript\" src=\"/shop/thumbnail-slider/jquery.carouFredSel-6.1.0-packed.js\"></script>";
	echo  "\n<script type=\"text/javascript\" language=\"javascript\">
			  jQuery(function() {
				  jQuery('#thumbnail_slider').carouFredSel({
					  width: $thumbnail_slider_width,  // 'auto' for auto
					  height: $thumbnail_slider_height,  // 'auto' for auto
					  prev: '#prev',
					  next: '#next',
					  auto: false
				  });
  
			  });
		  </script>";
} else {
	echo "\n<script language=\"javascript\" type=\"text/javascript\" src=\"jquery/jquery.js\"></script>";
}

############## For mobile Settings ##############
$mobile_view = false;
$table_width = '100%';
$thumbnail_total_columns = $thumbnail_total_columns == 0 ? 1 : $thumbnail_total_columns;
//$thumbnail_total_columns = '3';
$http_user_agent = userAgent($_SERVER['HTTP_USER_AGENT']);
if($mobile_version_enable != 'N' && $http_user_agent != 'desktop'){
	$category_separator = 'dropdownOnly';
	$item_sort = 'N';
	if($http_user_agent == 'mobile'){
	    $symbian= strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'symbian'); //Search for symbian as on http://ready.mobi/ Low-tier phone 
	    if ($symbian) {
	        $thumbnail_total_columns = 1;
          $display_subcategory_link_thumbnail_column = 1;
	    } else {
	        $thumbnail_total_columns = 1;
          $display_subcategory_link_thumbnail_column = 2;
          $table_width = '96%';
        }
	}
	else{
		if($tablet_layout == 1) {
			$thumbnail_total_columns = 1;
      $display_subcategory_link_thumbnail_column = 1;
		} else {
			$thumbnail_total_columns = 3;
			$display_subcategory_link_thumbnail_column = 3;
		}
	}
	$mobile_view = true;
}
################################################# 

if($add_to_cart_per_page == "Y"){
	global $url_start;
	$add_item_per_page_header  = $add_item_per_page_footer = "";
	$add_item_per_page_header .= "<form  name='prodform' method='post' action='". $url_start ."cart.php'>";
	$add_item_per_page_header .= "<input type='hidden' name='csrf_token' value='".generateCSRFToken()."'>";
	$add_item_per_page_footer .= "<input type='hidden' name=urlstamp value='". time(). "' />";
	$add_item_per_page_footer .= "<input type='hidden' name='multisubmit' value='Y' />";
	
	if($addtocart_as_image == "Y") { 
		if(preg_match("/^http:\/\//", $addcartimagename, $addcartimagename_matches) || preg_match("/^https:\/\//", $addcartimagename, $addcartimagename_matches)){
			$add_item_per_page_footer .= "<input type='image' name='submitact' value='".BTN_ADDMULTIPLETOCART."' src ='".$addcartimagename ."' align='center' />";
		} else {
			$add_item_per_page_footer .= "<input type='image' name='submitact' value='".BTN_ADDMULTIPLETOCART."' src ='".IMGS_DIR_URL.$addcartimagename."' align='center' />";
		}	
		//this is for fixing the x. and y. problem in the image
		$add_item_per_page_footer .= "<input type='hidden' name='submitact' value='".BTN_ADDMULTIPLETOCART."' align='center' />";
	} else {
		$add_item_per_page_footer .= "<input type='submit' name='submitact' value='".BTN_ADDMULTIPLETOCART."' />";
	}
	$add_item_per_page_footer .= "</div>";
	$add_item_per_page_footer .= "</form>";
	
}

#START HTML before category links option
 $pos_category_id   = strpos($html_before_category_links, "##category number##");
 $pos_category_name = strpos($html_before_category_links, "##category name##");
 if($pos_category_id === false || $pos_category_name === false){
	$searchbotArray = (DetectBrowserInfo());
	$searchbot 		= $searchbotArray[0];
	if($searchbot != ""){
		//$html_before_category_links = "<a href='./?cat=##category number##'>##category name##</a>";	
		$html_before_category_links = "<a href='".URL_SHOP_ALIAS_CATEGORY."##category number##'>##category name##</a>";
	}
	else{
		$html_before_category_links = "<a href='./?cart=".$cart."&cat=##category number##'>##category name##</a>";
	}
 } else {
	$searchbotArray = (DetectBrowserInfo());
	$searchbot 		= $searchbotArray[0];
	if($searchbot != ""){
		//$category_name_display = showCategoryName($cat);
		//$html_before_category_links = stripslashes(str_replace("cat=##", "cat=##",$html_before_category_links));
		  if ($keywords){			  
			  $html_before_category_links = stripslashes(str_replace("?cat=##", "##",$html_before_category_links)); // URL friendly links
		  }
		  else{
			  if($rec){
			  	$html_before_category_links = stripslashes(str_replace("./?cat=##", URL_SHOP_ALIAS_CATEGORY."##",$html_before_category_links)); // URL friendly links
			  }
			  else{
			  	$html_before_category_links = stripslashes(str_replace("?cat=##", "##",$html_before_category_links)); // URL friendly links
			  }
		  }	
	}
	else{
		$html_before_category_links = stripslashes(str_replace("cat=##", "cart=".$cart."&cat=##",$html_before_category_links));
	}
 }
#END HTML before category links option

//NOW CAPTURE SHOP THUMBNAIL DETAILS
$strThumbDisplay = $thumbnail_display;
$strThumbTitleDisplay = $thumbnail_title_display;
$strThumbSkuDisplay = $thumbnail_sku_display;
$strThumbPriceDisplay = $thumbnail_price_display;
$intThumbColumns = $thumbnail_total_columns;
$rec = ($rec == "" || $rec < 1) ? 0 : $rec;

if(isset($_SESSION['card_number'])){ // use for WGC
	$strThumbDisplay = 'N';			
} 

if ($goback)
$rec = $rec - $itemsperpage - $itemsperpage;

if ($itemid != '' && !$displaycatlinks_item_page) {
	$add_item_per_page_header = isset($add_item_per_page_header) ? "".$add_item_per_page_header : "";
	if($catalog3col == 4){
		echo "<table width='100%' cellspacing='0' style=\"align:center; border:0px; cellpadding:1px;\">";
	}
	else{
		echo "<br />", $add_item_per_page_header, '<table style="width:100%; margin:auto; width:100%; border-collapse:collapse; border:0px; padding:0px;" class="tbl-main">';
	}
	if($display_breadcrumbs_list == 'B' && $catalog3col != 6){
		echo "<tr><td colspan='4' valign='top' align='left' class='td_breadcrumbs' height='25' style=\"border: 0px;\">";
		
		if(isset($_SESSION['breadcrumbs_catid']) && ($_SERVER['HTTP_REFERER'] != '')) {
			$catid = $_SESSION['breadcrumbs_catid'];
		} else {
			$catid = mysql_result_(mysql_query_("SELECT category_pc_id FROM product_category WHERE product_pc_id='$itemid' AND category_pc_id<>0 ORDER BY category_pc_id asc"),0);
		}
		echo "<ol style='display: inline;' itemscope itemtype=\"http://schema.org/BreadcrumbList\">";
		echo breadcrumbsList($catid, $nested=1);
		echo "</ol>";
		echo "</td></tr>";
	}
	if($display_parent_category_link == 'Y' && $catalog3col != 6){
		echo "<tr><td colspan=4 style=\"border: 0px;\">";
		displayParentCategoryLink($itemid, $url_start, $custom_text_parent_category);
		echo "</td></tr>";
	}
	if($catalog3col == 6){
		echo "<tr><td>";
	}
	if ($stockcontrolmode != 4){
		if ($thumbval){	
			if($catalog3col == 6){
				showproduct_custom_layout($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N',$thumbval,$showFullImage);
			}
			else{		
				showproduct($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N',$thumbval,$showFullImage);
			}
		}
		else{
			if($catalog3col == 6){
				showproduct_custom_layout($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N');
			}
			else{
				showproduct($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N');
			}
		}
	} else {
		$prodcount = 0;
		$qry_getproductoption = mysql_query_("SELECT sum(stockqty) as qtysum FROM productoption WHERE productid = '{$itemid}'");
		list ($qtysum) = mysql_fetch_row_($qry_getproductoption);
		if ($qtysum > 0){
			if ($thumbval){
				if($catalog3col == 6){
					showproduct_custom_layout($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N',$thumbval,$showFullImage);
				}
				else{
					showproduct($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N',$thumbval,$showFullImage);
				}
			}
			else{				
				if($catalog3col == 6){
					showproduct_custom_layout($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N');
				}
				else{
					showproduct($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N');
				}
			}
		}
	}
	$add_item_per_page_footer = isset($add_item_per_page_footer) ? "<div style='text-align:right'>".$add_item_per_page_footer : "";
	if($catalog3col == 6){
		echo "</td></tr>";
	}
	echo "</table>", $add_item_per_page_footer;
 } else {  ?><!-- NEW INDEX PAGE --><?php  	
$customizableFields=array();
$resQuery = mysql_query_("SELECT label_id,label_text FROM tbl_customizable_labels WHERE area_id='6'");
if($resQuery && mysql_num_rows_($resQuery)){
	while ( $row = mysql_fetch_array_($resQuery)){  
		$customizableFields[$row["label_id"]]=stripslashes( $row["label_text"]);
	}
	mysql_free_result_($resQuery);
}
	// replace shortcode
	$header = str_replace('[category links]', '##category links##', $header);
	$footer = str_replace('[category links]', '##category links##', $footer);

	if(strpos($header,"[category hover menu]") == false && strpos($footer,"[category hover menu]") == false &&  strpos($header,"##category links##") == false && strpos($footer,"##category links##") == false && ($_SESSION['category_already_display'] == 0)) // && $itemid == ""
	{ 
		if($globalcats || $displaycatlinks){ // SHOW CATEGORIES IF ENABLED?><table id="MainTable-cart7" style="margin:auto; border: 0px;"><!-- SHOW CURRENT CATEGORY NAME IN CASE OF SINGLE COLUMN AND DROPDOWN DISPLAY --><?php  
		 //$tr_make = 0;
		 if($category_separator=='singlecol' AND (!isset($searchCat) OR $searchCat !='All') AND (!isset($searchCat) OR $searchCat !='0')) 
			{ 
				//$tr_make = 1;
				//echo "<tr><td colspan=\"3\" style='padding-bottom:3px' class='currcategoryselected'>";
				if($displaycatlinks && !$globalcats){
					$CATEGORYIDs = getParentCategoryIDs($cat);
					$CatSet = array_reverse(array_unique($CATEGORYIDs));
					if($searchbot != ""){
						for ($a=1; $a < count($CatSet); $a++){
						  $category_name_display  = showCategoryNameDisplay($CatSet[$a]);
						  $html_before_category_links_text = str_replace("##category number##", "$category_name_display-".$CatSet[$a], $html_before_category_links);
						  $html_before_category_links_text = str_replace("##category name##", showCategoryName($CatSet[$a]), $html_before_category_links_text);
						  $html_before_category_links_text = str_replace("##cart##", $cart, $html_before_category_links_text);
						  $html_before_category_links_text = str_replace("?cart=", "",$html_before_category_links_text);
						  $html_before_category_links_text = str_replace("$cart", "",$html_before_category_links_text);
						  $html_before_category_links_text = str_replace("&cat=", "",$html_before_category_links_text);
						  if($index_string == "./"){
							  $html_before_category_links_text = str_replace("./", URL_SHOP_ALIAS_CATEGORY,$html_before_category_links_text);
						  }
						  //echo $html_before_category_links_text, "&nbsp;&raquo;&nbsp;";
					  } // for
					}
					else{
					  for ($a=1; $a < count($CatSet); $a++)
					  {
						  $html_before_category_links_text = str_replace("##category number##", $CatSet[$a], $html_before_category_links);
						  $html_before_category_links_text = str_replace("##category name##", showCategoryName($CatSet[$a]), $html_before_category_links_text);
						  $html_before_category_links_text = str_replace("##cart##", $cart, $html_before_category_links_text);
						  echo $html_before_category_links_text, "&nbsp;&raquo;&nbsp;";
					  }
					}
					$singleColTr = true;
				}
			} ?><!-- END SHOW CURRENT CATEGORY NAME IN CASE OF SINGLE COLUMN AND DROPDOWN DISPLAY --><tr><td class="MainTable-cart7-td" style="vertical-align: top!important; border: 0px;" <?php  echo (isset($singleColTr)) ? ' style="padding-left:3px"' : '';?>>
			<?php  showCategories($index_string,$cat,$shop, $globalcats, $displaycatlinks, $category_separator, $category_columns, $cart, $stockcontrolmode); ?>
		<?php  if($category_separator == 'singlecol' || $category_separator == 'dropdown' ){ ?>
			</td>
			<td style="width:1px"></td>
		<?php  } else { ?>
			</td>
			</tr>
			<tr>
		<?php  } ?><td width="85%" valign="top" itemscope itemtype='https://schema.org/SiteNavigationElement' role='menu'><?php  if($category_separator=='dropdown')
			{ 

				if(isset($_REQUEST['ddCats']) AND strlen($_REQUEST['ddCats'])>0)
				{
					$sel = explode(":",$_REQUEST['ddCats']);
					$sel = $sel[0];
				}else{
					$sel = $cat;
				}
				echo "<form name='frmShowCat' method='post' action='index.php' style='margin:0px'>";
				echo "<input type='hidden' name='csrf_token' value='".generateCSRFToken()."'>";
				echo "<input type='hidden' name=\"cat\" value=''>";
				if(($globalcats AND $displaycatlinks) || (!$globalcats AND $displaycatlinks))
				{
					$GetCategories = mysql_query_("SELECT id, name, parentcatid FROM category WHERE is_deleted='N' AND category_list='Y' ORDER BY sequence ASC");
					if($GetCategories AND mysql_num_rows_($GetCategories)>0) {
					    if($mobile_view){
                          echo "<div class='shop-by-category'>Shop by Category</div>";
                        }
						echo "<select id='id-ddCats' name='ddCats' onChange='javascript:ShowItemOfCat();'>";
						categoryDropDown(0,0, $GetCategories,$shop,$cart,$sel);
						echo "</select>";
					}
				}
				elseif($globalcats AND $displaycatlinks != true) 
				{
					$SubCategories = mysql_query_("SELECT * FROM category WHERE parentcatid <=1 AND category_list='Y'  AND is_deleted='N' ORDER BY sequence");
					if($SubCategories AND mysql_num_rows_($SubCategories)>0) {
						echo "<select name='ddCats' id='id-ddCats' onChange='javascript:ShowItemOfCat();'>";
						/*while($acat = mysql_fetch_array_($SubCategories)) {
							$selected ="";
							if($acat['id']==$sel)
								$selected =" selected";
							//echo "<option value=\"{$acat['id']}:{$cart}\" {$selected}> {$acat['name']} </option>"; 
						}*/
						while($acat = mysql_fetch_array_($SubCategories)) 
						{
							$selected ="";
							if($acat['id']==$sel)
								$selected =" selected";
								$category_name_display = showCategoryNameDisplay($acat['id']);
								$url_start_cat 	= str_replace("/shop/","",$url_start);
							if($cat_display == 'slug') {
    						echo "<option value=".$url_start_cat.URL_SHOP_ALIAS_CATEGORY.$acat['slug']."{$selected}>{$acat['name']} </option>";
		    			} else {
		    				echo "<option value=".$url_start_cat.URL_SHOP_ALIAS_CATEGORY.$category_name_display.'-'.$acat['id']."{$selected}>{$acat['name']} </option>";
		    			}
							
						}
						echo "</select>";
					}
				}		  
				echo "</form>";
			} 
				
			if($category_separator=='dropdownOnly')
            { 
				if(isset($_POST['ddCats']) AND strlen($_POST['ddCats']) >0 )
				{
					$sel = explode(":",$_POST['ddCats']); # at 0 index cat id exists at 1 index cart id 
					$sel = $sel[0];
				}else{
					$sel = $cat;
				}
					 
				echo "<form name='frmShowCat' method='post' action='index.php' style='margin:0px' >"; 
				echo "<input type='hidden' name='csrf_token' value='".generateCSRFToken()."'>";
				echo "<input type='hidden' name=\"cat\" value=''>";
				if(($globalcats AND $displaycatlinks) || (!$globalcats AND $displaycatlinks))
				{
					$GetCategories = mysql_query_("SELECT id, name, parentcatid FROM category WHERE is_deleted='N' AND category_list='Y' ORDER BY sequence ASC");
					if($GetCategories AND mysql_num_rows_($GetCategories)>0)
					{
						if($mobile_view){
						  echo "<div class='shop-by-category'>Shop by Category</div>";
                        } else {
                            echo "&nbsp;&nbsp;";
                        }
						echo "<select name='ddCats' id='id-ddCats' onChange='javascript:ShowItemOfCat();'>";
						categoryDropDown(0,0, $GetCategories,$shop,$cart,$sel);
						echo "</select>";
						mysql_free_result_($GetCategories);
					}
				} 
				elseif($globalcats AND $displaycatlinks != true) 
				{
					$SubCategories = mysql_query_("SELECT * FROM category WHERE parentcatid <=1 AND is_deleted='N' AND category_list='Y' ORDER BY sequence");
					if($SubCategories AND mysql_num_rows_($SubCategories)>0) 
					{
						echo "<select name='ddCats' id='id-ddCats' onChange='javascript:ShowItemOfCat();'>";
						while($acat = mysql_fetch_array_($SubCategories)) 
						{
							$selected ="";
							if($acat['id']==$sel)
								$selected =" selected";
								$category_name_display = showCategoryNameDisplay($acat['id']);
								$url_start_cat 	= str_replace("/shop/","",$url_start);
							if($cat_display == 'slug') {
    						echo "<option value=".$url_start_cat.URL_SHOP_ALIAS_CATEGORY.$acat['slug']."{$selected}>{$acat['name']} </option>";
		    			} else {
		    				echo "<option value=".$url_start_cat.URL_SHOP_ALIAS_CATEGORY.$category_name_display.'-'.$acat['id']."{$selected}>{$acat['name']} </option>";
		    			}
							
						}
						echo "</select>";
						mysql_free_result_($SubCategories);
					}
				}
				echo "</form>";
			} ?><!-- END SHOW CURRENT CATEGORY NAME IN CASE OF DROPDOWN DISPLAY --><?php   } // END SHOW CATEGORIES IF ENABLED
	} 
?><?php  if($itemid == ""){ ?>
			<table id="ContentsContainer" cellspacing="0" style="width:100%; align:center; border:0px; cellpadding:0px;" ><?php  }
			if(!$page_call){ ?><!-- PAGINATION START --><?php 					
					//CHECK IF CAT DOES NOT COME THROUGH SEARCH BUTTON
					$subCategoryExist = mysql_result_(mysql_query_("SELECT count(id) as countCat FROM category WHERE parentcatid=$cat AND is_deleted='N'  AND category_list = 'Y'"),0);
					
					//if( (!isset($searchCat) || strlen($searchCat)<1) && !isset($_REQUEST['search']) )
					if($keywords=="" && $itemid == "")
					{
						$numprods = productsincategory($cat); 
						$numpages = intval($numprods / $itemsperpage);
						if ($numpages != ($numprods / $itemsperpage))
						$numpages = $numpages +1;
						$currpage = ($rec == 0) ? 1 : ($rec / $itemsperpage) + 1; 	
						
						if(($show_top_pager == "Y") && ($numpages > 1)){
				?>			<tr><td valign="top" align="right"  class="tdpaging"> <?php  
							if($subCategoryExist && $display_subcategory_link_thumbnail=='Y'){
								include("pager.php");
							}
							else{
								include("pager.php"); 
							}
							?></td></tr><?php   } ?>
                 <?php 				 
				 if($display_breadcrumbs_list == 'C' || $display_breadcrumbs_list == 'B' && $itemid == ""){

					if($cat != '1'){
						echo "<tr><td valign=\"top\" align=\"left\"  class=\"td_breadcrumbs\" height=\"25\">";
						echo "<ol style='display: inline;' itemscope itemtype=\"http://schema.org/BreadcrumbList\">";
						echo breadcrumbsList($cat, $nested=1);
						echo "</ol>";
					 	echo "</td></tr>";
					}
				
				} // end if display_breadcrumbs_list?>
                
<?php   } ?><!-- PAGINATION END -->	<!-- SHOW CATEGORY HTML IF EXISTS --><?php 
				$show_category_html = false;
				$qry_category_html  = mysql_query_("SELECT category_html, category_html_below, category_html_between, enable_sort_feature FROM category WHERE id='$cat' AND is_deleted='N'");
				if($qry_category_html && mysql_num_rows_($qry_category_html)){
					list ($category_html, $category_html_below, $category_html_between, $enable_sort_feature) = mysql_fetch_row_($qry_category_html);
					mysql_free_result_($qry_category_html);
				}
				if(trim($category_html) != "" && $itemid == "") 
				{
					$searchbotArray = (DetectBrowserInfo());
					$searchbot 		= $searchbotArray[0];
					if($searchbot != ""){
						$category_html	= 	str_replace("##cartid##","",$category_html);
					}
					else
					{
						$category_html	= 	str_replace("##cartid##","&cart=$cart",$category_html);
					}
					$category_html  =  replaceTextAndAffiliates($category_html);
					$show_category_html = true;
				}
				if($category_html != "" && $itemid == ""){			
					if(isset($keywords) AND (isset($searchCat) AND is_numeric($searchCat) AND $searchCat>0) AND $show_category_html)
						echo "<tr><td valign=\"top\" align=\"left\" style=\"border:0px;\">", $category_html ,"</td></tr>";
			 		elseif(!(isset($keywords) AND strlen(trim($keywords))>0) AND $show_category_html)
						echo "<tr><td valign=\"top\" align=\"left\" style=\"border:0px;\">", $category_html, "</td></tr>";
				}
				if(isset($_REQUEST['submit_custom_search'])){
					$custom_search_qry = "";
					foreach($_REQUEST as $key => $val){
						if($val != '0' && $val != "" && $key != 'submit_custom_search'){
							if(strpos($val,"-") === false){
								$custom_search_qry .= " AND product.{$key} = '{$val}' ";
							}
							else{
								$val = str_replace("-", "AND" , $val); 
								$custom_search_qry .= " AND product.{$key} BETWEEN {$val} ";
							}
						}
					}
					$keywords = "submit_custom_search";	
				}
				elseif(isset($_REQUEST['submit_custom_search_hidden'])){
					$custom_search_qry = stripslashes($_POST['custom_search_qry']);
					$keywords = "submit_custom_search";	
				}
				
				$order_by_item = " product_category.seq_pc_number ";
				$order_by = " product.name,pc.category_pc_id ";
				if($item_sort == "Y" && $enable_sort_feature == "Y" && $itemid == ""){
					$array_item_sort_featues = explode("|",$item_sort_features);
					$no_sort_features = count($array_item_sort_featues);
					if($no_sort_features > 1){
						echo "<tr><td class=\"td_sortBy\" style=\"border: 0px;\"><form action=\"\" name=\"frm_item_sort\" method=\"post\">";
						echo "<input type='hidden' name='csrf_token' value='".generateCSRFToken()."'>";
						echo "<span class=\"sortBy\">Sort By: </span><select class=\"textbox\" name=\"item_sort_option\">";
						if($_POST['item_sort_option'] == 'R' || $_SESSION['item_sort_option'] == 'R'){
							$select_r 		= "selected=\"selected\"";
							$order_by_item 	= " product_category.seq_pc_number ";
							$order_by 		= " product.name,pc.category_pc_id ";
							$_SESSION['item_sort_option'] =	'R';
						}
						if($_POST['item_sort_option'] == 'PLH' || $_SESSION['item_sort_option'] == 'PLH'){
							$select_plh 	= "selected=\"selected\"";
							$order_by_item 	= " product.price ";
							$order_by 		= " product.price ";
							$_SESSION['item_sort_option'] =	'PLH';
						}
						if($_POST['item_sort_option'] == 'PHL' || $_SESSION['item_sort_option'] == 'PHL'){
							$select_phl 	= "selected=\"selected\"";
							$order_by_item 	= " product.price DESC ";
							$order_by 		= " product.price DESC ";
							echo $_SESSION['item_sort_option'] =	'PHL';
						}
						if($_POST['item_sort_option'] == 'T' || $_SESSION['item_sort_option'] == 'T'){
							$select_t 		= "selected=\"selected\"";
							$order_by_item 	= " product.name ";
							$order_by 		= " product.name ";
							$_SESSION['item_sort_option'] =	'T';
							
						}

						echo "<option value=\"0\">Page sorting options</option>";
						for($ii=0; $ii<$no_sort_features; $ii++){							
							if($array_item_sort_featues[$ii] == 'R')
								echo "<option value=\"R\" $select_r>Relevance</option>";
							elseif($array_item_sort_featues[$ii] == 'PLH')
							 	echo "<option value=\"PLH\" $select_plh>Price Low to High</option>";
							elseif($array_item_sort_featues[$ii] == 'PHL')
							 	echo "<option value=\"PHL\" $select_phl>Price High to Low</option>";
							elseif($array_item_sort_featues[$ii] == 'T')
							 	echo "<option value=\"T\" $select_t>Title</option>";
						}
						echo "</select>&nbsp;";
						if($keywords == "submit_custom_search"){
							echo "<input type=\"hidden\" value=\"submit_custom_search\" name=\"submit_custom_search_hidden\" />";
							echo "<input type=\"hidden\" value=\"$custom_search_qry\" name=\"custom_search_qry\" />";
						}
						echo "<input class=\"buttonGo\" type=\"submit\" name=\"go\" value=\"Go\" />";
						echo "<input type=\"hidden\" value=\"$keywords\" name=\"keywords\" /></form></td></tr>";
					}
				}
			 ?><!-- END SHOW CATEGORY HTML IF EXISTS --><!-- SHOW PRODUCTS --><?php  
					$prodcount = 0;
					if($stockcontrolmode != 4) {
						$StockModeSQL = "SELECT product.id, isgiftcert FROM product, product_category, category 
										WHERE category.id='{$cat}' 
										AND display_product_in_cart = 'Y' AND product.is_deleted = 'N' 
										AND category.id = category_pc_id  AND product_pc_id = product.id 
										AND category.is_deleted = 'N' AND (category.category_list = 'Y' OR category.category_list = 'C')
										ORDER BY  $order_by_item
										LIMIT {$rec}, {$itemsperpage}";
					} else {
						$StockModeSQL = "SELECT product.id, isgiftcert, sum( stockqty ) AS qtysum FROM product, productoption, product_category, category 
										WHERE category.id='{$cat}' 
										AND display_product_in_cart = 'Y' AND product.is_deleted = 'N' AND product.id = productid 
										AND category.id = category_pc_id  AND product_pc_id = product.id
									    AND category.is_deleted = 'N' AND (category.category_list = 'Y' OR category.category_list = 'C')
										GROUP BY productid HAVING qtysum >0 
										ORDER BY $order_by_item 
										LIMIT {$rec}, {$itemsperpage}";
					}	
					//echo $StockModeSQL;
					if($displaycatlinks_item_page && $itemid != ""){
	$add_item_per_page_header = isset($add_item_per_page_header) ? "".$add_item_per_page_header : "";
	if($catalog3col == 4){
		echo "<table width='100%' cellspacing='0' id='table_item_html' style=\"align:center; border:0px; cellpadding:1px;\" >";
	}
	else{
		echo "<br />", $add_item_per_page_header, "<table style=\"width:100%; border:0px;\" id='table_item_html'>";
	}
	if($display_breadcrumbs_list == 'B' && $catalog3col != 6){
		echo "<tr><td colspan='4' style=\"border: 0px;\" valign='top' align='left' class='tdpaging' height='25'>";
		if(isset($_SESSION['breadcrumbs_catid']) && ($_SERVER['HTTP_REFERER'] != '')) {
			$catid = $_SESSION['breadcrumbs_catid'];
		} else {
			$catid = mysql_result_(mysql_query_("SELECT category_pc_id FROM product_category WHERE product_pc_id='$itemid' AND category_pc_id<>0 ORDER BY category_pc_id asc"),0);
		}
		echo "<ol style='display: inline;' itemscope itemtype=\"http://schema.org/BreadcrumbList\">";
		echo breadcrumbsList($catid, $nested=1);
		echo "</ol>";
		echo "</td></tr>";
	}
	if($display_parent_category_link == 'Y' && $catalog3col != 6){
		echo "<tr><td colspan=4 style=\"border: 0px;\">";
		displayParentCategoryLink($itemid, $url_start, $custom_text_parent_category);
		echo "</td></tr>";
	}
	if($catalog3col == 6){
		echo "<tr><td>";
	}
	if ($stockcontrolmode != 4){
		if ($thumbval){			
			if($catalog3col == 6){
				showproduct_custom_layout($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N',$thumbval,$showFullImage);
			}
			else{
				showproduct($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N',$thumbval,$showFullImage);
			}
		}
		else{			
			if($catalog3col == 6){
				showproduct_custom_layout($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N');
			}
			else{
				showproduct($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N');
			}
		}
	} else {
		$prodcount = 0;
		$qry_getproductoption = mysql_query_("SELECT sum(stockqty) as qtysum FROM productoption WHERE productid = '{$itemid}'");
		list ($qtysum) = mysql_fetch_row_($qry_getproductoption);
		if ($qtysum > 0){
			if ($thumbval){
				if($catalog3col == 6){
				showproduct_custom_layout($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N',$thumbval,$showFullImage);
				}
				else{
					showproduct($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N',$thumbval,$showFullImage);
				}				
			}
			else{		
				if($catalog3col == 6){
					showproduct_custom_layout($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N');
				}
				else{
					showproduct($itemid,$shop,$cat,$cart,$stockcontrolmode,'Y','N');
				}				
			}
		}
	}
	$add_item_per_page_footer = isset($add_item_per_page_footer) ? "<div style='text-align:right'>".$add_item_per_page_footer : "";
	if($catalog3col == 6){
		echo "</td></tr>";
	}
	#echo "</table>", $add_item_per_page_footer;
	if(!$globalcats && !$displaycatlinks){	
		echo  $add_item_per_page_footer;	
	}
	else{
		echo "</table>", $add_item_per_page_footer;
	}
}
else{

if(!$keywords){
	if($thumbnail_display =='Y' || !$numprods) $add_item_per_page_header = ""; 
}

$add_item_per_page_header = ($add_item_per_page_header) ? "".$add_item_per_page_header : "";
if($catalog3col == 4){
	echo "<tr><td valign='top' style=\"border: 0px;\">", $add_item_per_page_header,
		"<!-- tbl-thumbnail-position-fitter-start -->",
		"<table style=\"border:0px; cellpadding:2px;\" cellspacing='0' width='{$table_width}' class='list_option_display'>";
}
else{
	echo "<tr><td valign='top' style=\"border: 0px;\">", $add_item_per_page_header,
		"<!-- tbl-thumbnail-position-fitter-start -->",
		"<table width='{$table_width}' style=\"align:center; border:0px; cellpadding:1px; border-collapse:initial;\" cellspacing='10' class='tbl-cart7-main'>";
}

// new line below by ken 2/26
//echo "<tr><td valign='top'>";

						$parentid = mysql_result_(mysql_query_("Select parentcatid From category Where id=$cat"),0);
						if($keywords == '' && ($strThumbDisplay == "N" || $strThumbDisplay == "" || is_null($strThumbDisplay))) 
						{
							$qry_showproducts = mysql_query_($StockModeSQL);
							unset($StockModeSQL);
							$prod = 0;
							if($subCategoryExist && ($display_subcategory_link_thumbnail=='Y' || ($display_subcategory_link_thumbnail=='M' && $parentid != 0) || ($display_subcategory_link_thumbnail=='T' && $parentid == 0))){
								//echo "<tr><td colspan='$thumbnail_total_columns' valign='top' class='tbl-cart7-main-td'>";
								echo "<tr><td colspan='4' valign='top' class='tbl-cart7-main-td' style=\"border: 0px;\">";
								showcategory_thumbnail($cat, $display_subcategory_link_thumbnail_column);
								echo "</td></tr>";
							}
							//else{
							  if($catalog3col == 4 && mysql_num_rows_($qry_showproducts) > 0){
								  /*echo "<tr class='item_list_option_heading' style=\"width:100%\">";
								  echo "<td style=\"width:20%\"><span class=\"itemImg_heading\"></span></td>";
								  echo "<td style=\"width:60%\"><span class=\"itemName_heading\"></span></td>";
								  echo "<td style=\"width:10%\"><span class=\"itemPrice_heading\"></span></td>";
								  echo "<td style=\"width:10%\"><span class=\"quantity_heading\"></span></td>";
								  echo "</tr>";*/
								  $_SESSION['list_option_loop'] = 0;
							  }
							  if($stockcontrolmode != 4)
							  {
								  while (list($product, $isgiftcert) = mysql_fetch_row_($qry_showproducts)){
									  if($catalog3col == 6){
										  $prod = showproduct_custom_layout($product,$shop,$cat,$cart,$stockcontrolmode);
									  }
									  else{
										  $prod = showproduct($product,$shop,$cat,$cart,$stockcontrolmode);
									  }									  
									  $prod++;
									  $_SESSION['list_option_loop']++;
								  }
							  }
							  else
							  {
								  while (list($product, $isgiftcert, $qtysum) = mysql_fetch_row_($qry_showproducts)){									  
									  if($catalog3col == 6){
										  $prod = showproduct_custom_layout($product,$shop,$cat,$cart,$stockcontrolmode);
									  }
									  else{
										  $prod = showproduct($product,$shop,$cat,$cart,$stockcontrolmode);
									  }	
									  $prod++;
									  $_SESSION['list_option_loop']++;
								  }
							  }
							//}// end else
						#} elseif($keywords == '' && $calledfrom == '' && $strThumbDisplay == "Y") {
						}
						elseif($keywords == '' || ($keywords == '' && $calledfrom == '' && $strThumbDisplay == "Y")) 
						{						
							$qry_showproducts = mysql_query_($StockModeSQL);
							unset($StockModeSQL);
							$prod = 0;
							$j = "";
							$k = 0;
							$NewHeight = '100'; //TD height which contains thumbnail
							
							if($stockcontrolmode != 4)
							{
								#MAKE ARRAY HAVING HEIGHT VAL OF ALL ITEMS PRIOR TO DISPLAY
								#SO THAT MAX HEIGHT CAN BE CAUGHT WHICH WILL BE APPLIED ON
								#EACH ROW ACCORDINGLY
								
								$ArrHeightMain = array(); #THIS WILL CONTAIN ALL ARRAYS CONTAINING HEIGHT VALS OF EACH ROW
								$intThumbColumnsStart = $intThumbColumns;
								while (list($product,$isgiftcert) = mysql_fetch_row_($qry_showproducts)) {
									if ($k == 0){
										$ArrHeightChild = array(); #THIS WILL CONTAIN HEIGHT VALS OF EACH
									}
									$k = $k + 1;
									$ArrHeightChild[] = GetImageHeight($product);
									if ($k >= $intThumbColumns){
										$ArrHeightMain[$intThumbColumnsStart] = $ArrHeightChild;
										$intThumbColumnsStart = ($intThumbColumnsStart * 2);
										$k = 0;
									}
								}
								
								#IF PRODUCT(S) ARE FOUND LESSER THAN $intThumbColumns OR COME IN SINGLE ROW
								if(mysql_num_rows_($qry_showproducts) < $intThumbColumns){
									$ArrHeightChild = isset($ArrHeightChild) ? $ArrHeightChild : "";
									$ArrHeightMain[$intThumbColumns] = $ArrHeightChild;
								}
								
								
								@mysql_data_seek_($qry_showproducts,0);
								$intThumbColumnsStart = $intThumbColumns;		
							 	
								if($subCategoryExist && ($display_subcategory_link_thumbnail=='Y' || ($display_subcategory_link_thumbnail=='M' && $parentid != 0) || ($display_subcategory_link_thumbnail=='T' && $parentid == 0))){
									echo "<tr><td colspan='$thumbnail_total_columns' valign='top' class='tbl-cart7-main-td' style=\"border: 0px;\">";
									showcategory_thumbnail($cat, $display_subcategory_link_thumbnail_column);
									echo "</td></tr>";
								}
								################### Category HTML between subcategory and items ###################
								$show_category_html = false;
								if(trim($category_html_between) != ""){
									$searchbotArray = (DetectBrowserInfo());
									$searchbot 		= $searchbotArray[0];
									if($searchbot != ""){
										$category_html_between	= 	str_replace("##cartid##","",$category_html_between);
									}
									else{
										$category_html_between	= 	str_replace("##cartid##","&cart=$cart",$category_html_between);
									}
									$category_html_between  =  replaceTextAndAffiliates($category_html_between);
									$show_category_html = true;
								}
								if($category_html_between != ""){
									if(isset($keywords) AND (isset($searchCat) AND is_numeric($searchCat) AND $searchCat>0) AND $show_category_html)
										echo "<tr><td valign=\"top\" colspan='$thumbnail_total_columns' align=\"left\" class='tbl-cart7-main-td' style=\"border: 0px;\">", $category_html_between ,"</td></tr>";
									elseif(!(isset($keywords) AND strlen(trim($keywords))>0) AND $show_category_html)
										echo "<tr><td class='tbl-cart7-main-td' valign=\"top\" colspan='$thumbnail_total_columns' align=\"left\" style=\"border: 0px;\">", $category_html_between, "</td></tr>";
								}
								################### Category HTML between subcategory and items ###################
								//else{ 
								$loop_val = 1;
								$j = 0;
								  while (list($product,$isgiftcert) = mysql_fetch_row_($qry_showproducts)) {
									  if ($j == 0) 
										  echo  "<tr>";
									  $j = $j + 1;
									  
									  if(is_array($ArrHeightMain[$intThumbColumnsStart]))
										  rsort($ArrHeightMain[$intThumbColumnsStart]);
									  
									  $prod =	showproduct_thumbnail($product,$shop,$cat,$cart,$stockcontrolmode,'','Y','','','',$ArrHeightMain[$intThumbColumnsStart][0],$keywords, $loop_val);
									  if ($j >= $intThumbColumns){
										  echo "</tr>";
										  $j = 0;
										  $intThumbColumnsStart = ($intThumbColumnsStart * 2);
									  }
									  
									  $prod++;
									  $loop_val++;
								  }
							//	}// end else
								
								unset($ArrHeightMain);
								
							} else {
							
								$ArrHeightMain = array();
								$intThumbColumnsStart = $intThumbColumns;
								$k = 0;
								while (list($product,$isgiftcert,$qtysum) = mysql_fetch_row_($qry_showproducts)) {
									if ($k == 0){
										$ArrHeightChild = array();
									}
									$k = $k + 1;
									$ArrHeightChild[] = GetImageHeight($product);
									if ($k >= $intThumbColumns){
										$ArrHeightMain[$intThumbColumnsStart] = $ArrHeightChild;
										$intThumbColumnsStart = ($intThumbColumnsStart * 2);
										$k = 0;
									}
								}

								if(mysql_num_rows_($qry_showproducts) < $intThumbColumns){
									$ArrHeightMain[$intThumbColumns] = $ArrHeightChild;
								}
								
								@mysql_data_seek_($qry_showproducts,0);
								$intThumbColumnsStart = $intThumbColumns;	
					
								if($subCategoryExist && ($display_subcategory_link_thumbnail=='Y' || ($display_subcategory_link_thumbnail=='M' && $parentid != 0) || ($display_subcategory_link_thumbnail=='T' && $parentid == 0))){
									echo "<tr><td colspan='$thumbnail_total_columns' valign='top' class='tbl-cart7-main-td' style=\"border: 0px;\">";
									showcategory_thumbnail($cat, $display_subcategory_link_thumbnail_column);
									echo "</td></tr>";
								}
							//	else{
								$loop_val = 1;
								$j=0;
								  while (list($product,$isgiftcert,$qtysum) = mysql_fetch_row_($qry_showproducts)) {
								  
									  if ($j == 0) 
										  echo  "<tr>";
									  $j = $j + 1;
									  if(is_array($ArrHeightMain[$intThumbColumnsStart]))
										  rsort($ArrHeightMain[$intThumbColumnsStart]);
									  
									  $prod =	showproduct_thumbnail($product,$shop,$cat,$cart,$stockcontrolmode,'','Y','','','',$ArrHeightMain[$intThumbColumnsStart][0],$keywords, $loop_val);
									  if ($j >= $intThumbColumns){
										  echo "</tr>";
										  $j = 0;
										  $intThumbColumnsStart = ($intThumbColumnsStart * 2);
									  }
									  $prod++;
									  $loop_val++;
								  }
							//	} // end else
								
								unset($ArrHeightMain);
							}
							
						} 
						elseif($keywords == '' && $calledfrom == "thumb" && $strThumbDisplay == "Y"){
								
								if($catalog3col == 6){
									showproduct_custom_layout($itemid,$shop,$cat,$cart,$stockcontrolmode);
								}
								else{
									showproduct($itemid,$shop,$cat,$cart,$stockcontrolmode);
								}
								//showproduct_thumbnail($itemid,$shop,$cat,$cart,$stockcontrolmode);
								$CSpan = $intThumbColumns+1;
								$searchbotArray = (DetectBrowserInfo());
								$searchbot 		= $searchbotArray[0];
								if($searchbot != ""){
									//echo "<tr><td align=cenetr colspan='$CSpan'><a href='",$index_string,"?shop=$shop&cat=$cat'>Back</a></td></tr>";
									$category_name_display  = showCategoryNameDisplay($cat);
									echo "<tr><td align='cenetr' colspan='$CSpan' style=\"border: 0px;\"><a href='",URL_SHOP_ALIAS_CATEGORY,"$category_name_display-$cat'>Back</a></td></tr>";
								}
								else
								{
									echo "<tr><td align='cenetr' colspan='$CSpan' style=\"border: 0px;\"><a href='",$index_string,"?shop=$shop&cat=$cat&cart=$cart'>Back</a></td></tr>";
								}
								
						} 
						else {						
								$sqlkeywordsarray = array();
								if(!isset($searchCat)) $searchCat = "";
								if(!isset($searchCatName)) $searchCatName = "";
								
								/************************************************************************************************
								Start of the search code comes here
								/************************************************************************************************/
								if ($display_category_in_searchbox == 'Y') { 
									if ($searchCat == 'All' || $searchCat == '') {
										$searchCatName = 'All';
										$searchCat = 0;
									} else {
										$rscatname = mysql_query_("SELECT name FROM category WHERE id = '{$searchCat}' AND is_deleted = 'N' AND category_list = 'Y' ");
										if($rscatname && mysql_num_rows_($rscatname)){
											list($searchCatName) = mysql_fetch_row_($rscatname);
											mysql_free_result_($rscatname);
										}
									}
									
								}
								
								
								//if search is made used custom header search form
								//slashes have to remove
								if(strpos($keywords,"\\\\") !==false){ 
									$keywords = stripslashes($keywords);
								}

								//if a search has two quotes like "Abraham Lincoln"  or Abraham "Lincoln" 
								//then have them disregard 
								$keywords = stripslashes(DisregardQuotes($keywords));
								$search_text_keywords = $keywords;
								$keywords = str_ireplace("'s","",$keywords);
								$sqlkeywords = KeyWordCleaner($keywords);
								$invalidCharacter = 0;
								if($sst == 'alphabetic'){
									if (!preg_match("/^[a-zA-Z0-9 -.]+$/", $keywords)) {
								   		//echo "A match was found.";
										$sqlkeywords = 'bannned';
										$invalidCharacter = 1;
									}
									else {
								   		//echo "A match was not found.";
										$sqlkeywords 	= KeyWordCleaner($keywords);
									}
								}
								elseif($sst == 'never' && $showSR == ''){
										$sqlkeywords = 'bannned';
								}
								else{
									$sqlkeywords 	= KeyWordCleaner($keywords);
								}	
								
								$sqlkeywords = str_replace("'","&#39;",$sqlkeywords);
								
								$keywords 	 	= KeyWordCleaner('',$keywords);
								$MatchCriteria = "";
								
								if(!isset($match_criteria))
									$match_criteria = 'all';

								if(isset($match_criteria) AND  $match_criteria == '')
									$match_criteria = 'all';
								
								if(isset($match_criteria) AND $match_criteria == 'all') {
									$MatchCriteria = "(matching all words)";
									$sqlkeywordsarray = explode(" ",$sqlkeywords);
								}
								
								if(isset($match_criteria) AND $match_criteria == 'whole') {
									$MatchCriteria = "(matching whole words only)";
									$sqlkeywordsarray = explode(" ",$sqlkeywords);
								} elseif(isset($match_criteria) AND $match_criteria == 'any'){
									$MatchCriteria =  "( matching any word ) ";
									$sqlkeywordsarray = split(" ",$sqlkeywords);
								}
								
								//******************************************************
								// Code added to put the keyword in the log for the keyword.
								//******************************************************
								if(!isset($search)) $search = "";
								if(trim($keywords) != ''){
									if ($searchCat == 'All' || $searchCat == '')
										$searchCat=0;
									($searchCat != '') ? putKeyword(mysql_real_escape_string_($keywords), $match_criteria, $searchCat) : putKeyword(mysql_real_escape_string_($keywords), $match_criteria);
								}
								//******************************************************
								
								##################################################################################
								#Code to remove trailing 's' from all words	
                                # AK, GRTteam # changing to remove 's' only for words longer than 8 chars #
								if(sizeof($sqlkeywordsarray)>=1){
									for($i= 0; $i< sizeof($sqlkeywordsarray); $i++){
										if (strtolower(substr($sqlkeywordsarray[$i],-2)) != "ss" && strtolower(substr($sqlkeywordsarray[$i],-1)) == "s" && $match_criteria !='whole' && (strlen($sqlkeywordsarray[$i]) > 8)){
											 $sqlkeywordsarray[$i] =	substr_replace($sqlkeywordsarray[$i],'',-1);
										}
									}
								}
								##################################################################################
								
								//$sqlkeywords = implode(" ",$sqlkeywordsarray);
								$search_string_name			="";
								$search_string_description	= "";
								$search_string_sku			= "";
								$search_string_productoption_desc = "";
								
								$j = (sizeof($sqlkeywordsarray) - 1);
								
								for($i= 0; $i< sizeof($sqlkeywordsarray); $i++)	{
									if ($match_criteria == 'whole'){										
										$Search_String_Name .= "FIND_IN_SET('$sqlkeywordsarray[$i]', REPLACE(product.name,' ',','))>0 OR ";
										$Search_String_Description .= "FIND_IN_SET('$sqlkeywordsarray[$i]', REPLACE(product.description,' ',','))>0 OR ";
										$Search_String_SKU .= "FIND_IN_SET('$sqlkeywordsarray[$i]', REPLACE(product.sku_pno,' ',','))>0 OR ";
										$Search_String_ProductOption_Description .= "FIND_IN_SET('$sqlkeywordsarray[$i]', REPLACE(productoption.description,' ',','))>0  OR ";
										
									}else{
										$search_string_name .= $sqlkeywordsarray[$i];
										$search_string_description .= $sqlkeywordsarray[$i];
										$search_string_sku .= $sqlkeywordsarray[$i];
										$search_string_productoption_desc .= $sqlkeywordsarray[$i];
									}
									
									if($i < $j){
										if ($match_criteria == "all"){
											$search_string_name .= "%' AND product.name LIKE '%";
											$search_string_description .= "%' AND product.description LIKE '%";
											$search_string_sku .= "%' AND sku_pno  LIKE '%";
											$search_string_productoption_desc .= "%' AND productoption.description  LIKE '%";
										} elseif ($match_criteria == "whole"){
											
										} else {										
											$search_string_name .= "%' OR product.name LIKE '%";
											$search_string_description .= "%' OR product.description LIKE '%";
											$search_string_sku .= "%' OR sku_pno  LIKE '%";
											$search_string_productoption_desc .= "%' OR productoption.description LIKE '%";
										}
									}
								}
								
								if ($searchCat != 0 && intval($searchCat)){
									$searchCat = intval($searchCat);
									$sub_cat_list = listCatTree($searchCat);
									$search_cat_list = $sub_cat_list.$searchCat;
									$appendCat = " AND pc.category_pc_id IN($search_cat_list) AND pc.product_pc_id = product.id";	
								} else {
									$appendCat = " AND product.id=product_pc_id";
								}
								if($stockcontrolmode != 4) {
									if($keywords == "submit_custom_search"){
										$query =  "SELECT DISTINCT product.id AS id FROM  ";
										$query .= ($appendCat=='')?'':" product_category pc, ";
										$query .=   "	product LEFT JOIN productoption ON product.id = productoption.productid
														WHERE (is_deleted='N') {$custom_search_qry} AND display_product_in_cart = 'Y' ".$appendCat;											   
										$query .= " AND pc.product_pc_id=product.id ";
										$query .= "GROUP BY pc.product_pc_id,pc.category_pc_id";
									}
									else{
										if (isset($match_criteria) AND $match_criteria != 'whole') {
											$query =  "SELECT DISTINCT product.id AS id FROM ";
											$query .= ($appendCat=='')?'':" product_category pc, ";
											$query .=   " category, product LEFT JOIN productoption ON product.id = productoption.productid
													   WHERE (product.is_deleted='N') AND (product.name LIKE '%".$search_string_name."%'";

											if($itemsperpage < 35 || 1) {
												$query .=" OR product.description LIKE '%".$search_string_description."%' ";
											}
											
											$query .=" OR sku_pno LIKE '%". $search_string_sku."%'
													   OR productoption.description LIKE '%".$search_string_productoption_desc."%') 
                                                       AND category.id=category_pc_id AND category.is_deleted='N' AND category.category_list = 'Y'
													   AND display_product_in_cart = 'Y' ".$appendCat;
													   
											$query .= " AND pc.product_pc_id=product.id ";
											$query .= "GROUP BY pc.product_pc_id,pc.category_pc_id";
										} else {
											$WHOLE_KEY_WORDS = substr($Search_String_Name.$Search_String_Description.$Search_String_SKU.$Search_String_ProductOption_Description,0,-3);
											 $query =  "SELECT DISTINCT product.id AS id FROM  ";
											 $query .= ($appendCat=='')?'':" product_category pc, ";
											 $query .=   "	product LEFT JOIN productoption ON product.id = productoption.productid
															WHERE (is_deleted='N') AND ($WHOLE_KEY_WORDS) AND display_product_in_cart = 'Y' ".$appendCat;
											$query .= " AND pc.product_pc_id=product.id ";
											$query .= "GROUP BY pc.product_pc_id,pc.category_pc_id";
										}	
									}

									$qry_countproducts = mysql_query_($query);
									if($qry_countproducts) {
										$numprods = $reccount = mysql_num_rows_($qry_countproducts);
										unset($query);
										mysql_free_result_($qry_countproducts);
									}
									
								} else {
								
									$prodcount = 0;
									$prodlist = "";
									$ProductArray = array();
									if(isset($match_criteria) AND $match_criteria == 'whole') {
										$search_string_name = $sqlkeywords;
										$search_string_description = $sqlkeywords;
										$search_string_sku = $sqlkeywords;
										$search_string_productoption_desc = $sqlkeywords;
										$WHOLE_KEY_WORDS = substr($Search_String_Name.$Search_String_Description.$Search_String_SKU.$Search_String_ProductOption_Description,0,-3);
										
										$query = "SELECT DISTINCT product.id AS id, 
										REPLACE(position(lower('$sqlkeywords') IN lower(product.name)),'0','1000') AS  pos 
												  FROM product_category pc, product 
												  LEFT JOIN productoption ON product.id = productoption.productid
												  WHERE (is_deleted='N') AND 
												  ($WHOLE_KEY_WORDS) AND display_product_in_cart = 'Y' 
												   AND pc.`product_pc_id` = product.`id` 
												  ". $appendCat ." {$show_one_result_per_sku_query} 
												  ORDER BY pos ";
									} else {										
										$query = "SELECT DISTINCT product.id AS id, 
										REPLACE(position(lower('$sqlkeywords') IN lower(product.name)),'0','1000') AS  pos 
												  FROM product_category pc, product 
												  LEFT JOIN productoption ON product.id = productoption.productid
												  WHERE (is_deleted='N') 
												  AND  (name LIKE '%".$search_string_name."%' ";
										if($itemsperpage < 35 || 1) {
												$query .=		" OR product.description LIKE '%".$search_string_description."%'";
										}
										$query .= " OR sku_pno LIKE '%".$search_string_sku."%'  
											  OR productoption.description LIKE '%".$search_string_productoption_desc."%') 
											  AND display_product_in_cart = 'Y' 
											  AND pc.`product_pc_id` = product.`id` 
											  ". $appendCat ."   {$show_one_result_per_sku_query} ORDER BY pos ";
									}
										
									$qry_countproducts = mysql_query_($query);
									while (list ($prodid) = mysql_fetch_row_($qry_countproducts)){
										$qry_getproductoption = mysql_query_("SELECT sum(stockqty) as qtysum FROM productoption WHERE productid=$prodid");
										list ($qtysum) = mysql_fetch_row_($qry_getproductoption);
										if ($qtysum > 0){
											$prodcount++;
											$ProductArray[] = $prodid;
										}
									}
									
									if(sizeof($ProductArray)){
										$ProductArray = array_unique($ProductArray);
										$prodlist = implode(',',$ProductArray);
										unset($ProductArray);
									}

									unset($query);
									mysql_free_result_($qry_countproducts);
									$numprods = $reccount = $prodcount;
									
								}
								if(isset($match_criteria) && $match_criteria == 'all' && $numprods == 0 && str_word_count($keywords) > 4) {


									$keywords_new = str_word_count($keywords, 1);

									$no_of_keywords = ceil(count($keywords_new) / 2);
									$keywords_new = array_slice($keywords_new, 0, $no_of_keywords);
									$keywords = implode(' ', $keywords_new);
									$_SESSION['close_match'] = 1;
									$new_sarch_url = str_replace("/shop/", SEARCH_ALIAS, $url_start);
									$new_sarch_url = $new_sarch_url.urlencode($keywords);
									header("Location: $new_sarch_url");
									die;
								}
								$srch_query = "";
								if ($stockcontrolmode != 4){
									$search_link_categories = "Y";
									if($search_link_categories == "Y" && !strpos($requestURI,"/searchCat/")  && $reccount  > $limit_link_categories){
										$show_one_result_per_sku_query=" GROUP BY pc.category_pc_id ";
										$itemsperpage = "10000";
										$order_by = " category.name";
									}
									if(isset($match_criteria) AND $match_criteria == "all") {
										if($item_sort == "Y" || $reccount  > $limit_link_categories){
											$srch_query = "SELECT DISTINCT product.id AS id,
													   pc.category_pc_id AS categoryid,
													   REPLACE(position(lower('$sqlkeywords') IN lower(product.name)),'0','1000') AS  pos
													   FROM 
													   category, product_category pc, product 
													   LEFT JOIN productoption ON product.id = productoption.productid
													   WHERE (product.is_deleted='N') AND (product.name LIKE '%".$search_string_name."%'";
													   if($itemsperpage < 35 || 1) {
													   	$srch_query .= " OR product.description LIKE '%".$search_string_description."%'"; 
													 	 }
													   $srch_query .= " OR sku_pno LIKE '%".$search_string_sku."%'
													   OR productoption.description LIKE '%".$search_string_productoption_desc."%') 
													   AND display_product_in_cart = 'Y' 
													   AND pc.`product_pc_id` = product.`id` 
													   AND category.id=category_pc_id AND category.is_deleted='N' AND (category.category_list = 'Y' OR category.category_list = 'C')
													   " .$appendCat . " {$show_one_result_per_sku_query} 
													   ORDER BY $order_by
													   LIMIT $rec, $itemsperpage";
										}
										else {
											if( $search_item_name_first == 'N' || $full_search == 'Y'){
											 	$srch_query = "SELECT DISTINCT product.id AS id,
											 		   pc.category_pc_id AS categoryid,
													   REPLACE(position(lower('$sqlkeywords') IN lower(product.name)),'0','1000') AS  pos, 
													   IF(product.name LIKE '%".$search_string_name."%', 1, 0 ) AS one,
													   IF(product.description LIKE '%".$search_string_description."%', 1, 0 ) AS two,
													   IF(sku_pno LIKE '%".$search_string_sku."%', 1, 0 ) AS three,
													   IF(productoption.description LIKE '%".$search_string_productoption_desc."%', 1, 0 ) AS four
													   FROM 
													   category, product_category pc, product 
													   LEFT JOIN productoption ON product.id = productoption.productid
													   WHERE (product.is_deleted='N') 
													   AND (product.name LIKE '%".$search_string_name."%' 
													   OR product.description LIKE '%".$search_string_description."%' 
													   OR sku_pno LIKE '%".$search_string_sku."%'
													   OR productoption.description LIKE '%".$search_string_productoption_desc."%') 
													   AND display_product_in_cart = 'Y' 
													   AND pc.`product_pc_id` = product.`id` 
													   AND category.id=category_pc_id AND category.is_deleted='N' AND (category.category_list = 'Y' OR category.category_list = 'C')
													   " .$appendCat . " {$show_one_result_per_sku_query}
													   ORDER BY one desc, two desc, three desc, four desc
													   LIMIT $rec, $itemsperpage"; 
												} else {
													$srch_query = "SELECT DISTINCT product.id AS id,
											 		   pc.category_pc_id AS categoryid,
													   REPLACE(position(lower('$sqlkeywords') IN lower(product.name)),'0','1000') AS  pos, 
													   IF(product.name LIKE '%".$search_string_name."%', 1, 0 ) AS one
													   FROM 
													   category, product_category pc, product 
													   
													   WHERE (product.is_deleted='N')
													   AND (product.name LIKE '%".$search_string_name."%' 
													   OR product.description LIKE '%".$search_string_description."%' 
													   OR sku_pno LIKE '%".$search_string_sku."%')
													   AND display_product_in_cart = 'Y' 
													   AND pc.`product_pc_id` = product.`id` 
													   AND category.id=category_pc_id AND category.is_deleted='N' AND (category.category_list = 'Y' OR category.category_list = 'C')
													   " .$appendCat . " {$show_one_result_per_sku_query}
													   ORDER BY one desc
													   LIMIT $rec, $itemsperpage"; 
												}
												}
											}
									elseif(isset($match_criteria) AND $match_criteria == "whole") {
										$WHOLE_KEY_WORDS = substr($Search_String_Name.$Search_String_Description.$Search_String_SKU.$Search_String_ProductOption_Description,0,-3);
										 $srch_query = "SELECT DISTINCT product.id AS id,
														pc.category_pc_id  AS categoryid,
														REPLACE(position(lower('$sqlkeywords') IN lower(product.name)),'0','1000') AS  pos
														FROM category, product_category pc, product  
													    LEFT JOIN productoption ON product.id = productoption.productid
														WHERE (product.is_deleted='N') 
														AND ($WHOLE_KEY_WORDS) 
														AND display_product_in_cart = 'Y' 
														 AND pc.`product_pc_id` = product.`id` 
														 AND category.id=category_pc_id AND category.is_deleted='N' AND (category.category_list = 'Y' OR category.category_list = 'C')
														" .$appendCat . " {$show_one_result_per_sku_query} 	
														ORDER BY $order_by
														LIMIT $rec, $itemsperpage";
									}
									elseif(isset($match_criteria) AND $match_criteria == "any") {	
										$srch_query = "SELECT DISTINCT product.id AS id,
														pc.category_pc_id  AS categoryid,
														REPLACE(position(lower('$sqlkeywordsarray[0]') IN lower(product.name)) ,'0','1000') AS pos
														FROM category, product_category pc, product 
													    LEFT JOIN productoption ON product.id = productoption.productid
														WHERE (product.is_deleted='N') 
														AND (product.name LIKE '%".$search_string_name."%'";
														if($itemsperpage < 35 || 1) {
														 $srch_query .= " OR product.description LIKE '%".$search_string_description."%'"; 
														}
														$srch_query .= " OR sku_pno LIKE '%".$search_string_sku."%'
														OR productoption.description LIKE '%".$search_string_productoption_desc."%') 
														AND display_product_in_cart = 'Y'
														 AND pc.`product_pc_id` = product.`id`
														 AND category.id=category_pc_id AND category.is_deleted='N' AND (category.category_list = 'Y' OR category.category_list = 'C')
														" .$appendCat . " {$show_one_result_per_sku_query} 
														ORDER BY $order_by
														LIMIT $rec, $itemsperpage";
									}
								} else {
										if(!empty($prodlist)) {
											$srch_query_param = '';
											if(!empty($prodlist)) {
												$srch_query_param = "AND product.id IN ($prodlist)";
											}	
										}
										$srch_query = "SELECT DISTINCT product.id AS id,
														pc.category_pc_id  AS categoryid,
														REPLACE(position(lower('$sqlkeywords') IN lower(product.name)),'0','1000') AS  pos
														FROM category, product_category pc, product  
													    LEFT JOIN productoption ON product.id = productoption.productid
														WHERE (product.is_deleted='N') {$srch_query_param} 
														AND display_product_in_cart = 'Y'  
														AND pc.`product_pc_id` = product.`id`  
														AND category.id=category_pc_id AND category.is_deleted='N' AND (category.category_list = 'Y' OR category.category_list = 'C')
														" .$appendCat . " 
														{$show_one_result_per_sku_query}
														ORDER BY $order_by
														LIMIT $rec, $itemsperpage";		
								}
								if($keywords == "submit_custom_search"){
									$srch_query = "SELECT DISTINCT product.id AS id,
														pc.category_pc_id  AS categoryid,
														REPLACE(position(lower('$sqlkeywords') IN lower(product.name)),'0','1000') AS  pos
														FROM category, product_category pc, product  
													    LEFT JOIN productoption ON product.id = productoption.productid
														WHERE (product.is_deleted='N') 
														{$custom_search_qry} 
														AND display_product_in_cart = 'Y' 
														 AND pc.`product_pc_id` = product.`id` 
														 AND category.id=category_pc_id AND category.is_deleted='N' AND (category.category_list = 'Y' OR category.category_list = 'C')
														" .$appendCat . " {$show_one_result_per_sku_query} 
														ORDER BY $order_by
														LIMIT $rec, $itemsperpage";	
								}

								//echo $srch_query;
								$qry_showproducts = mysql_query_($srch_query);
								if($keywords == "submit_custom_search") {
									$reccount = mysql_num_rows_($qry_showproducts);
								}

								
								/***********************************************************************************************
								End of search code
								************************************************************************************************/
								if( $strThumbDisplay != "Y")
									$CSpan = 5;
								else
									$CSpan = $intThumbColumns+1;
								
								if($keywords != "submit_custom_search"){
									if($sst == 'alphabetic' && $invalidCharacter == 1){
										echo "<tr><td colspan='$CSpan'><span class='searchtext' style=\"border: 0px;\">$customizableFields[212]</span></td></tr>";
									}								
									elseif($sst == 'never'){
										echo "<tr><td colspan='$CSpan'><span class='searchtext' style=\"border: 0px;\">$customizableFields[212]</span></td></tr>";
									}
									else{
										echo "<tr><td colspan='$CSpan'><span class='searchtext' style=\"border: 0px;\">$customizableFields[213]</span><b class=searchkeyword>", 
										 str_replace("\\","",GetFilterizedHMTLEntities(html_entity_decode($search_text_keywords,ENT_QUOTES))),
										 "</b>&nbsp; <span class='searchtext'>";
										 if(!isset($_SESSION['close_match'])) {
										 	echo GetFilterizedHMTLEntities($MatchCriteria);
										 	echo str_replace("\\","",htmlspecialchars($searchCatName)), " ";
										 }
										 echo "</span></td></tr>";
									}
								}
/*if(($search_item_name_first == 'Y' || $full_search == 'N') && $reccount < 10) {
							echo "<tr><td colspan='$CSpan'><span class='searchtext' style=\"border: 0px;\"><a href='/search/$keywords?opt=all'>Also search the description, SKU, and dropdowns etc. </a></span></td></tr>";
						}*/
								if ($reccount == 0 && $match_criteria != 'whole' && !isset($_REQUEST['submit_custom_search'])){
									echo "<tr><td  colspan=$CSpan class=searchnotfound style=\"border: 0px;\"> $customizableFields[216]";
									if($display_celldividerbar == 'Y')
										echo "<hr color='",$dividercellcolor,"' size=1>";
									echo "</td></tr>";
									
								} else {
									if($search_link_categories == "Y" && !strpos($requestURI,"/searchCat/") && $reccount  > $limit_link_categories){
										echo "<tr><td colspan='$CSpan' class='tdsearchfound' style=\"border: 0px;\">";
									}
									else{
										if(isset($_SESSION['close_match'])) {
											echo "<tr><td colspan='$CSpan' class='tdsearchfound' style=\"border: 0px;\">No exact matches found. Close matches are listed below:";
											unset($_SESSION['close_match']);
										} else {
										echo "<tr><td colspan='$CSpan' class='tdsearchfound' style=\"border: 0px;\">$customizableFields[214] <b>", GetFilterizedHMTLEntities($reccount), "</b> $customizableFields[215]";//</td></tr>";
										}

									}
									if($display_celldividerbar == 'Y')
										echo "<hr color='", GetFilterizedHMTLEntities($dividercellcolor), "' size=1>";
									echo "</td></tr>";
									
									
									//////////////////// START CATEGORY LINK /////////////////////									
									if($search_link_categories == "Y" && !strpos($requestURI,"/searchCat/")){							  
									  $qry_showproducts1 = mysql_query_($srch_query);
									  while (list($product,$mycat,$pos) = mysql_fetch_row_($qry_showproducts1)){
										$srch_query_new = str_replace("GROUP BY pc.category_pc_id","AND pc.category_pc_id = $mycat GROUP BY product.id",$srch_query);
										$category_products[$mycat] = mysql_num_rows_(mysql_query_($srch_query_new));
									  }
									}
									
									
									if($search_link_categories == "Y" && !strpos($requestURI,"/searchCat/") && $reccount  > $limit_link_categories){
									 $search_categories_url = str_replace("/shop/",SEARCH_ALIAS,$url_start);
									  echo "<tr><td style=\"border: 0px;\">";
									  echo $text_link_categories = str_replace('[xx]',$reccount,stripslashes($text_link_categories));
									  echo "</td></tr>";
									  if ($mobile_view) {
									  	$td_search_category = 2;
									  } else {
									  	$td_search_category = ($category_columns <= 0 ) ? 3 : $category_columns;
									  }
									  echo "<tr><td style=\"border: 0px;\"><table cellspacing=2 style=\"border:0px; cellpadding:2px;\">";
									  $j = 0;
									  while (list($product,$mycat,$pos) = mysql_fetch_row_($qry_showproducts)) {
										  if ($j == 0) echo "<tr>";
				  						  $j = $j + 1; 
										  $cat_name = showCategoryNameDisplay($mycat);
										  $display_cat_name = getCatName($mycat);
										  if($display_cat_name!= ""){
										  	echo "<td>";
											//echo "<td><a href='".$search_categories_url."$keywords/match_criteria/$match_criteria/searchCat/$mycat'>".$display_cat_name."</a>";
										  	$url_start_without_shop = str_replace("/shop/", "", $url_start);
											$catname = showCategoryNameDisplay($mycat);
										  	echo "<td style=\"border: 0px;\"><a href='".$url_start_without_shop . URL_SHOP_ALIAS_CATEGORY . "$catname-$mycat'>".$display_cat_name."</a>";	
										  	echo "<font size = '1'> ($category_products[$mycat] items found)</font>";
										  	echo "</td>";
										  }
										  if ($j >= $td_search_category){
					  						echo "</tr>"; 
					  						$j = 0;
				  						  }
									  }
									  echo "</table></td></tr>";
									}
									//////////////////// END CATEGORY LINK ///////////////////////
									else{
									//SHOW TOP PAGING									
									if($show_top_pager == "Y"){
										if ($numprods > $itemsperpage){ 
											$numpages = intval($numprods / $itemsperpage);
											if ($numpages != ($numprods / $itemsperpage))
											$numpages = $numpages +1;
											$currpage = ($rec == 0) ? 1 : ($rec / $itemsperpage) + 1;
											if ($numprods > $itemsperpage){
												echo "<tr>
													<td align='right' colspan='$CSpan' class='tdpaging' style=\"border: 0px;\">
													<br />";
												include("pager.php");
												echo "</td></tr>";
											}
										}
									}

									//END SHOW TOP PAGING
									
									$k=0;
									$NewHeight = '100'; //TD height which contains thumbnail	
									$ArrHeightMain = array();
									$intThumbColumnsStart = $intThumbColumns;
									while (list($product,$mycat,$pos) = mysql_fetch_row_($qry_showproducts)) {									
										if ($k == 0){
											$ArrHeightChild = array();
										}
										$k = $k + 1;
										
										$ArrHeightChild[] = GetImageHeight($product);
										if ($k >= $intThumbColumns){
											$ArrHeightMain[$intThumbColumnsStart] = $ArrHeightChild;
											$intThumbColumnsStart = ($intThumbColumnsStart * 2);
											$k = 0;
										}
									}
									
									if(mysql_num_rows_($qry_showproducts) < $intThumbColumns){
										$ArrHeightMain[$intThumbColumns] = $ArrHeightChild;
									}

									@mysql_data_seek_($qry_showproducts,0);
									$intThumbColumnsStart = $intThumbColumns;
									$j=0;
									$loop_val = 1;
									while (list($product,$mycat,$pos) = mysql_fetch_row_($qry_showproducts)){										
										if ($stockcontrolmode != 4){										
											if( $strThumbDisplay == "Y"  AND ($search_displayfull =='Y'|| $search_displayfull =='B'))	{
												if ($j == 0) 
													echo  "<tr>";
													
												$j = $j + 1;
												if(is_array($ArrHeightMain[$intThumbColumnsStart]))
													rsort($ArrHeightMain[$intThumbColumnsStart]);
												
												$prod =	showproduct_thumbnail($product,$shop,$cat,$cart,$stockcontrolmode,$search_displayfull,'Y','','','',$ArrHeightMain[$intThumbColumnsStart][0],$keywords, $j, $loop_val);
												if ($j >= $intThumbColumns)	{
													echo "</tr>";
													$j = 0;
													$intThumbColumnsStart = ($intThumbColumnsStart * 2);
												}
												$prod++;
												$loop_val++;
											} else 	{												
												if($catalog3col == 6 && ($search_displayfull =='Y' || $search_displayfull =='B')){
													showproduct_custom_layout($product,$shop,$mycat,$cart,$stockcontrolmode,$search_displayfull);
												}
												else{
													showproduct($product,$shop,$mycat,$cart,$stockcontrolmode,$search_displayfull);
												}
											}
										} else {
											$prodcount = 0;
											$qry_getproductoption = mysql_query_("SELECT sum(stockqty) as qtysum FROM productoption WHERE productid='{$product}'");
											list ($qtysum) = mysql_fetch_row_($qry_getproductoption);
											if ($qtysum > 0) {
												if( $strThumbDisplay == "Y" AND ($search_displayfull =='Y' || $search_displayfull =='B')) {
													if ($j == 0) 
														echo  "<tr>";
														
														$j = $j + 1;
														if(is_array($ArrHeightMain[$intThumbColumnsStart]))
															rsort($ArrHeightMain[$intThumbColumnsStart]);
														
														$prod =	showproduct_thumbnail($product,$shop,$mycat,$cart,$stockcontrolmode,'','Y','','','',$ArrHeightMain[$intThumbColumnsStart][0],$keywords, $loop_val);											
														if ($j >= $intThumbColumns)	{
															echo "</tr>";
															$j = 0;
															$intThumbColumnsStart = ($intThumbColumnsStart * 2);
														}
													$prod++;
													$loop_val++;
												} else {													
													if($catalog3col == 6){
														showproduct_custom_layout($product,$shop,$mycat,$cart,$stockcontrolmode,$search_displayfull);
													}
													else{
														showproduct($product,$shop,$mycat,$cart,$stockcontrolmode,$search_displayfull);
													}
												}
											}
										}
									}
									unset($_SESSION['breadcrumbs_catid']);
									unset($ArrHeightMain);
								}
						} // end else	 
						}

						
						if (isset($keywords) AND strlen(trim($keywords)) > 0) {
							$qry_search_pages = "SELECT page_name, page_url 
												 FROM pages WHERE 
												 page_name LIKE '%$keywords' OR
												 page_url LIKE '%$keywords' OR
												 page_html LIKE '%$keywords' OR
												 page_title_tag LIKE '%$keywords' OR
												 page_description_tag LIKE '%$keywords' OR
												 page_keywords LIKE '%$keywords'";

							$rs_search_pages = mysql_query_($qry_search_pages);
							if (!empty($rs_search_pages->num_rows)) {
								while(list($page_name, $page_url) = mysql_fetch_array_($rs_search_pages)) {
									$page_name = (trim($page_name) != '') ? $page_name : $page_url;
									echo "<tr><td colspan='2' style=\"border: 0px;\"><a href='$page_url'>$page_name</a></td></tr>";
								}
							}
						}
			
 				# removed by ken 2/18/08     echo "</table>",
				$item_fit_in_page = ($numprods % $thumbnail_total_columns);

 				    if (($numprods > $itemsperpage) || !$item_fit_in_page)
						echo "</table><!-- tbl-thumbnail-position-fitter-end -->";//echo "</tr></table><!-- tbl-thumbnail-position-fitter-end -->";
					else
						echo "</tr></table><!-- tbl-thumbnail-position-fitter-end -->"; 
					
					if($thumbnail_display =='Y' || !$numprods) $add_item_per_page_footer = "";
					echo $add_item_per_page_footer = ($add_item_per_page_footer) ? "<div style='text-align:right'>".$add_item_per_page_footer."</div>" : "";
				    echo  "</td></tr>";
				?> <!-- END SHOW PRODUCTS --><!-- SHOW ABOUT GIFTREGISTER  -->				<?php 
				if( isset($_SESSION["giftregistrycart"]) && ($_SESSION["giftregistrycart"] == 1) && (isset($_GET['giftadded']) && $_GET['giftadded'] == 1)){
					echo "<tr><td style=\"border: 0px;\">&nbsp;</td></tr>",
						 "<tr><td align='center' bgcolor=\"#FCFCDF\" style=\"border: 0px;\">";
					
					if ($_GET['giftadded'] == 1)
						echo "<font color='blue'>$customizableFields[240]</font>";
					else
						echo "<font color='red'>$customizableFields[241]</font>";
						
					$searchbotArray = (DetectBrowserInfo());
					$searchbot 		= $searchbotArray[0];
					if($searchbot != ""){
						echo	"&nbsp;$customizableFields[242] ",
								"<a href=gr_listings.php?gr_id=",$_SESSION["gr_id"],"&cart=$cart>$customizableFields[208]</a>",
								"</td></tr>";
					}
					else{
						echo	"&nbsp;$customizableFields[242] ",
								"<a href=gr_listings.php?cart=",$cart,"&gr_id=",$_SESSION["gr_id"],">$customizableFields[208]</a>",
								"</td></tr>";
					}
				}
				?><!-- SHOW ABOUT GIFTREGISTER  --><!-- BOTTOM PAGINATION START --><?php  
			$search_link_categories = isset($search_link_categories) ? $search_link_categories : "";
			if($search_link_categories == "Y" && !strpos($requestURI,"/searchCat/") && $reccount  > $limit_link_categories){
				// nothing
			}
			else{
				
			if ($numprods > $itemsperpage){ ?>
			
			<?php  if(!isset($match_criteria)){ $match_criteria = ""; } ?>
			<?php 
			if($match_criteria == "" && $keywords == ""){
			  if(strpos($requestURI,"/rec")){
				  $go_url = ($rec+$itemsperpage);
				  $go_method = "post";
			  }
			  else{
				  $go_url = htmlentities($category_name_display)."-$cat/rec/".($rec+$itemsperpage);
				  $go_method = "post";
			  }
			}
			else{
				if(strpos($requestURI,"/rec")){
					$go_url = ($rec+$itemsperpage);
				}
				$go_method = "post";
				
			}
			
			?>
				<tr><td colspan="2">                
                <form name="pageform" action="<?php  echo $go_url?>" method="<?php  echo $go_method?>" style="margin:0px">				
                <table width="100%" style="align:center; border:0px; cellpadding:0px;" cellspacing="0">
				<?php  //if($display_celldividerbar == 'Y') echo "<hr color='{$dividercellcolor}' size=1>"; 

				// Paging
				$numpages = intval($numprods / $itemsperpage);
				if ($numpages != ($numprods / $itemsperpage))
				$numpages = $numpages +1;
				
				$currpage = ($rec == 0) ? 1 : ($rec / $itemsperpage) + 1;
				if ($numprods > $itemsperpage){
				?>
					<tr><td align='right'  class='tdpaging'><br /><?php  include("pager.php"); ?></td></tr>
				<?php  } ?>
					<tr>
					<td align="center" height="50">
										<input type='hidden' name='csrf_token' value='<?php generateCSRFToken()?>'>
                    <input type="hidden" name="cart" value="<?php  echo GetFilterizedHMTLEntities($cart)?>" />
                    <input type="hidden" name="cat" value="<?php  echo GetFilterizedHMTLEntities($cat)?>" />
                    <input type="hidden" name="keywords" value="<?php  echo urldecode(GetFilterizedHMTLEntities(stripslashes($keywords)))?>" />
                    <input type="hidden" name="match_criteria" value="<?php  echo GetFilterizedHMTLEntities($match_criteria)?>" />
                    <input type="hidden" name="rec" value="<?php  echo GetFilterizedHMTLEntities(($rec + $itemsperpage))?>" />
                    <input type="hidden" name="numprods" value="<?php  echo $numprods?>" />
                    <?php 
					if($keywords == "submit_custom_search"){
						echo "<input type=\"hidden\" value=\"submit_custom_search\" name=\"submit_custom_search_hidden\" />";
						echo "<input type=\"hidden\" value=\"$custom_search_qry\" name=\"custom_search_qry\" />";
					}
					?>
						<?php  if(isset($searchCat)){ 
							echo "<input type='hidden' name='searchCat' value=\"", GetFilterizedHMTLEntities($searchCat), "\" />";
						 } ?>
						<?php  if ($rec >0 ) { ?>
						<input type="submit" name="goback" class="btnPaging"  value="<?php  echo $customizableFields[243]?>" />&nbsp;&nbsp;
						<?php  	} ?>
						
						<?php  if ($numprods > ($rec + $itemsperpage)){ ?>
					    <input type="submit" class="btnPaging" name="gonext" value="<?php  echo $customizableFields[244]?>" />
						<?php  } ?>
					</td>
					</tr>
				 </table></form></td></tr>					
			<?php  }			
 			} // end else
			################### Category HTML below items listing ###################
			$show_category_html = false;
			if(trim($category_html_below) != ""){
			  $searchbotArray = (DetectBrowserInfo());
			  $searchbot 		= $searchbotArray[0];
			  if($searchbot != ""){
				  $category_html_below	= 	str_replace("##cartid##","",$category_html_below);
			  }
			  else{
				  $category_html_below	= 	str_replace("##cartid##","&cart=$cart",$category_html_below);
			  }
			  $category_html_below  =  replaceTextAndAffiliates($category_html_below);
			  $show_category_html = true;
			 }
			 if($category_html_below != ""){			
			  if(isset($keywords) AND (isset($searchCat) AND is_numeric($searchCat) AND $searchCat>0) AND $show_category_html)
				  echo "<tr><td valign=\"top\" align=\"left\" style=\"border: 0px;\">", $category_html_below ,"</td></tr>";
			  elseif(!(isset($keywords) AND strlen(trim($keywords))>0) AND $show_category_html)
				  echo "<tr><td valign=\"top\" align=\"left\" style=\"border: 0px;\">", $category_html_below, "</td></tr>";
			}
			################### Category HTML below items listing ###################
} ?><!-- BOTTOM PAGINATION END --><?php 
			} // end if(!$page_call)
			else{
				$page_html = html_entity_decode(mysql_result_(mysql_query_("Select page_html From pages Where id=$page_id"),0));
				echo "<tr><td valign=\"top\" align=\"left\" style=\"border: 0px;\">$page_html</td></tr>";
			}?></table><!-- End ContentsContainer --><?php  	if((strpos($header,"##category links##") == false && strpos($footer,"##category links##") == false) && ($globalcats || $displaycatlinks) && $itemid == ""){ // SHOW CATEGORIES IF ENABLED?></td></tr></table><!-- End MainTable --><?php  } ?><div id="div_multi_product_counter" style="display:none"><?php  //=implode(",", $multi_product_counter)?></div><!-- NEW INDEX PAGE END-->
<?php 
} 
?>

<?php 
if($add_to_cart_option == 'P' || $quick_view == 'Y' || isset($_SESSION['insert_jquery_files'])){
	echo "<div id=\"divAddToCart\" style=\"display:none\"></div>";
}
if(stristr($_SERVER['HTTP_REFERER'],"facebook")){
	sendOKacknowledgement();
}

unset($background, $dividercellcolor, $displaycatlinks, $itemsperpage, $search_displayfull, $show_top_pager, $display_category_in_searchbox, $thumbnail_display, $thumbnail_title_display, $thumbnail_price_display, $thumbnail_total_columns, $display_celldividerbar, $main_category_separator, $main_category_columns, $category_separator, $category_columns, $totalMainCategories, $totalCategories, $display_items_alignment);
$footer =  showfooter($shop,$cart,$usecustom=1,$tableWidth="100%", $cat, $itemtitle);
//$footer = str_replace("</body>", "<script>runAuto('{$currency_name}')</script></body>", $footer);
echo $footer;
echo "<!-- catid: {$_SESSION['breadcrumbs_catid']} -->";
mysql_close_($mysql_link);
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
if($_SERVER['SERVER_NAME'] == "clarionworld.precisionweb.net" )
	echo "<font color='#ffffff'>This page was created in ".$totaltime." seconds</font>";
?>