<?php
#define mccc /* (this should be a valid comment in Perl, C, C++, & PHP)
#
# COPYRIGHT NOTICE
#
# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
# The enclosed or following software code is the sole property
# of Michael Chaney Consulting Corporation.  Michael Chaney Consulting
# Corporation reserves all rights in this software not explicitly
# granted to you by Michael Chaney Consulting Corporation or its
# representatives.
# You may not record, store, reproduce, and/or transmit this
# software in any medium, electronic or otherwise, without the
# express written consent of Michael Chaney Consulting Corporation.
# ALL RIGHTS RESERVED.
# Copyright 2003 Michael Chaney Consulting Corporation
# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
#
# END COPYRIGHT NOTICE
# */

# Different ways to use search.php:
#
# Normal searches:
#
# ?searchtype=full&searchtext=look+for+me
# ?searchtype=part&searchtext=part_number
# ?searchtype=desc&searchtext=look+for+me+in+description
#
# Browse vendors, categories, or vendcats:
#
# ?searchtype=vendor&vendor_id=11826  (vendor_group_id)
# ?searchtype=category&category_id=10
# ?searchtype=vendcat&vendor_id=11921&category_id=23
#
# Search within a vendor, category, or vendcat:
#
# ?searchtype=full&searchtext=find+me&subsearchtype=vendor&vendor_id=12200
# ?searchtype=full&searchtext=find+me&subsearchtype=vendcat&vendor_id=12200&category_id=9
# ?searchtype=full&searchtext=find+me&subsearchtype=category&category_id=21
#
# All vendor_id's are the vendor_group_id from the vendors table.
#
# Paths:
#
# /categories/category_name/page
# /vendors/vendor_name/page
# /vendors/vendor_name/category_name/page
# /brands/brand_name/page
# /brands/brand_name/category_name/page

	essential_header();

	$istr=($my_site_info['alias']=='toolresource.com');

	unset($pathlinks);

	if ($_SERVER['SCRIPT_NAME']!='/search.php') {
		path_to_req($_SERVER['PHP_SELF']);
		if ($short_path_include) {
			include_once($short_path_include);
			exit;
		}
	}

	get_request_var_int('items_per_page');
	get_request_var_int('start');
	get_request_var_int('limit');
	get_request_var_int('page_limit');
	get_request_var_int('page');

	if (!$items_per_page) $items_per_page=20;
	if (!$start) $start=0;
	if (!$limit) $limit=200;
	if (!$page_limit) $page_limit=10;

	if (!$page) $page=0;
	if ($page) $start=$page*$items_per_page;
	if (!$page && $start) $page=$start/$items_per_page;

	# These are vendor_id, brand_id and category_id in the req vars, but I'm going
	# to call them s_category_id, s_brand_id and s_vendor_id internally since
	# vendor_id, brand_id and category_id are used otherwise.
	
	get_request_var_int('category_id');
	if (isset($category_id)) $s_category_id=$category_id;
	get_request_var_int('vendor_id');
	if (isset($vendor_id)) $s_vendor_id=$vendor_id;
	get_request_var_int('brand_id');
	if (isset($brand_id)) $s_brand_id=$brand_id;

	# This is useful for searching within a set of search results, which I
	# won't implement yet.  The problem with implementing such is that we
	# throw away everything past the first 200 rows, meaning it would
	# probably be most useful to grab the old search text out of the
	# searches table and simply append the new text to it.
	#get_request_var_int('s_search_id');

	get_request_var_int('search_id');

	get_request_var_int('start_seq');
	get_request_var_int('end_seq');

	$searchtext=trim($_REQUEST['searchtext']);
	if (strstr($searchtext,'Enter Part # or Description')!==false) {
		$searchtext=preg_replace('/\s*Enter Part # or Description\s*/','',$searchtext,-1);
	}
	if (strlen($searchtext)>200) $searchtext=substr($searchtext,0,200);
	$searchtype=$_REQUEST['searchtype'];
	$subsearchtype=$_REQUEST['subsearchtype'];

	$check_perms = sprintf('(not rhed or %s) and (not bcs or %s) and
	               				(not dealer or %s)',
						($auth->has_perm('gatnky')?'true':'false'),
						($auth->has_perm('bcs')?'true':'false'),
						($auth->has_perm('dealer')?'true':'false'));

	$isadmin = $auth->has_perm('admin');
	unset($contact_id);
	if ($auth->logged_in()) {
		$contact_id=$auth->userinfo['contact_id'];
	}

	# make sure this only exists if there is an exact match on a part
	# number

	unset($exact_match);

	$contact_id=0;
	$entity_id=0;
	if ($auth->logged_in()) {
		$contact_id=$auth->userinfo['contact_id'];
		$entity_id=$auth->userinfo['entity_id'];
	}

	$prodtypes=array('U'=>'Units','P'=>'Parts','A'=>'Accessories');

	$searchtypes=array('full'=>'products', 'desc'=>'product description',
							'part'=>'part number', 'vendor'=>'vendor name',
							'category'=>'product category',
							 'vendcat'=>'vendor and category',
							 'brand'=>'brand name', 'brandcat'=>'brand and category');
	$subsearchtypes=array('vendor'=>'vendor name',
							'category'=>'product category',
							 'vendcat'=>'vendor and category',
							 'brand'=>'brand name',
							 'brandcat'=>'brand and category');

	if ($s_category_id && !$category_name) {
		$db->query(sprintf("
				select category_name from categories
					where category_id=%d and %s
			", $s_category_id, $check_perms));
		if ($db->next_record()) {
			extract($db->Record, EXTR_OVERWRITE);
		}
	}

	if ($s_brand_id && !$brand_name) {
		$db->query(sprintf("
				select brand_name from brands where id=%d
			", $s_brand_id));
		if ($db->next_record()) {
			extract($db->Record, EXTR_OVERWRITE);
		}
	}

	if ($s_vendor_id && !$vendor_name) {
		$db->query(sprintf("
				select vendor_name from vendors where vendor_id=%d
			", $s_vendor_id));
		if ($db->next_record()) {
			extract($db->Record, EXTR_OVERWRITE);
		}
	}

	# If the search type is unknown, just show the form
	if (!$search_id && (!$searchtypes[$searchtype] ||
			($subsearchtype && !$subsearchtypes[$subsearchtype]))) {
		page_header();
		print "<!-- Invalid search type -->\n";
		show_search();
		page_footer();
		exit;
	}

	# Nothing to search for, show the form
	if ((!$searchtext || $searchtext=='Enter Part # or Description') &&
				!$search_id && !$s_brand_id && !$s_vendor_id && !$s_category_id) {
		page_header();
		print "<!-- Nothing to search for -->\n";
		show_search();
		page_footer();
		exit;
	}

	# Check to see if the search exists, otherwise we'll search again
	$new_search=true;
	if ($search_id) {
		$db->query(sprintf("
			select first_item, total_rows, overflow, searchtext, searchtype,
					subsearchtype, vendor_group_id as s_vendor_id,
					brand_id as s_brand_id, category_id as s_category_id
				from searches
				where search_id=%d and
					(sid='%s' or %s or contact_id=%d or entity_id=%d)
				", $search_id, pg_escape_string(session_id()),
					$isadmin?'true':'false', $contact_id?$contact_id:-1,
					$entity_id?$entity_id:-1));
		if ($db->next_record()) {
			extract($db->Record, EXTR_OVERWRITE);
			$db->query(sprintf("
					select search_id from search_results where sequence=%d
				", $first_item));
			if ($db->next_record() && $db->f('search_id')==$search_id) {
				$new_search=false;
			}
		} else {
			unset($search_id);
		}
	}
	
	if ($new_search && ($subsearchtype || $searchtype=='vendor' ||
			$searchtype=='category' || $searchtype=='vendcat' ||
			$searchtype=='brand' || $searchtype=='brandcat')) {

		$products=array();
		$epns=array();

		if ($subsearchtype) {
			$type=$subsearchtype;
		} else {
			$type=$searchtype;
		}

		unset($query);
		if ($type=='vendor' && $s_vendor_id) {
			# We don't check the vendor id in the table because we're
			# really using the vendor_group_id.  At some point, we might
			# actually split out vendor_id and vendor_group_id, but
			# assume that for now when we see vendor id, it's really a
			# group id.
			$table='items_in_vendor';
			$query=sprintf("
					select start_seq, end_seq from iiv_lookup
						where vendor_group_id=%d
				", $s_vendor_id);

		} elseif ($type=='category' && $s_category_id) {
			$table='items_in_category';
			$query=sprintf("
					select start_seq, end_seq, category_name
						from iic_lookup l, categories c
						where l.category_id=%d and
							c.category_id=l.category_id and %s
				", $s_category_id, $check_perms);

		} elseif ($type=='vendcat' && $s_vendor_id && $s_category_id) {
			$table='items_in_vendcat';
			$query=sprintf("
					select start_seq, end_seq, category_name
						from iivc_lookup l, categories c
						where l.category_id=%d and l.vendor_group_id=%d and
							c.category_id=l.category_id and %s
				", $s_category_id, $s_vendor_id, $check_perms);

		} elseif ($type=='brand' && $s_brand_id) {
			$table='items_in_brand';
			$query=sprintf("
					select start_seq, end_seq from iib_lookup
						where brand_id=%d
				", $s_brand_id);

		} elseif ($type=='brandcat' && $s_brand_id && $s_category_id) {
			$table='items_in_brandcat';
			$query=sprintf("
					select start_seq, end_seq, category_name
						from iibc_lookup l, categories c
						where l.category_id=%d and l.brand_id=%d and
							c.category_id=l.category_id and %s
				", $s_category_id, $s_brand_id, $check_perms);

		} else {
			page_header();
			show_search();
			page_footer();
			exit;
		}

		$db->query($query);
		if ($db->next_record()) {
			extract($db->Record, EXTR_OVERWRITE);
		} else {
			if ($isadmin) {
				page_header();
				print "<pre>\n${query}\n</pre>\n";
			}
			die_msg("<h1>Fatal Error</h1><p>Item not found during search.</p>");
		}

		if ($subsearchtype) {
			$subtable=", ${table} t";
			$subwc=sprintf(' and p.eclipse_part_number=t.eclipse_part_number and t.sequence between %d and %d ',
									$start_seq, $end_seq);
			# I have subtable and subwc to pass on to the next section.

		} else {

			# $table is set above
			$first_item=$start_seq;
			$total_rows=$end_seq-$start_seq+1;

			#if (!$start_seq || !$end_seq) {
			#	# this is to make the query fail
			#	$page_start=-1; $page_end=-1;
			#} else {
			#	$page_start=($page*$items_per_page)+$start_seq;
			#	$page_end=$page_start+$items_per_page-1;
			#	if ($page_start>$end_seq) {
			#		# went too far
			#		die_msg("<h1>End Of Item</h1><p>You've moved past
			#		the last page.</p>");
			#	} elseif ($page_end>$end_seq) {
			#		$page_end=$end_seq;
			#	}
			#}
			#
			#$rowcount=$end_seq-$start_seq+1;
		}
	}

	if ($new_search && $searchtext &&
			($searchtype=='desc' || $searchtype=='part' || $searchtype=='full')) {

		if ($search_id) {
			$new_search_id=false;
		} else {
			$new_search_id=true;
			$db->query("select nextval('searches_search_id_seq') as search_id");
			if ($db->next_record()) {
				$search_id=$db->f('search_id');
			} else {
				#ACK!
				die_msg("<h1>Fatal Error</h1>\n<p>An unexpected error has
				arisn, and we cannot process your search at this
				time.</p>\n");
			}
		}

		unset($search_query);

		if ($searchtype=='desc') {

			$search_query=sprintf("
				insert into search_results 
						(search_id, mta_part_number, eclipse_part_number)
				select %d as search_id, mta_part_number,
						p.eclipse_part_number
					from products p %s
					where description like '%%%s%%' and
							goto_part_number='' and %s %s
					order by prodtype desc, description, mta_part_number
					limit %d
				", $search_id, $subtable, strtoupper(pg_escape_string($searchtext)),
				$check_perms, $subwc, $limit+1);

		} elseif ($searchtype=='part') {

			$searchtext=strtoupper(trim($searchtext));
			$searchtext2=preg_replace('/-/',' ',$searchtext);
			if ($searchtext!=$searchtext2) {
				$wc=sprintf("(mta_part_number like '%s%%' or
									mta_part_number like '%s%%')",
						pg_escape_string($searchtext), pg_escape_string($searchtext2));
			} else {
				$wc=sprintf("mta_part_number like '%s%%'",
						pg_escape_string($searchtext));
			}
			$search_query=sprintf("
				insert into search_results
						(search_id, mta_part_number, eclipse_part_number)
				select %d as search_id, mta_part_number,
						p.eclipse_part_number
					from products p %s
					where %s and %s %s
					order by prodtype desc, description, mta_part_number
					limit %d
				", $search_id, $subtable, $wc, $check_perms, $subwc, $limit+1);

		} elseif ($searchtype=='full') {

			# The raw query
			# select mta_part_number, (case when tier1 @@ 'OIL&DRAIN'
			# then 1000 else 0 end) + (case when tier2 @@ 'OIL&DRAIN' then 100
			# else 0 end) as ranking
			# from search_rankings
			# where tier1 @@ 'OIL&DRAIN' or tier2 @@ 'OIL&DRAIN'
			# order by ranking, mta_part_number
			# limit 201;


			$searchtext=strtolower($searchtext);

			$s='';
			$wordcount=0;
			$words=preg_split('/\s+/',$searchtext);
			for ($i=0 ; $i<count($words) ; $i++) {
				$word=$words[$i];
				if ($s) {
					$last=($i==count($words)-1);
					if (!$last && $word=='or') {
						$s.='|';
						$i++;
						$word=$words[$i];
					} elseif (!$last && $word=='and') {
						$s.='&';
						$i++;
						$word=$words[$i];
					} else {
						$s.='&';
					}
				}
				$s.=pg_escape_string(strtolower($word));
				$wordcount++;
				if ($wordcount>4) break;
			}

			if ($wordcount==1) {
				$mpn_lookup=sprintf(" or sr.mta_part_number like '%s%%' ",
											pg_escape_string(strtoupper($searchtext)));
			} else {
				$mpn_lookup='';
			}

			$search_query=sprintf("
				insert into search_results
						(search_id, rank, mta_part_number, eclipse_part_number)
				select %d as search_id,
						( (case when tier1 @@ '%s' then 1000 else 0 end) +
							(case when tier2 @@ '%s' then 100 else 0 end))
									as rank,
						p.mta_part_number, p.eclipse_part_number
					from products p, search_rankings sr %s
					where p.mta_part_number=sr.mta_part_number and 
						(tier1@@'%s' or tier2@@'%s' %s) and %s %s
					order by rank, description, mta_part_number
					limit %d
				", $search_id, $s, $s, $subtable, $s, $s, $mpn_lookup,
				$check_perms, $subwc, $limit+1);

		}

		if ($search_query) {

			$start_time=microtime();

			$db->query('begin');

			$db->query('lock table search_results in exclusive mode');

			$db->query($search_query);
			$total_rows=$db->affected_rows();

			$db->query('commit');

			$end_time=microtime();
			$query_time=microtime_diff($start_time,$end_time);

		} else {
			$total_rows=0;
		}

		if ($total_rows) {

			$db->query("select currval('search_results_sequence_seq') as sort_order");
			if ($db->next_record()) {
				$last_item=$db->f('sort_order');
				$first_item=$last_item-$total_rows+1;
			} else {
				#ACK!
				page_header();
				print "<h1>Fatal Error</h1>\n<p>Due to a fatal
				error within our search application, your search cannot
				be completed.</p>\n";
				page_footer();
				exit;
			}

			if ($total_rows>$limit) {
				$total_rows=$limit;
				$overflow='t';
			} else {
				$overflow='f';
			}

		} else {
			$first_item=0;
			$total_rows=0;
			$overflow='f';
		}

		$search_query=preg_replace('/\t/m','  ',$search_query,-1);

		if ($new_search_id) {
			$db->query(sprintf("
				insert into searches
					(search_id, entity_id, contact_id, sid, searchtype, searchtext,
							subsearchtype, vendor_group_id, brand_id, category_id,
							search_time, first_item, total_rows, overflow,
							query_text, query_time)
					values
					(%d, %d, %d, '%s', '%s', '%s', '%s', %d, %d, %d, now(), %d, %d,
					'%s', '%s', %f)",
				$search_id, $entity_id, $contact_id, session_id(),
				pg_escape_string($searchtype), pg_escape_string($searchtext),
				pg_escape_string($subsearchtype), $s_vendor_id, $s_brand_id, $s_category_id,
				$first_item, $total_rows, $overflow, pg_escape_string($search_query),
				$query_time));
		} else {
			# There's already a record in "searches", so we'll just update it
			$db->query(sprintf("
                  update searches set first_item=%d, total_rows=%d,
								overflow='%s', query_text='%s', query_time=%f
							where search_id=%d
					", $first_item, $total_rows, $overflow, 
					pg_escape_string($search_query), $query_time, $search_id));
		}

		if ($total_rows) {
			header('Status: 302 Moved Temporarily');
			header(sprintf('Location: search.php?page=%d&search_id=%d&searchtext=%s&searchtype=%s',$page,$search_id,urlencode($searchtext),urlencode($searchtype)));
			exit;
		} else {
			page_header();
			show_static('dead search');
			show_search();
			page_footer();
			exit;
		}
	}

	if ($search_id) {

		# We grabbed the relevant record from searches back up around line 80,
		# so here we need to 

		$products=array();
		$epns=array();

		# Check for an exact match
		if ($page==0 && $total_rows>1 &&
					($searchtype=='part' ||
					($searchtype=='full' && !preg_match('/ /',$searchtext)))) {
			$searchtext=strtoupper($searchtext);
			$searchtext2=preg_replace('/-/',' ',$searchtext);
			$db->query(sprintf("
					select distinct eclipse_part_number, mta_part_number,
						description, unit_of_measure, uom_quantity,
						price_line, buy_line, weight, vendor_id, status,
						discontinued, goto_part_number, prodtype
					from products
					where mta_part_number in ('%s','%s') and %s
					", pg_escape_string($searchtext), pg_escape_string($searchtext2),
						$check_perms));
			if ($db->num_rows()) {
				# grab the exact match
				while ($db->next_record()) {
					$exact_match=$db->Record;
					$exact_match['prodtype']='Exact Match';
					$products[]=$exact_match;
					$epns[]=$exact_match['eclipse_part_number'];
				}
			}
		}

		#$rowcount=$total_rows;

		$table='search_results';
	}

	if ($table && $first_item && $total_rows) {

		if (!$first_item) {
			# this is to make the query fail
			$page_start=-1; $page_end=-1;
		} else {
			$page_start=($page*$items_per_page)+$first_item;
			$page_end=$page_start+$items_per_page-1;
			if ($page_end>=$first_item+$total_rows) {
				$page_end=$first_item+$total_rows-1;
			}
			if ($page_start>$page_end) {
				die_msg("<h1>Fatal Error</h1><p>Attempt to move past the
				last page.</p>");
			}
		}

		$db->query(sprintf("
					select distinct sequence, p.eclipse_part_number,
						p.mta_part_number, description, unit_of_measure,
						uom_quantity, price_line, buy_line, weight, p.status,
						vendor_id, discontinued, goto_part_number %s
				from products p, %s t
				where p.eclipse_part_number=t.eclipse_part_number and 
					t.sequence between %d and %d
				order by t.sequence
			",$searchtype=='full'?'':', prodtype',
			$table, $page_start, $page_end));

		while ($db->next_record()) {
			$rec=$db->Record;
			if ($searchtype=='full') {
				if ($exact_match) {
					$rec['prodtype']='Other Matching Items';
				} else {
					$rec['prodtype']='Matching Items';
				}
			} else {
				$rec['prodtype']=$prodtypes[$rec['prodtype']];
			}
			$products[]=$rec;
			$epns[]=$db->f('eclipse_part_number');
		}
	}
	$decorations='left_menu';
	$page_title = iso_htmlentities($vendor_name . $brand_name);
	page_header();


	if ($searchtype=='vendcat') {
		printf('
		<h2>Browse Vendor by Category</h2>
		<h3>%s - %s</h3>
		', iso_htmlentities($vendor_name), iso_htmlentities($category_name));

	} elseif ($searchtype=='vendor') {
		printf('
		<h2>Browse Vendor %s</h2>
		', iso_htmlentities($vendor_name));

	} elseif ($searchtype=='brandcat') {
		printf('
		<h2>Browse Brand by Category</h2>
		<h3>%s - %s</h3>
		', iso_htmlentities($brand_name), iso_htmlentities($category_name));

	} elseif ($searchtype=='brand') {
		printf('
		<h2>Browse Brand %s</h2>
		', iso_htmlentities($brand_name));

	} elseif ($searchtype=='category') {
		printf('
		<h2>Browse Category "%s"</h2>
		', iso_htmlentities($category_name));
	} else {
		unset($ss);
		if ($subsearchtype) {
			if ($subsearchtype=='vendcat') {
				$ss=sprintf('%s - %s',
					iso_htmlentities($vendor_name), iso_htmlentities($category_name));
			} elseif ($subsearchtype=='vendor') {
				$ss=iso_htmlentities($vendor_name);
			} elseif ($subsearchtype=='brandcat') {
				$ss=sprintf('%s - %s',
					iso_htmlentities($brand_name), iso_htmlentities($category_name));
			} elseif ($subsearchtype=='brand') {
				$ss=iso_htmlentities($brand_name);
			} elseif ($subsearchtype=='category') {
				$ss=iso_htmlentities($category_name);
			}
		}
		printf('
		<h2>Search Results</h2>
		<h3>Search %s for "%s"%s</h3>
		', iso_htmlentities($searchtypes[$searchtype]),
		iso_htmlentities($searchtext), $ss?" in ${ss}":'');
	}

	if ($searchtype=='brandcat' || $searchtype=='brand' ||
				$searchtype=='category') {

		if ($s_brand_id && $s_category_id) {
			print "<table><tr><td>";
		}

		if ($s_brand_id) {
			$db->query(sprintf("
					select category_name, category_id from categories
						where %s and category_id in
							(select category_id from iibc_lookup
									where brand_id=%d)
						order by category_name
				", $check_perms, $s_brand_id));

			$numcats=$db->num_rows();

			if ($numcats==1 && !$s_category_id) {
				$db->next_record();
				printf("<h3>Category: %s</h3>\n",
						iso_htmlentities($db->f('category_name')));

			} elseif ($numcats>1) {
				print '<form method="get" action="/search.php">';
				if ($s_category_id) {
					print "Narrow your view to another category in this
					brand<br />";
				} else {
					print "Narrow your view to a category in this brand<br />";
				}
				print "<select name='category_id'>";
				while ($db->next_record()) {
					printf("<option value='%d'%s>%s</option>\n",
							$db->f('category_id'),
							$db->f('category_id')==$s_category_id?' selected disabled':'',
							iso_htmlentities($db->f('category_name')));
				}
				print "</select>\n";
				print "<input type='submit' name='submit' value='Go' />\n";
				printf("<input type='hidden' name='brand_id' value='%d' />",
							$brand_id);
				printf("<input type='hidden' name='searchtype'
				value='brandcat' />");
				print "</form>\n";
			}
		}

		if ($s_category_id) {
			$db->query(sprintf("
					select distinct brand_name, id as brand_id
						from brands
						where brand_name!='' and id in
							(select brand_id from iibc_lookup
									where category_id=%d)
						order by brand_name
				", $s_category_id));

			if ($db->num_rows()==1 && !$s_brand_id) {
				$db->next_record();
				printf("<h3>Brand: %s</h3>\n",
						iso_htmlentities($db->f('brand_name')));

			} elseif ($db->num_rows()>1) {
				if ($numcats>1 && $s_brand_id && $s_category_id) {
					print "</td><td style='vertical-align:middle;'>--OR--</td><td>";
				}
				print '<form method="get" action="/search.php">';
				if ($s_brand_id) {
					print "Narrow your view to another brand in this
					category<br />";
				} else {
					print "Narrow your view to a brand in this category<br />";
				}
				print "<select name='brand_id'>";
				while ($db->next_record()) {
					printf("<option value='%d'%s>%s</option>\n",
							$db->f('brand_id'),
							$db->f('brand_id')==$s_brand_id?' selected disabled':'',
							iso_htmlentities($db->f('brand_name')));
				}
				print "</select>\n";
				print "<input type='submit' name='submit' value='Go' />\n";
				printf("<input type='hidden' name='category_id' value='%d' />",
							$category_id);
				printf("<input type='hidden' name='searchtype'
				value='brandcat' />");
				print "</form>\n";
			}
		}

		if ($s_brand_id && $s_category_id) {
			print "</td></tr></table>\n";
		}

	}

	if ($searchtype=='vendcat' || $searchtype=='vendor') {

		if ($s_vendor_id && $s_category_id) {
			print "<table><tr><td>";
		}

		if ($s_vendor_id) {
			$db->query(sprintf("
					select category_name, category_id from categories
						where %s and category_id in
							(select category_id from iivc_lookup
									where vendor_group_id=%d)
						order by category_name
				", $check_perms, $s_vendor_id));

			$numcats=$db->num_rows();

			if ($numcats==1 && !$s_category_id) {
				$db->next_record();
				printf("<h3>Category: %s</h3>\n",
						iso_htmlentities($db->f('category_name')));

			} elseif ($numcats>1) {
				print '<form method="get" action="/search.php">';
				if ($s_category_id) {
					print "Narrow your view to another category in this
					vendor<br />";
				} else {
					print "Narrow your view to a category in this vendor<br />";
				}
				print "<select name='category_id'>";
				while ($db->next_record()) {
					printf("<option value='%d'%s>%s</option>\n",
							$db->f('category_id'),
							$db->f('category_id')==$s_category_id?' disabled':'',
							iso_htmlentities($db->f('category_name')));
				}
				print "</select>\n";
				print "<input type='submit' name='submit' value='Go' />\n";
				printf("<input type='hidden' name='vendor_id' value='%d' />",
							$vendor_id);
				printf("<input type='hidden' name='searchtype'
				value='vendcat' />");
				print "</form>\n";
			}
		}

		if ($s_category_id) {
			$db->query(sprintf("
					select distinct vendor_name, vendor_group_id from vendors
						where vendor_name!='' and vendor_id in
							(select vendor_group_id from iivc_lookup
									where category_id=%d)
						order by vendor_name
				", $s_category_id));

			if ($db->num_rows()==1 && !$s_vendor_id) {
				$db->next_record();
				printf("<h3>Vendor: %s</h3>\n",
						iso_htmlentities($db->f('vendor_name')));

			} elseif ($db->num_rows()>1) {
				if ($numcats>1 && $s_vendor_id && $s_category_id) {
					print "</td><td style='vertical-align:middle;'>--OR--</td><td>";
				}
				print '<form method="get" action="/search.php">';
				if ($s_vendor_id) {
					print "Narrow your view to another vendor in this
					category<br />";
				} else {
					print "Narrow your view to a vendor in this category<br />";
				}
				print "<select name='vendor_id'>";
				while ($db->next_record()) {
					printf("<option value='%d'%s>%s</option>\n",
							$db->f('vendor_group_id'),
							$db->f('vendor_group_id')==$s_vendor_id?' disabled':'',
							iso_htmlentities($db->f('vendor_name')));
				}
				print "</select>\n";
				print "<input type='submit' name='submit' value='Go' />\n";
				printf("<input type='hidden' name='category_id' value='%d' />",
							$category_id);
				printf("<input type='hidden' name='searchtype'
				value='vendcat' />");
				print "</form>\n";
			}
		}

		if ($s_vendor_id && $s_category_id) {
			print "</td></tr></table>\n";
		}

	}

	if ($products) {

		if ($auth->logged_in()) {
			$eclipse_data = get_eclipse_product_data($epns);
			# Used to show cart status
			$cart=array();
			$db->query(sprintf('
					select eclipse_part_number, quantity
						from cart
						where contact_id=%d
						order by 1',
				$auth->userinfo['contact_id']));
			while ($db->next_record()) {
				if ($eclipse_data[$db->f('eclipse_part_number')]) {
					$cart[$db->f('eclipse_part_number')]=$db->f('quantity');
				}
			}
		} else {
			$eclipse_data=array();
			$cart=array();
		}

		$last_prodtype='sdlfj';

		printf('
		<form name="searchres" method="post" action="/cart/dropnrun.php">
		<input type="hidden" name="target" value="%s" />
		<input type="hidden" name="from" value="Search Results" />
		<table class="search-results">
		<thead>
		',iso_htmlentities($_SERVER['REQUEST_URI']));

		$column_count=2;
		if ($auth->logged_in()) $column_count += 2;
		if ($cart) $column_count++;
		if ($eclipse_data['has_availability']) $column_count++;

		foreach ($products as $product) {
			extract($product);
			$num++;
			if ($last_prodtype!=$prodtype) {
				if ($last_prodtype!='') {
				}
				$last_prodtype=$prodtype;
				if ($prodtype) {
					printf('
						<tr><th class="prodtype" colspan="%d">%s</th></tr>
						', $column_count, iso_htmlentities($prodtype));
				}
				print '
					  <tr>
					  ';
				printf('
						 <th>Part #</th>
						 <th>Description</th>
						 ');
				if (!$istr && $auth->logged_in()) {
					if ($eclipse_data['has_availability'])
						print '<th>Status</th>';
					print '<th>Your Price</th>
							 <th>Qty</th>';
					if ($cart) {
						print '<th>In Cart</th>';
					}
				}
				print "</tr>\n";
				print "</thead>\n";
				print "<tbody>\n";
			}
			show_search_row($row, $product,
					isset($eclipse_data[$eclipse_part_number]) ? $eclipse_data[$eclipse_part_number] : array(),
					isset($cart) ? $cart[$eclipse_part_number] : -1);
			$row++;
		}

		print "</tbody>\n";
		print "</table>\n";
		if ($cart) {
			show_static('search items in cart');
		}
		if (!$istr) {
			if ($auth->logged_in()) {
				print "
					<input type='reset' name='reset' value='Reset' />
					<input type='submit' name='submit2' value='Add To Cart' />
					";
			} else {
				print "<p>* Pricing information is available when you log in or register.</p>\n";
			}
		}
      print "</form>";
		$page_total=ceil($total_rows/$items_per_page);

		if ($page_total>1) {

			show_static('Nav to cart');

			print "<p>Search Navigation:\n";
			if ($page>0) {
				// previous link
				make_search_url($page-1,'Previous');
			}

			if ($page>=$page_limit*.7) {
				$start_page=max(min($page-($page_limit/2),$page_total-$page_limit),0);
			} else {
				$start_page=0;
			}

			if ($start_page>0) {
				make_search_url(0,'1');
				if ($start_page>2) {
					make_search_url(max($page-10,0),'...');
				} elseif ($start_page==2) {
					make_search_url(1,'2');
				}
			}

			// pages
			for ($num=$start_page; $num<$start_page+$page_limit && $num<$page_total; $num++) {
				if ($num==$page) {
					printf("<b>%d</b>\n",$num+1);
				} else {
					make_search_url($num,$num+1);
				}
			}

			if ($num<$page_total) {
				if ($num<$page_total-2) {
					make_search_url(min($page+10,$page_total-1),'...');
				} elseif ($num==$page_total-2) {
					make_search_url($page_total-2,$page_total-1);
				}
				make_search_url($page_total-1,$page_total);
			}

			if ($page<$page_total-1) {
				// next link
				make_search_url($page+1,'Next');
			}

			if ($overflow=='t') {
				show_static('search too broad');
			}
			print "</p>\n";
		}
	}

	page_header();

//	show_search();

	page_footer();

	function show_search() {
		global $auth,$db,$searchtype,$subsearchtype,$searchtext;
		global $s_vendor_id,$s_category_id,$category_name,$vendor_name;
		global $s_brand_id, $brand_name;
		printf('
			<br />
			<table border="1"><tr><td align="center">
			<form action="/search.php" method="get">
			');

		if ($searchtype=='brandcat' || $searchtype=='brand' ||
					$searchtype=='category' || $subsearchtype) {
			if ($subsearchtype) $type=$subsearchtype; else $type=$searchtype;
			if ($type=='brandcat') {
				$ss=sprintf('%s - %s',
					iso_htmlentities($brand_name), iso_htmlentities($category_name));
				printf('
					<nobr><input type="radio" name="subsearchtype" value="brandcat"
						checked />
						Search in %s - %s</nobr><br />
					<nobr><input type="radio" name="subsearchtype"
					value="brand" />
						Search in %s</nobr>
					<nobr><input type="radio" name="subsearchtype" value="" />
						Search all products</nobr><br />
					', iso_htmlentities($brand_name), iso_htmlentities($category_name),
					iso_htmlentities($brand_name));
			} elseif ($type=='brand') {
				$ss=iso_htmlentities($brand_name);
				printf('
					<input type="radio" name="subsearchtype" value="%s"
					checked />
						Search in %s
					<input type="radio" name="subsearchtype" value="" />
						Search all products<br />
					', iso_htmlentities($type), $ss);
			} elseif ($type=='category') {
				$ss=iso_htmlentities($category_name);
				printf('
					<input type="radio" name="subsearchtype" value="%s"
					checked />
						Search in %s
					<input type="radio" name="subsearchtype" value="" />
						Search all products<br />
					', iso_htmlentities($type), $ss);
			}
			printf('
				<input type="hidden" name="brand_id" value="%s" />
				<input type="hidden" name="category_id" value="%s" />
			',$s_brand_id?sprintf('%d',$s_brand_id):'',
			$s_category_id?sprintf('%d',$s_category_id):'');
		}

		if ($searchtype=='vendcat' || $searchtype=='vendor') {
			if ($subsearchtype) $type=$subsearchtype; else $type=$searchtype;
			if ($type=='vendcat') {
				$ss=sprintf('%s - %s',
					iso_htmlentities($vendor_name), iso_htmlentities($category_name));
				printf('
					<nobr><input type="radio" name="subsearchtype" value="vendcat"
						checked />
						Search in %s - %s</nobr><br />
					<nobr><input type="radio" name="subsearchtype"
					value="vendor" />
						Search in %s</nobr>
					<nobr><input type="radio" name="subsearchtype" value="" />
						Search all products</nobr><br />
					', iso_htmlentities($vendor_name), iso_htmlentities($category_name),
					iso_htmlentities($vendor_name));
			} elseif ($type=='vendor') {
				$ss=iso_htmlentities($vendor_name);
				printf('
					<input type="radio" name="subsearchtype" value="%s"
					checked />
						Search in %s
					<input type="radio" name="subsearchtype" value="" />
						Search all products<br />
					', iso_htmlentities($type), $ss);
			} elseif ($type=='category') {
				$ss=iso_htmlentities($category_name);
				printf('
					<input type="radio" name="subsearchtype" value="%s"
					checked />
						Search in %s
					<input type="radio" name="subsearchtype" value="" />
						Search all products<br />
					', iso_htmlentities($type), $ss);
			}
			printf('
				<input type="hidden" name="vendor_id" value="%s" />
				<input type="hidden" name="category_id" value="%s" />
			',$s_vendor_id?sprintf('%d',$s_vendor_id):'',
			$s_category_id?sprintf('%d',$s_category_id):'');
		}

		printf('
			Type in a product description:
			<input type="text" name="searchtext" value="%s" size="20"
					maxlength="100" /><br />
			Search Type
			', iso_htmlentities($searchtext));

			make_selection('searchtype',$searchtype,
					array('full'=>'General','desc'=>'Description',
					'part'=>'Part Number'),1,0);

		if ($auth->has_perm('admin') && !$subsearchtype &&
				$searchtype!='vendcat' && $searchtype!='vendor' &&
				$searchtype!='category' && $searchtype!='brand' &&
				$searchtype!='brandcat') {
			# allow an admin to add subsearch criteria
			printf('
				<br />
				Advanced Criteria (for admins)<br />
				Vendor ID
				<input type="text" name="vendor_id" value="%s" size="6"
						maxlength="6" />
				Brand ID
				<input type="text" name="brand_id" value="%s" size="6"
						maxlength="6" />
				Category ID
				<input type="text" name="category_id" value="%s" size="6"
						maxlength="6" /><br />
			',$s_vendor_id?sprintf('%d',$s_vendor_id):'',
			$s_brand_id?sprintf('%d',$s_brand_id):'',
			$s_category_id?sprintf('%d',$s_category_id):'');
			make_selection('subsearchtype',$subsearchtype,
					array('brandcat'=>'Brand & Category', 'brand'=>'Brand Only',
					'vendcat'=>'Vendor & Category','vendor'=>'Vendor Only',
							'category'=>'Category Only'),1,1);
		}

		printf('
			<input type="submit" name="submit" value="Search" />
			</form>
			</td></tr></table>
		');
	}

	function make_search_url($page, $label) {
		global $searchtype, $searchtext, $category_name, $vendor_name, $brand_name;
		global $search_id, $s_category_id, $s_vendor_id, $s_brand_id;
		global $pathlinks;
		global $auth;
		if ($searchtype=='vendcat' || $searchtype=='vendor' ||
					$searchtype=='brandcat' || $searchtype=='brand' ||
					$searchtype=='category') {
			if ($pathlinks) {
				$path=array();
				if ($searchtype=='vendor') {
					$path[]='vendors';
					$path[]=$vendor_name;
				} elseif ($searchtype=='category') {
					$path[]='categories';
					$path[]=$category_name;
				} elseif ($searchtype=='vendcat') {
					$path[]='vendors';
					$path[]=$vendor_name;
					$path[]=$category_name;
				} elseif ($searchtype=='brand') {
					$path[]='brands';
					$path[]=$brand_name;
				} elseif ($searchtype=='brandcat') {
					$path[]='brands';
					$path[]=$brand_name;
					if ($category_name!='Parts') {
					$path[]=$category_name;
				   }	
				}
				$path[]="$page";
				$url=make_path($path);
			} else {
				$url=MTA_URL('/search.php',array('searchtype'=>$searchtype,
					'category_id'=>$s_category_id,'vendor_id'=>$s_vendor_id,
					'brand_id'=>$s_brand_id,'page'=>$page));
			}
		} elseif ($searchtype=='desc' || $searchtype=='part' ||
					$searchtype=='full') {
			$url=MTA_URL('/search.php',array('searchtype'=>$searchtype,
					'searchtext'=>$searchtext,'page'=>$page,
					'search_id'=>$search_id));
		}
#		if (!$auth->logged_in()) {
			printf("<a href='%s'>%s</a>\n", $url, iso_htmlentities($label));
#		} else {
#			printf("<a href=\"javascript:document.searchres.target.value='%s';document.searchres.submit();\">%s</a>\n",
#				$url, iso_htmlentities($label));
#		}
	}

	function path_to_req($path) {
		global $db;
		$path_parts=unmake_path($path);
		if ($path_parts[0]=='vendors') {
			$vendor_name=$path_parts[1];
			if (!$vendor_name) {
				$GLOBALS['short_path_include']='vendors.php';
				return;
			}
			# third piece is either nothing (page 0), a category
			# (non-numeric), or a page (numeric)
			if ($path_parts[2]) {
				if (is_numeric($path_parts[2])) {
					$page=$path_parts[2];
					$searchtype='vendor';
				} else {
					$category_name=$path_parts[2];
					if ($path_parts[3] && is_numeric($path_parts[3])) {
						$page=$path_parts[3];
					} else {
						$page=0;
					}
					$searchtype='vendcat';
				}
			} else {
				$page=0;
				$searchtype='vendor';
			}
		} elseif ($path_parts[0]=='brands') {
			$brand_name=$path_parts[1];
			if (!$brand_name) {
				$GLOBALS['short_path_include']='brands.php';
				return;
			}
			# third piece is either nothing (page 0), a category
			# (non-numeric), or a page (numeric)
			if ($path_parts[2]) {
				if (is_numeric($path_parts[2])) {
					$page=$path_parts[2];
					$searchtype='brand';
				} else {
					$category_name=$path_parts[2];
					if ($path_parts[3] && is_numeric($path_parts[3])) {
						$page=$path_parts[3];
					} else {
						$page=0;
					}
					$searchtype='brandcat';
				}
			} else {
				$page=0;
				$searchtype='brand';
			}
		} elseif ($path_parts[0]=='categories') {
			$category_name=$path_parts[1];
			if (!$category_name) {
				$GLOBALS['short_path_include']='categories.php';
				return;
			}
			$category_name=$path_parts[1];
			if ($path_parts[2] && is_numeric($path_parts[2])) {
				$page=$path_parts[2];
			} else {
				$page=0;
			}
			$searchtype='category';
		} else {
			# no idea
		}
		if ($searchtype) {
			# prime the $_REQUEST variables
			$_REQUEST['searchtype']=$searchtype;
			$_REQUEST['page']=$page;
			if ($vendor_name) {
				$GLOBALS['vendor_name']=$vendor_name;
				$db->query(sprintf("select vendor_group_id from vendors where vendor_name='%s' limit 1", pg_escape_string($vendor_name)));
				if ($db->next_record()) {
					$vendor_id=$db->f('vendor_group_id');
				}
			}
			if ($brand_name) {
				$GLOBALS['brand_name']=$brand_name;
				$db->query(sprintf("select id from brands where brand_name='%s' limit 1", pg_escape_string($brand_name)));
				if ($db->next_record()) {
					$brand_id=$db->f('id');
				}
			}
			if ($category_name) {
				$GLOBALS['category_name']=$category_name;
				$db->query(sprintf("select category_id from categories where category_name='%s'", pg_escape_string($category_name)));
				if ($db->next_record()) {
					$category_id=$db->f('category_id');
				}
			}
			if ($vendor_id) $_REQUEST['vendor_id']=$vendor_id;
			if ($brand_id) $_REQUEST['brand_id']=$brand_id;
			if ($category_id) $_REQUEST['category_id']=$category_id;
			$GLOBALS['pathlinks']=1;
		}
	}

	function show_search_row($row,$rec,$pricing,$incart) {

		global $auth, $pathlinks, $istr;

		extract($rec, EXTR_OVERWRITE);

		if ($auth->has_perm('cart')) {
			if ($pricing) {
				$unit_price=get_unit_price($pricing, $incart);
			} else {
				print "\n<!-- No pricing for item: $eclipse_part_number -->\n";
				return;
			}
		}

		if ($goto_part_number) {
			$jumpto=$goto_part_number;
		} else {
			$jumpto=$mta_part_number;
		}
		
		if (false && $pathlinks) {
			$path=array();
			$path[]='products';
			$path[]=$jumpto;
			$url=make_path($path);
		} else {
			$url=MTA_URL('/family.php',array('family_id'=>isset($goto_epn) && $goto_epn > 0?$goto_epn:$eclipse_part_number));
		}
		if (!$description) $description='-';

		printf('<tr%s>', $row&1?' class="odd"':'');
		printf('<td><a href="%s">%s</a></td>',
				$url, iso_htmlentities($mta_part_number));
		printf('<td><a href="%s">%s</a>', $url, iso_htmlentities($description));
		if ($goto_part_number) {
			printf("<br />Replaced by <a href='%s'>%s</a>",
				MTA_URL('detail.php',array('mta_part_number'=>$jumpto)),
				iso_htmlentities($goto_part_number));
		}
		print '</td>';

		if (!$istr && $auth->has_perm('cart')) {

			if ($pricing['has_availability']) {
				$title='';
				if ($goto_part_number) {
					print '<td>Replaced</td>';
				} elseif ($pricing['on_hand']>0) {
					printf('<td>In Stock</td>');
				} elseif ($status == 'NONSTOCK') {
					printf('<td>Special Order</td>');
				} else {
					/*Turned off until more history is available in Eclipse
					if ($pricing['earliest_more_date']) {
						$title=sprintf('Available on %s',
							iso_htmlentities($pricing['earliest_more_date']));
					} elseif ($pricing['plenty_date']) {
						$title=sprintf('Available on %s',
							iso_htmlentities($pricing['plenty_date']));
					}
					*/
					printf('<td><span title="%s">Out of Stock</span></td>',
								$title);
				}
				#printf('<td><img src="/images/%s.gif" alt="%s stock" title="%s"
				#					border="0"></td>',
				#			$pricing['on_hand']?'in':'out',
				#			$pricing['on_hand']?'In':'Out of',
				#			$title);
			}

			printf('<td align="right">$%.2f</td>', ceil($unit_price*100)/100);
			if ($goto_part_number) {
				print '<td>&nbsp;</td>';
			} else {
				printf('<td><input type="text" name="qtys[%d]" value=""
				size="3" maxlength="5" /><input type="hidden" name="epns[%d]"
				value="%d" /></td>',
					$row, $row, $eclipse_part_number);
			}
			if ($incart>0) {
				printf('<td align="right">%d</td>', $incart);
			} elseif ($incart==0) {
				print '<td>&nbsp;</td>';
			}
		}

		print "</tr>\n";
	}
?>