#!/usr/bin/perl

MAIN:
{

	$server = $ENV{'SERVER_NAME'};
	$query  = $ENV{'QUERY_STRING'};
	$query0 = $query;
	$query  =~ s/\&stk\=.*//;
	$query0 =~ s/\&price\_range\=.*//g;

	$domain = $server;
	if   ( $domain =~ m/sex\-superstore/i ) { $domain = '.sex-superstore.com' }
	else                                    { $domain = '' }

	#affiliate flag
	if (    !( $server =~ m/pexxx/i )
		and !( $server =~ m/privateentertainment/i )
		and !( $server =~ m/myadultwarehouse/i ) )
	{
		$aff_flag = 1;
	}
	if (   $server =~ /shop\.sex\-superstore\.com/i
		or $server =~ /store\.sex\-superstore\.com/i
		or $server =~ /store\.dev\.sex\-superstore\.com/i
		or $server =~ /shop\.dev\.sex\-superstore\.com/i )
	{
		$aff_super = 1;
	}

	#initial categories
	@asso00 = (
		'hotdeal',  'anal',    'gaggift',  'battery',
		'bondage',  'book',    'cockring', 'condom',
		'dildo',    'egg',     'enhancer', 'extension',
		'couples',  'games',   'grooming', 'headcleaner',
		'herbals',  'jewelry', 'lingerie', 'doll',
		'lube',     'massage', 'vagina',   'pump',
		'strap-on', 'vibrator'
	);

	#init-name  association
	@asso0 = (
		'all',         'New Releases', 'hotdeal',  'Hot Deals!',
		'anal',        'Anal Toys',    'gaggift',  'Bachelorette',
		'battery',     'Batteries',    'bondage',  'Bondage',
		'book',        'Books',        'cockring', 'Cockrings',
		'condom',      'Condoms',      'dildo',    'Dildos/Dongs',
		'egg',         'Eggs/Bullets', 'enhancer', 'Enhancers',
		'extension',   'Extensions',   'couples',  'For Couples',
		'games',       'Games',        'grooming', 'Grooming',
		'headcleaner', 'Head Cleaner', 'herbals',  'Herbals',
		'jewelry',     'Jewelry',      'lingerie', 'Lingerie',
		'doll',        'Love Dolls',   'lube',     'Lubricants',
		'massage',     'Massage',      'vagina',   'Masturbators',
		'pump',        'Penis Pumps',  'strap-on', 'Strap-Ons',
		'vibrator',    'Vibrators'
	);
	%asso0 = @asso0;

	$pth        = 'pthumbs';
	$status     = 'date';
	$order      = 'ASC';
	$order_list = 'ASC';

	#DATE
	local ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
	  localtime(time);
	$year = 1900 + $year;
	local (@month) = (
		'January',   'February', 'March',    'April',
		'May',       'June',     'July',     'August',
		'September', 'October',  'November', 'December'
	);
	local ($mo) = $month[$mon];

	&ReadParse;
	(
		$text,       $type,       $criteria,  $last,       $last_list,
		$first,      $first_list, $fam,       $hotdeal,    $discount,
		$bestseller, $init,       $dozen,     $dozen_list, $letter,
		$init1,      $noresult,   $affiliate, $stk,        $price_range
	  )
	  = (
		$in{'text'},       $in{'type'},       $in{'criteria'},
		$in{'last'},       $in{'last_list'},  $in{'first'},
		$in{'first_list'}, $in{'fam'},        $in{'hotdeal'},
		$in{'discount'},   $in{'bestseller'}, $in{'init'},
		$in{'dozen'},      $in{'dozen_list'}, $in{'letter'},
		$in{'init1'},      $in{'noresult'},   $in{'af'},
		$in{'stk'},        $in{'price_range'}
	  );
	  
	if (length($ecode) > 10) {
		die('Invalid Parameter');
	}	  

	if ( $criteria eq 'ecode' ) {
		$init  = '';
		$init1 = '';
	}

	&fam2init;    #converts some families to inits

	if ( !$type ) { $type = 'toys' }
	if ( $text eq 'hotdeal' or $init eq 'hotdeal' ) { $hotdeal = 'Yes' }
	if ( $criteria eq 'voldiscount' or $init eq 'voldiscount' ) {
		$discount = 'Yes';
		$init     = 'voldiscount';
	}
	if ( $discount eq 'Yes' )  { $criteria = 'voldiscount' }
	if ( $criteria eq 'init' ) { $init     = $text }
	if ( !$init and !$criteria ) { $init = 'all' }
	if ($noresult) { $text = $noresult; $criteria = 'ecode'; }
	if ( $text eq 'all' and $criteria eq 'init' ) {
		$text     = '';
		$criteria = '';
	}

	if ( $stk eq 'Yes' ) {
		$first      = '';
		$last       = '';
		$first_list = '';
		$last_list  = '';
		$dozen      = 1;
		$dozen_list = 1;
	}
	if ($price_range) { $price_app = "&price_range=$price_range" }

	&get_cookie;
	$stock = $cookie{'stock'};
	$stock = substr( $stock, 0, 1 );
	if (
		!$stock
		or (    $stock ne 'N'
			and $stock ne 'T'
			and $stock ne 'A'
			and $stock ne 'P'
			and $stock ne 'O'
			and $stock ne 'F'
			and $stock ne 'D' )
	  )
	{
		$stock = 'N';
	}
	if ( $stock ne 'N' ) { $inv_mod = " and inventory.available='$stock'"; }
	else {
		$inv_mod = " and (inventory.available='T' or inventory.available='P')";
	}
	$res_field = 'results';
	if ( $stock eq 'T' ) { $sel_T = 'selected'; $res_field = 'res_T' }
	if ( $stock eq 'A' ) {
		$sel_A     = 'selected';
		$inv_mod   = '';
		$res_field = 'res_A';
	}
	if ( $stock eq 'P' ) { $sel_P = 'selected'; $res_field = 'res_P' }
	if ( $stock eq 'O' ) { $sel_O = 'selected'; $res_field = 'res_O' }
	if ( $stock eq 'F' ) { $sel_F = 'selected'; $res_field = 'res_F'; }
	if ( $stock eq 'D' ) { $sel_D = 'selected'; $res_field = 'res_D'; }

	if ( !( $affiliate =~ /^\d/ ) ) {
		$affiliate = $cookie{'affiliate'};
	}
	$affiliate =~ s/\D.*//s;
	if ( !( $affiliate =~ /^\d/ ) ) { $affiliate = 0 }

	if ( !$dozen )      { $dozen      = 1 }
	if ( !$dozen_list ) { $dozen_list = 1 }
	$dozen0      = $dozen - 1;
	$dozen1      = $dozen + 1;
	$dozen_list0 = $dozen_list - 1;
	$dozen_list1 = $dozen_list + 1;
	$first_list0 = $first_list;
	$last_list0  = $last_list;

	if ( !$init1 and ( $discount eq 'Yes' ) ) { $init1 = 'all' }

	use CGI;
	$foo   = new CGI;
	$text3 = $foo->escape($text);

###CATEGORY & family SELECT

	$text_type = $type;

	open( FILEHANDLE, "< store.txt" ) or print 'Cannot open file';
	while (<FILEHANDLE>) { chop $_; $code .= $_ }
	close(FILEHANDLE);
	eval($code);
	%assa3 = @asso3;
	%assa1 = @asso1;
	%assa0 = @asso0;

	$fam_number = ( $#asso1 + 1 ) / 2;

	$initial = $assa0{$init};
	if ( !$text ) { $text = $initial }

	$family = $assa1{$fam};

	if ( $criteria eq 'init' ) {
		$text1 =
" &GT; <a href='/cgi-bin/toys.cgi?af=$affiliate&type=$type&text=$text3&criteria=init' class='text1large'>$asso0{$text}</a>";
	}
	if ($fam) {
		$fam1 =
" &GT; <a href='/cgi-bin/toys.cgi?af=$affiliate&init=$init&fam=$fam' class='text1large'>$family</a>";
	}
	if ($init1) {
		$fam1 =
" &GT; <a href='/cgi-bin/toys.cgi?af=$affiliate&init1=$init1&criteria=$criteria&text=$text3' class=text1large'>$asso0{$init1}</a>";
	}

	require("../inc/dbc.dat");

	#show stream
	if ( $criteria ne 'init' ) {
		$text1 =
" &GT; <a href='/cgi-bin/toys.cgi?af=$affiliate&init=$init&text=$text3&criteria=$criteria' class='text1large'>$text</a>";
	}
	if ( $hotdeal eq 'Yes' ) {
		$text1 =
" &GT; <a href='/cgi-bin/toys.cgi?af=$affiliate&init=hotdeal' class='text1large'>Hot Deals!</a>";
		$addition = '&hotdeal=Yes';
	}
	if ( $discount eq 'Yes' ) {
		$text1 =
" &GT; <a href='/cgi-bin/toys.cgi?af=$affiliate&discount=Yes'  class='text1large'>Volume Discounts</a>";
		$addition = '&discount=Yes';
	}
	if ( $bestseller eq 'Yes' ) {
		$text1 =
" &GT; <a href='/cgi-bin/toys.cgi?af=$affiliate&bestseller=Yes' class='text1large'>Bestsellers</a>";
		$addition = '&bestseller=Yes';
		$pth      = 'pimage';
	}
	$type1 =
	  "<a href=/cgi-bin/toys.cgi?af=$affiliate class='text1large'>Sex Toys</a>";

	#types for Cart
	$type3 = $type;
	if ( $type eq 'magazines' ) { $type3 = 'mag' }
	if ( $type eq 'toys' )      { $type3 = 'toy' }

	if ($family)  { $family3  = ": $family" }
	if ($initial) { $initial3 = " $initial" }

	require("/export/home0/vhost218/cgi-serverwide/colors.pl");

	#page layout
	print &PrintHeader;
	print <<EOT;
<html>
<head>
<title>Sex Toys: $initial3$family3</title>
<META HTTP-EQUIV="Expires" CONTENT="0">

<script language="JavaScript">
<!--
function repl(value){
var url='/cgi-bin/toys.cgi?af=$affiliate&fam='+value+'&init=$init'
window.location= url;
}

function replC(value){
var url='/cgi-bin/toys.cgi?af=$affiliate&init1='+value+'&criteria=$criteria&text=$text3'
window.location= url;
}

function replP(value){
  if(value){window.location='http://$ENV{"HTTP_HOST"}/cgi-bin/$type.cgi?$query0&price_range='+value;}
  else{window.location='http://$ENV{"HTTP_HOST"}/cgi-bin/$type.cgi?$query0';}
}

var caution = false
today=new Date();
quarterlater=new Date();
quarterlater.setTime(today.getTime()+7776000000);
yearslater=new Date();
yearslater.setTime(today.getTime()+315360000000);

function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		 "; path=/" +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "")
	if (!caution || (name + "=" + escape(value)).length <= 4000)
		document.cookie = curCookie
	else
		if (confirm("Cookie exceeds 4KB and will be cut!"))
			document.cookie = curCookie
}

function getCookie(name) {
	var prefix = name + "="
	var cookieStartIndex = document.cookie.indexOf(prefix)
	if (cookieStartIndex == -1)
		return null
	var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
	if (cookieEndIndex == -1)
		cookieEndIndex = document.cookie.length
	return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}

function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" + 
		"; path=/" +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT"
	}
}

function fixDate(date) {
	var base = new Date(0)
	var skew = base.getTime()
	if (skew > 0)
		date.setTime(date.getTime() - skew)
}

ecod = new Array;
coll = new Array;
prim = new Array;
stkk = new Array;



function setCart(onsale,number,last_price){
if(stkk[number] == 'D'){alert('Sorry, this option is NOT AVAILABLE. Please try other options.');return;}
var key=prim[number]+'alpha'+ecod[number]
var keyss = getCookie("keysCookie")		
var onsales = getCookie("onsalesCookie")		
if ( keyss ) {keyss = keyss+key+'\$' }
else {keyss = key+'\$' }
if ( onsales ) {onsales = onsales+onsale+'\$' }
else {onsales = onsale+'\$' }

var total = getCookie("total");
var tot_qty = getCookie("tot_qty");
if(eval(total)>0){total = eval(total)+eval(last_price);} else{total = eval(last_price)}
if(eval(tot_qty)){tot_qty = eval(tot_qty)+1} else{tot_qty = 1}

setCookie ("keysCookie",keyss,quarterlater)
setCookie ("onsalesCookie",onsales,quarterlater)
setCookie ("total",total,quarterlater);
setCookie ("tot_qty",tot_qty,quarterlater);
document.location.reload();
}

function set_stock(stock){
setCookie ("stock",stock);
window.location='http://$ENV{"HTTP_HOST"}/cgi-bin/$type.cgi?$query&stk=Yes'+'&';
}

browserName = navigator.appName;
browserVer = parseInt(navigator.appVersion);
if (browserVer >= 3) version = "n3";
else if (browserName == "Netscape" && browserVer <= 2) version = "n2";
else version = "ie"
function MakeHelpLogin(url) {
	if (version == "ie" || version == "n2") { alert('Netscape 3.0 and above or Internet Explorer 4.0 and above are required to use the Help Windows.'); }
	if (version == "n3") {
		HelpWindow=window.open(url,"HelpWindow","toolbar=no,width=300,height=400,scrollbars=auto,directories=no,status=no,menubar=no");
		HelpWindow.focus();
	}
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);
// -->
</script>
$style_sheet
</head>
<body bgcolor="$bgcolor" text="#000000" link="#0000FF" vlink="#0000FF" alink="$hover" topmargin=0 leftmargin=0 marginwidth=0 marginheight=0>
EOT

	require("/export/home0/vhost218/cgi-serverwide/header.pl");

	print <<EOT;
<table border="0" cellspacing="0" cellpadding="0" width=100%>
 <tr>
  <td width="5%" bgcolor="$bgcolor2" valign="top">
EOT

	require("/export/home0/vhost218/cgi-serverwide/menu_new.pl");

	#price range/match
	if ($price_range) {

		#field for price
		if (   ( $aff_flag and !( $server =~ m/shop/ ) )
			or ( $server =~ m/myadultwarehouse/ ) )
		{
			$price_field = 'price';
		}
		else { $price_field = 'saleprice' }

		if ( $price_range !~ /\-/ ) {    #exact match
			$price_match = $price_range;
			if ( $price_match =~ /^\d+$/ or $price_match =~ /^\d+\.\d+$/ ) {
				$price_mod = "$price_field=$price_match";
				$price2    = "\$$price_match";
				$price1 =
" &gt; <a href='/cgi-bin/$type.cgi?price_range=$price_match' class='text1large'>$price2</a>";
			}
		}
		else {                           #range
			( $price_min, $price_max ) = split /-/, $price_range;
			if ( $price_min =~ /^\d+$/ or $price_min =~ /^\d+\.\d+$/ ) {
				$price_mod_min = "$price_field>$price_min";
			}
			if ( $price_max =~ /^\d+$/ or $price_max =~ /^\d+\.\d+$/ ) {
				$price_mod_max = "$price_field<$price_max";
			}
			if ( $price_mod_min and $price_mod_max ) {
				$price_mod = "$price_mod_min and $price_mod_max";
				$price2    = "\$$price_min - \$$price_max";
				$price1 =
" &gt; <a href='/cgi-bin/$type.cgi?price_range=$price_min-$price_max' class='text1large'>$price2</a>";
			}
			elsif ($price_mod_min) {
				$price_mod = $price_mod_min;
				$price2    = "more than \$$price_min";
				$price1 =
" &gt; <a href='/cgi-bin/$type.cgi?price_range=$price_min-' class='text1large'>$price2</a>";
			}
			elsif ($price_mod_max) {
				$price_mod = $price_mod_max;
				$price2    = "less than \$$price_max";
				$price1 =
" &gt; <a href='/cgi-bin/$type.cgi?price_range=-$price_max' class='text1large'>$price2</a>";
			}
		}

	}

	print <<EOT;
  </td>
  <td valign="top">
   <table cellpadding="0" cellspacing="0" width="100%" valign="top" align="center">
    <tr> 
     <td width="75%" valign="top" align="center">
     <form name="InventoryForm" METHOD=get>
      <table cellspacing="6" cellpadding="0" border="0" width="100%" valign="top" align="center">
       <tr> 
        <td colspan=2> 
         <table  cellspacing="0" cellpadding="0" border="0" width="100%">
          <tr>
           <td width="75%" class="text1large">&nbsp;&nbsp;$type1$text1$fam1$price1</td>
           <td width="25%" align="right">
            <select name="inventory"  onChange="set_stock(this.options[this.selectedIndex].value)">
             <option value="N" $sel_N>In Stock Plus</option>
             <option value="T" $sel_T>In Stock Only</option>
             <option value="P" $sel_P>Pre-Order Only</option>
             <option value="O" $sel_O>On Order Only</option>
             <option value="F" $sel_F>Special Order</option>
             <option value="D" $sel_D>Not Available</option>
             <option value="A" $sel_A>All Stock</option>
            </select>
           </td>
          </tr>
	     </table>
	    </td>
       </tr>
EOT

	#product DB retrieve
	$table  = 'date_' . $type;
	$table1 = 'aph_' . $type;

	if ( $init ne 'all' ) {
		$where      = "WHERE initial='$init'";
		$where_list = "WHERE initial='$init'";
	}
	else {
		$where      = "WHERE (bigkey>=0)";
		$where_list = "WHERE (bigkey>=0)";
	}

	if ( $criteria eq 'title' )        { $crt = 'product_name' }
	if ( $criteria eq 'manufacturer' ) { $crt = 'manufacturer' }
	if ( $criteria eq 'star' )         { $crt = 'stars' }
	if ( $criteria eq 'ecode' )        { $crt = 'inventory.item' }
	if ( $criteria eq 'init' )         { $crt = 'initial' }
	if ( $criteria eq 'sku' )          { $crt = 'sku' }
	if   ( $text ne 'all' ) { $textE = "%" . $text . "%"; }
	else                    { $textE = "%" . "%"; }
	$textE = $dbh->quote($textE);

	if ( $criteria or $init1 ) {
		$where      = "WHERE $crt LIKE $textE";
		$where_list = "WHERE $crt LIKE $textE";
		if ($init1) {
			$where      = $where . " and initial='$init1'";
			$where_list = $where_list . " and initial='$init1'";
		}
	}

	if ( $discount eq 'Yes' ) {
		$where      = "WHERE voldiscount='T'";
		$where_list = "WHERE voldiscount='T'";
		if ($init1) {
			$where      = $where . " and initial='$init1'";
			$where_list = $where_list . " and initial='$init1'";
		}
	}

	if ($fam) {
		$where = $where . " and (family1='$fam' or family2='$fam' $where1)";
		$where_list =
		  $where_list . " and (family1='$fam' or family2='$fam' $where1)";
	}

	if ( $hotdeal eq 'Yes' ) {
		$where      = "WHERE hotdeals='T'";
		$where_list = "WHERE hotdeals='T'";
		if ($fam) {
			$where = $where
			  . " and (initial='$fam' or family1='$fam' or family2='$fam')";
			$where_list = $where_list
			  . " and (initial='$fam' or family1='$fam' or family2='$fam')";
		}
	}

	if ($last) { $where = $where . " and bigkey>'$last'" }
	if ($first) { $where = $where . " and bigkey<'$first'"; $order = 'DESC' }

	if ($letter) { $where = $where . " and product_name LIKE '$letter%'" }

	if ($price_mod) {
		if   ($where) { $where = "$where and $price_mod"; }
		else          { $where = "WHERE $price_mod"; }
		if   ($where_list) { $where_list = "$where_list and $price_mod"; }
		else               { $where_list = "WHERE $price_mod"; }
	}

	&getProductData;

	if ( ( $criteria eq 'ecode' ) and !$imax0 ) {
		if ( $ecode_pri = &getEcode($text) ) {
			$where      = "WHERE inventory.item='$ecode_pri'";
			$where_list = "WHERE inventory.item='$ecode_pri'";
			&getProductData;
		}
	}
	else { $ecode_pri = $text }

	if ($first) {
		@ecode        = reverse @ecode;
		@product_name = reverse @product_name;
		@saleprice    = reverse @saleprice;
		@price        = reverse @price;
		@manufacturer = reverse @manufacturer;
		@image        = reverse @image;
		@onsale       = reverse @onsale;
		@bigkey       = reverse @bigkey;
		@synopsis     = reverse @synopsis;
		@stars        = reverse @stars;
		@options      = reverse @options;
		@opts_set     = reverse @opts_set;
		@ecodes_set   = reverse @ecodes_set;
		@stock_this   = reverse @stock_this;
		@opt_set1     = reverse @opt_set1;
	}

	$first = $bigkey[0];
	$last  = $bigkey[$imax];

	#alphabetic list
	$where_list0 = $where_list;
	if ($last_list) { $where_list = $where_list . " and bigkey>'$last_list'" }
	if ($first_list) {
		$where_list = $where_list . " and bigkey<'$first_list'";
		$order_list = 'DESC';
	}
	if ($letter) {
		$where_list  = $where_list . " and product_name LIKE '$letter%'";
		$where_list0 = $where_list0 . " and product_name LIKE '$letter%'";
	}

	$sql2 = $dbh->prepare(
		" SELECT $table1.item,$table1.product_name,$table1.bigkey
     FROM $table1,inventory
     $where_list and $table1.item=inventory.item $inv_mod
     ORDER by $table1.bigkey $order_list 
     LIMIT 50
     "
	);

	$sql2->execute;
	$j = 0;
	while ( @record1 = $sql2->fetchrow_array ) {
		( $list_ecode[$j], $list[$j], $bigkey_list[$j] ) = @record1;
		$j++;
	}
	$sql2->finish;

	#number of search results
	if ( $letter or ( $criteria and ( $criteria ne 'init' ) and $text ) ) {

		#check search DB

		if ( $criteria and ( $criteria ne 'init' ) ) {
			$phrase = $dbh->quote($text);
			$sql0   = $dbh->prepare(
				" SELECT hits,$res_field,inits
     FROM search
     WHERE phrase=$phrase and type='$type' and criteria='$criteria' and site='SuperStore'
     LIMIT 1
     "
			);

			$sql0->execute;
			( $hits, $results, $inits ) = $sql0->fetchrow_array;
			$sql0->finish;

		}

		if ( !$hits or ( $results < 0 ) ) {

			if   ( $criteria ne 'ecode' ) { $add_inv = " $inv_mod"; }
			else                          { $add_inv = '' }

			$sql3 = $dbh->prepare(
				" SELECT COUNT($table1.item)
     FROM $table1,inventory
     $where_list0 and $table1.item=inventory.item $add_inv
     ORDER by $table1.bigkey $order_list 
     "
			);

			$sql3->execute;
			$jj = 0;
			($jj) = $sql3->fetchrow_array;
			$sql3->finish;

			if ( !$hits and $criteria and ( $criteria ne 'init' ) ) {

				if ( $jj > 0 ) {
					$sql4 = $dbh->prepare(
						" SELECT DISTINCT $table1.initial
                FROM $table1,inventory
                $where_list0 and $table1.item=inventory.item $inv_mod
                "
					);

					$sql4->execute;
					while ( ($init_dd) = $sql4->fetchrow_array ) {
						push( @init_ddd, $init_dd );
					}
					$sql4->finish;
					$inits = join( ',', @init_ddd );
				}

				$dbh->do(
"INSERT search (phrase,type,criteria,hits,$res_field,inits,site)
                     VALUES ($phrase,'$type','$criteria',1,$jj,'$inits','SuperStore')            
             "
				  )

			}

			if ( ( $results < 0 ) and $criteria and ( $criteria ne 'init' ) ) {

				$dbh->do(
					"UPDATE search
             SET hits=hits+1,$res_field=$jj
             WHERE phrase=$phrase and type='$type' and criteria='$criteria' and site='SuperStore'
           "
				);

			}

		}    #end of no hits
		else {
			$jj = $results;
			if ( $criteria and ( $criteria ne 'init' ) ) {
				$dbh->do(
					"UPDATE search
             SET hits=hits+1
             WHERE phrase=$phrase and type='$type' and criteria='$criteria' and site='SuperStore'
           "
				);
			}

		}

	}    ### end of number of search results

	@inits = split /,/, $inits;
	foreach $init_dd (@inits) { $init_present{$init_dd} = 'Yes' }

	if ( ( $jj >= 1 ) and ( $criteria eq 'ecode' ) and $text ) {
		print
"<script>document.location = '/cgi-bin/toys2.cgi?af=$affiliate&ecode=$ecode_pri&bestseller=$bestseller'</script>";
	}
	if ( $bestseller eq 'Yes' ) {
		print "<script>document.location = '/cgi-bin/best_toys.cgi'</script>";
	}

	if ($first_list) {
		@list_ecode  = reverse @list_ecode;
		@list        = reverse @list;
		@bigkey_list = reverse @bigkey_list;
	}

	$first_list = $bigkey_list[0];
	$last_list  = $bigkey_list[ $j - 1 ];
	$l0         = $#list;

	#FILTER FOR NAMES IN LIST
	$l = $#list + 1;
	local ($lil) = 0;
	local ($il)  = 0;
	while ( $lil + $il <= 100 && $il <= $l - 1 ) {
		local ($lilo) = 0;
		local ($prev) = 0;
		for ( $i = 0 ; $i <= ( length( $list[$il] ) - 1 ) ; $i++ ) {
			if (   ( substr( $list[$il], $i, 1 ) eq ' ' )
				&& ( ( $i - $prev ) > 25 )
				&& substr( $list[$il], $i + 1, 1 ) )
			{
				$prev = $i + $prev;
				$lilo++;
				substr( $list[$il], $i, 1 ) = '*';
			}
		}
		$lil = $lil + $lilo;
		while ( $list[$il] =~ m/\*/ ) {
			$list[$il] =~
s/\*/<\/a><br>&nbsp;&nbsp;&nbsp;<a href='\/cgi-bin\/toys2.cgi?af=$affiliate&ecode=$list_ecode[$il]&fam=$fam&init=$init&letter=$letter&last_list=$last_list0&first_list=$first_list0&dozen_list=$dozen_list&text=$text3&criteria=$criteria&init1=$init1$price_app' class='text1'>/;
		}
		$il++;
	}
	for ( $i = $0 ; $i < $il ; $i++ ) { $list[ $i + $il ] = $list[ $i + $l ] }
	$lold     = $l;
	$l        = $il;
	$list_key = $list[ 2 * $l - 1 ];

	if ( $imax0 > 0 ) {
		$text1 = ( $fam ? "-&GT;$fam" : '' );

		$n = $imax;
		for ( $i = 0 ; $i <= $imax ; $i++ ) {

			if ( &Flag( $i + 1 ) && $i != $n ) {    #odd != last
				print '<tr>';
				&Thumbs(
					0,             $product_name[$i], $image[$i],
					$synopsis[$i], $saleprice[$i],    $bigkey[$i],
					$stars[$i],    $onsale[$i],       $ecode[$i],
					$options[$i],  $opts_set[$i],     $ecodes_set[$i],
					$price[$i],    $stock_this[$i],   $opt_set1[$i]
				);
			}

			if ( !&Flag( $i + 1 ) ) {               #even != 2
				&Thumbs(
					0,             $product_name[$i], $image[$i],
					$synopsis[$i], $saleprice[$i],    $bigkey[$i],
					$stars[$i],    $onsale[$i],       $ecode[$i],
					$options[$i],  $opts_set[$i],     $ecodes_set[$i],
					$price[$i],    $stock_this[$i],   $opt_set1[$i]
				);
				print '</tr>';
			}

			if ( &Flag( $i + 1 ) && $i eq $n ) {    #odd=last
				print '<tr>';
				&Thumbs(
					1,             $product_name[$i], $image[$i],
					$synopsis[$i], $saleprice[$i],    $bigkey[$i],
					$stars[$i],    $onsale[$i],       $ecode[$i],
					$options[$i],  $opts_set[$i],     $ecodes_set[$i],
					$price[$i],    $stock_this[$i],   $opt_set1[$i]
				);
				print '</tr>';
			}

		}    #end of product loop

	}
######  NO SEARCH RESULTS
	else {
		print <<EOT;

       <tr>
        <td bgcolor=#FFFFFF class="redlarge"><br>&nbsp;&nbsp;&nbsp;No Sex Toys found matching your inventory and search criteria.<br>&nbsp;&nbsp;&nbsp;Please search again. For help on search, <a href="javascript:MakeHelpLogin('/ahtml/help/menu_search.html')" onMouseover="self.status='Open A Help Window'; return true;" onMouseout="self.status=''; return true;" class="blacklarge">click here</a><br><br></td>
       </tr>
       <tr>
        <td align=center>
         <table width="100%" border="1" cellspacing="0" cellpadding="1" bgcolor="#FFFFFF" bordercolor="$bgcolor3">
          <tr align=center> 
           <td bgcolor="$bgcolor3" class="text3large">We recommend these Sex Toys Hot Deals:</td>
          </tr>
          <tr> 
           <td> 
            <table width=100% border="0" cellspacing="0" cellpadding="2">
             <tr valign=top align=center> 
                          
EOT

		if ( $init and ( $init ne 'all' ) ) {
			$where_hot = "and initial='$init'";
		}
		else { $where_hot = "" }

		$sql3 =

		  $dbh->prepare(
" SELECT date_toys.item,date_toys.product_name,date_toys.pthumbs,date_toys.price,date_toys.saleprice
          FROM date_toys,inventory
          WHERE date_toys.hotdeals='T' $where_hot and date_toys.item=inventory.item and inventory.available='T'
          ORDER by RAND()
          LIMIT 4
          "
		  );

		$sql3->execute;

		while ( @record = $sql3->fetchrow_array ) {
			( $item_th, $name_th, $thumb_th, $regprice_th, $price_th ) =
			  @record;
			if (   ( $aff_flag and !( $server =~ m/shop/ ) )
				or ( $server =~ m/myadultwarehouse/ ) )
			{
				$price_th = $regprice_th;
			}
			print
qq(<td width=25% class="blue"><b>TOY</b><br><a href="/cgi-bin/toys2.cgi?af=$affiliate&ecode=$item_th&init=$init&fam=$thumb_fm&race=$race" class="black"><img src="/images/pthumbs/toys/$thumb_th" width="105" height="140" border="0"><br>$name_th<br>\$$price_th</a></td>);
		}
		$sql3->finish;
		print <<EOT;
     
             </tr>
            </table>
           </td>
          </tr>
         </table>
        </td>
       </tr>

EOT

	}    ### end of no search results

	# DOZENS CONTROL (NEXT -- PREVIOUS)
	if ( $n eq 19 and $dozen eq 1 ) { print &Nextt; }
	if ( $n eq 19 and $dozen > 1 and $dozen ne 1 ) { print &PreviousNext; }
	if ( $n < 19 and $dozen > 1 ) { print &Previous; }

	print <<E_O_T;
      </table>
     </form>
     </td>
     <td align="center" valign="top" width="25%">
     <form name="InventoryForm2" METHOD=get>
      <table valign="top" border="0">
E_O_T

	require("/export/home0/vhost218/cgi-serverwide/cart.pl");
	require("/export/home0/vhost218/cgi-serverwide/promo_inc.pl");

	$initial1 = $initial;
	if ( $criteria and ( $criteria ne 'init' ) ) {
		$criteria1 = ucfirst $criteria;
		$initial1  = "$criteria1 : $text";
	}
	print <<E_O_T;
		<tr>
			<td class="text1large" height="20">&nbsp;&nbsp;&nbsp;Alphabetically Sorted List</td>
		</tr>
       <tr>
        <td class="text1large">&nbsp;&nbsp;&nbsp;$initial1</td>
       </tr>
E_O_T
	if ( !( $criteria and ( $criteria ne 'init' ) ) and ( $discount ne 'Yes' ) )
	{
		print <<E_O_T;
       <tr>
        <td valign="top">
         <select id="InventoryComboBox" name="fam" onChange="repl(this.options[this.selectedIndex].value)">
          <option value="category" SELECTED>-- Select a Category --</option>
E_O_T
		for ( $ji = 0 ; $ji <= $fam_number - 1 ; $ji++ ) {
			$fam_this = $asso1[ 2 * $ji ];
			local ($show) = $assa1{$fam_this};
			$show =~ s/&#8482;/(TM)/;
			if ( !$show ) { next }
			print '<option value="', $fam_this, '">', $show, '</option>';
		}

		print <<E_O_T;
         </select>
        </td>
       </tr>
E_O_T
	}

	if ( ( $criteria and ( $criteria ne 'init' ) ) or $discount eq 'Yes' ) {
		print <<E_O_T;
       <tr>
        <td valign="top">
         <select id="InventoryComboBox" name="fam" onChange="replC(this.options[this.selectedIndex].value)">
          <option value="category" SELECTED>-- Select a Category --</option>
E_O_T
		for ( $ji = 0 ; $ji <= $#asso00 ; $ji++ ) {
			$ini = $asso00[$ji];
			if ( $ini eq 'hotdeal' or $ini eq 'voldiscount' ) { next }
			if ( $init_present{$ini} eq 'Yes' or $criteria eq 'voldiscount' ) {
				print '<option value="', $ini, '">', $asso0{$ini}, '</option>';
			}
		}
		print <<E_O_T;
         </select>
        </td>
       </tr>
E_O_T
	}

	print <<E_O_T;
       <tr valign=top>
        <td valign=top nowrap>
E_O_T
	&RightDefault;
	print <<E_O_T;
        </td>
       </tr>
       <tr>
        <td align=center valign=middle>
E_O_T

	# DOZENS CONTROL for list (NEXT -- PREVIOUS)
	if ( $dozen_list > 1 ) {
		print
"<a href='/cgi-bin/toys.cgi?af=$affiliate&first_list=$first_list&init=$init&fam=$fam&dozen_list=$dozen_list0&letter=$letter&criteria=$criteria&text=$text3&init1=$init1$price_app' class='text1bold'><img src='/ahtml/images/arrowback.gif' HEIGHT=10 WIDTH=30 align=absmiddle border=0>BACK&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>";
	}
	if ( $l0 eq 49 ) {
		print
"<a href='/cgi-bin/toys.cgi?af=$affiliate&last_list=$last_list&init=$init&fam=$fam&dozen_list=$dozen_list1&letter=$letter&criteria=$criteria&text=$text3&init1=$init1$price_app' class='text1bold'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;NEXT<img src='/ahtml/images/arrownext.gif' HEIGHT=10 WIDTH=30 align=absmiddle border=0></a>";
	}

	if ( $server =~ /^store/i or $server =~ /myadultwarehouse/i ) {

		#options for higher price
		$price_range_options = qq(
      <option value="">All Prices</option>
      <option value="-15">less than \$15</option>
      <option value="15-20">\$15-\$20</option>
      <option value="20-25">\$20-\$25</option>
      <option value="25-30">\$25-\$30</option>
      <option value="30-35">\$30-\$35</option>      
      <option value="35-">more than \$35</option>);
	}
	else {    #options for lower price
		$price_range_options = qq(
      <option value="">All Prices</option>
      <option value="-10">less than \$10</option>
      <option value="10-15">\$10-\$15</option>
      <option value="15-20">\$15-\$20</option>
      <option value="20-25">\$20-\$25</option>
      <option value="25-30">\$25-\$30</option>
      <option value="30-35">\$30-\$35</option>      
      <option value="35-">more than \$35</option>);
	}

	print <<E_O_T;
        </td>
       </tr>  
       <tr>
        <td align=center>
         <br>
         <select name="price_rng" onChange="replP(this.options[this.selectedIndex].value)">
          <option value="" SELECTED>-- Price Range --</option>                        
          $price_range_options      
         </select>
        </td>
       </tr>                  
       <tr>
        <td align=center> 
         <br>                
E_O_T
	$br         = '';
	$alph_count = 1;
	@alphabet   = (
		'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
		'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
	);

	print <<E_O_T;
         <table cellspacing=0 cellpadding=2 border=1 bgcolor='$bgcolor3' bordercolor='$bgcolor3'>
          <tr>
           <td align=center class="text3large">Alphabetical
E_O_T
	$initial_category = $foo->escape($initial_category);
	print <<E_O_T;
           </td>
          </tr>
          <tr>
           <td align=center bgcolor="#FFFFFF" class="black">
E_O_T
	foreach $alphabet (@alphabet) {
		if   ( $init ne 'top20' ) { $init2 = $init; $fam2 = $fam }
		else                      { $init2 = '';    $fam2 = '' }
		print <<E_O_T;
<a href=/cgi-bin/toys.cgi?af=$affiliate&init=$init2&fam=$fam2&letter=$alphabet$price_app>$alphabet</a>
$br
E_O_T
		$br = '';
		$alph_count++;
		if ( $alph_count == 13 or $alph_count == 26 ) { $br = '<br>'; }
	}
	print <<E_O_T;
           </td>
          </tr>
         </table>
        </td>
       </tr> 
      </table>
     </form>
     </td> 
    </tr>
   </table>
  </td>
 </tr>
</table>

E_O_T

	#FOOTER

	require("/export/home0/vhost218/cgi-serverwide/footer.pl");

	print <<E_O_T;

</body>
</html>
E_O_T

	$sql1->finish();
	$dbh->disconnect;
	exit;
}
############################################################################################################################################
sub Thumbs {
	local (
		$control, $name,      $image,    $synopsis,  $price,
		$key,     $star,      $onsale,   $itkey,     $option,
		$opt_set, $ecode_set, $regprice, $available, $stock_set
	) = @_;

	local ($stks);
	undef @stks;
	local ($available2);
	if ( $available eq 'T' ) { $available2 = 'IN STOCK'; }
	if ( $available eq 'F' ) { $available2 = 'SPECIAL ORDER'; }
	if ( $available eq 'P' ) { $available2 = 'PRE-ORDER'; }
	if ( $available eq 'O' ) { $available2 = 'ON ORDER'; }
	if ( $available eq 'D' ) { $available2 = 'NOT AVAILABLE'; }

	#change plan A->B
	if (   ( $aff_flag and !( $server =~ m/shop/ ) )
		or ( $server =~ m/myadultwarehouse/ ) )
	{
		$price = $regprice;
	}

	#-change-

	$price = sprintf "%.2f", $price;
	local ( $tridot, $sale );
	if ( $fam eq 'results' ) { $initial = $show_param; }
	if ( length($synopsis) > 90 ) {
		$synopsis = substr( $synopsis, 0, 90 );
		$tridot = '...';
	}
	else { $tridot = '' }
	if ($control) {
		print '        <td colspan=2 height=140 align=center>
         <table width="85%" cellspacing=0 cellpadding=0>
          <td width="20%">&nbsp;</td>
          <td "width=50%" align=center valign=top>';
	}
	else {
		print '        <td width="50%" height=140 align=center valign=top>';
	}
	if ( $onsale eq 'T' ) {
		$sale =
'<img width=35 height=16 src="/ahtml/images/sale.gif" align=absmiddle border=0 alt="Volume Discounts">';
	}
	elsif ( $onsale eq 'C' ) {
		$sale =
'<img width=35 height=16 src="/ahtml/images/salec.gif" align=absmiddle border=0 alt="Clearance Specials">';
	}
	else { $sale = '' }
	$onsale1 = $onsale;
	if ( $onsale eq 'T' ) { $onsale1 = 1; }
	if ( $onsale eq 'F' ) { $onsale1 = 0; }

	$name1 = $name;
	$name1 =~ s/\'/\`/g;
	$name1 =~ s/\"/ inches/g;
	$name1 =~ s/&#8482;/\(TM\)/ig;

	print <<E_O_T;
  
  <table bgcolor="$bgcolor3" width="100%" border=1 bordercolor="$bgcolor3" cellspacing=0 cellpadding=0>
   <tr>
    <td>
     <table bgcolor="#FFFFFF" border=0 cellspacing=0 cellpadding=1 width="100%">
      <tr>
       <td colspan=3 bgcolor="$bgcolor3" valign=middle align=center class="text3large">$name</td>
      </tr>
      <tr>
       <td rowspan=2 valign=top align=center width="38%"><a href="/cgi-bin/toys2.cgi?af=$affiliate&ecode=$itkey&init=$init&fam=$fam&letter=$letter&last_list=$last_list0&first_list=$first_list0&dozen_list=$dozen_list&text=$text3&criteria=$criteria&init1=$init1$price_app" onmouseover="self.status='CLICK FOR MORE INFO ON $name1';return true" onmouseout="self.status='';return true" class="blackbold"><img src="/images/pthumbs/toys/$image" height="140" width="105" border="0" alt="$name"><br>DETAILS</a></td>
       <td colspan=2 valign=top>
        <table width="100%" height=140 border=0 cellspacing=2 cellpadding=0>
         <tr>
          <td valign=top height=76 class="black">&nbsp;&nbsp;$synopsis$tridot<br><a href="/cgi-bin/toys2.cgi?af=$affiliate&ecode=$itkey&init=$init&fam=$fam&letter=$letter&last_list=$last_list0&first_list=$first_list0&dozen_list=$dozen_list&text=$text3&criteria=$criteria&init1=$init1$price_app" onmouseover="self.status='CLICK FOR MORE INFO ON $name1';return true" onmouseout="self.status='';return true">more...</a></td>
         </tr>
         <tr>
          <td valign=top class="black">

E_O_T

	if ( $option ne 'none' ) {

		@stks = split /,/, $stock_set;
		$opt_set =~ tr/\'/\`/;
		local (@opt) = split /,/, $opt_set;
		local (@ecd) = split /,/, $ecode_set;

		$opt0  = $opt[0];
		$ecod0 = $ecd[0];

		print
"<span class='blue'>&nbsp;Select $option:</span><br>&nbsp;<select name=opt$i onChange=sel$i()>";

		for ( $jjj = 0 ; $jjj <= $#opt ; $jjj++ ) {

			$stk_s = ",$stks[$jjj]";
			$ecd[$jjj] =~ s/^ //;
			$opt[$jjj] =~ s/^ //;
			print "<option value='$ecd[$jjj]$stk_s'>$opt[$jjj]";
		}

		print '</select>';

		$available2 =
"<img name=stock_image$i src=/ahtml/images/$stks[0].gif width=90 height=8 border=0>";
	}

	else {
		$opt0  = 'none';
		$ecod0 = "$itkey";
	}

	print <<E_O_T;
          </td>
         </tr>
         <tr>
          <td height=18>&nbsp;<a href="javascript:MakeHelpLogin('/ahtml/help/menu_status.html')" onMouseover="self.status='Open A Help Window'; return true;" onMouseout="self.status=''; return true;" class="redlarge">$available2</a>&nbsp;</td>
         </tr>
        </table>
       </td>
      </tr>
      <tr>
       <td valign=middle nowrap class="blacklarge">&nbsp;&nbsp;\$$price</td>
       <td align=right valign=middle nowrap>
E_O_T

	$name = $name1;

	if ( $stks[0] ) { $available = $stks[0]; }
	if ( $available ne 'D' ) {
		print <<EOT;
<a href="javascript:MakeHelpLogin('/ahtml/help/menu_discounts.html')" onMouseover="self.status='Open A Help Window'; return true;" onMouseout="self.status=''; return true;")">$sale</a>
<a href="javascript:setCart('$onsale1', $i,$price)"  onmouseover="self.status='Add to Shopping Cart';return true" onmouseout="self.status='';return true;"><img height=16 width=35 src="/ahtml/images/buyicon.gif" align=absmiddle border=0 alt="Add to Cart"></a>
EOT
	}
	else { print '&nbsp;' }

	print <<E_O_T;

<script language="JavaScript">
<!--
ecod[$i]='$ecod0'
coll[$i]='$opt0'
prim[$i]='$itkey'
function sel$i(){
var strng$i=document.InventoryForm.opt$i.options[document.InventoryForm.opt$i.selectedIndex].value;
ecod[$i]=strng$i.substr(0,8);
stkk[$i]='T';
E_O_T

	if ( $option ne 'none' ) {
		print <<EOT;
stkk[$i]=strng$i.substr(9,1); document.stock_image$i.src='/ahtml/images/'+stkk[$i]+'.gif';
EOT
	}

	print <<E_O_T;
coll[$i]=document.InventoryForm.opt$i.options[document.InventoryForm.opt$i.selectedIndex].text}
// -->
</script>

       </td>
      </tr>
     </table>
    </td>
   </tr>
  </table>
  </td>
E_O_T
	if ($control) { print '  <td width="20%">&nbsp;</td></tr></table>'; }
	1;
}

########################################################################

# FUNCTION FLAG(NUMBER)
sub Flag {
	local ($input) = @_;
	local ($flag)  = 1;
	$flag = 0
	  if ( $input / 2 eq int( $input / 2 ) );  # $flag=0 if even, and =1 if odd;
	return $flag;
	1;
}

############################################################################################################################################

#RIGHTDEFAULT
sub RightDefault {

	if ( $criteria and ( $criteria ne 'init' ) ) { $initial = $text; }
	if ( !$family ) {
		$family = 'All Categories';
		if ($price_range) { $family = $price2 }
	}
	if ($letter) { $letter1 = "<br>&nbsp;&nbsp;&nbsp;$letter" }
	if ( $letter or ( $criteria and ( $criteria ne 'init' ) ) ) {
		$family = "$jj products found$letter1";
	}
	if ($init1) { $family = $asso0{$init1} . $letter1 }
	print <<E_O_T;

    <tr>
     <td valign=top nowrap class="text1large">&nbsp;&nbsp;&nbsp;$family<br></td>
    </tr>
    <tr valign=top>
     <td valign=top nowrap class='text1'>

E_O_T
	for ( $j = 0 ; $j <= ( $l - 1 ) ; $j++ ) {
		print
"&#8226;&nbsp;<a href='/cgi-bin/toys2.cgi?af=$affiliate&ecode=$list_ecode[$j]&letter=$letter&fam=$fam&init=$init&last_list=$last_list0&first_list=$first_list0&dozen_list=$dozen_list&text=$text3&criteria=$criteria&init1=$init1$price_app' class='text1'>$list[$j]</a><br>
";
	}
	print "<br>";
	1;
}

##############################################################################################
sub fam2init {
	if (   $fam eq 'cockring'
		or $fam eq 'massage'
		or $fam eq 'egg'
		or $fam eq 'herbals'
		or $fam eq 'strap-on' )
	{
		$init = $fam;
		$fam  = '';
	}
	else { return }
}
#############################################################################################################################################

sub getEcode {
	local ($ec) = @_;

	local ($sqlV) = $dbh->prepare(
		" SELECT  item
        FROM ecode
        WHERE ecode='$ec'
             "
	);

	$sqlV->execute;
	($ec) = $sqlV->fetchrow_array;
	$sqlV->finish;

	return $ec;

}

##################################################################################

sub getProductData {

	local ( $ad_inv, $opt_i, $opt3_1, $ecd3_1, $stk3_1, $opt3_0, $ecd3_0,
		$stk3_0 );
	if   ( $criteria ne 'ecode' ) { $ad_inv = " $inv_mod"; }
	else                          { $ad_inv = '' }

	$sql1 = $dbh->prepare(
" SELECT $table.item,$table.product_name,$table.saleprice,$table.price,$table.manufacturer,$table.$pth,$table.voldiscount,$table.bigkey,$table.synopsis,$table.stars,$table.options,$table.options_set,$table.item_set,inventory.available,inventory.opt_set
     FROM $table,inventory
     $where and $table.item=inventory.item $ad_inv
     ORDER by $table.bigkey $order
     LIMIT 20
     "
	);

	$sql1->execute;
	$i = 0;
	while ( @record = $sql1->fetchrow_array ) {
		(
			$ecode[$i],      $product_name[$i], $saleprice[$i],
			$price[$i],      $manufacturer[$i], $image[$i],
			$onsale[$i],     $bigkey[$i],       $synopsis[$i],
			$stars[$i],      $options[$i],      $opts_set[$i],
			$ecodes_set[$i], $stock_this[$i],   $opt_set1[$i]
		) = @record;
		if ( substr( $synopsis[$i], 100, 1 ) ) {
			$synopsis[$i] = substr( $synopsis[$i], 0, 100 ) . '...';
		}
		$ecodes_set[$i] =~ s/ //;

		if ( $options[$i] and ( $options[$i] ne 'none' ) ) {
			local (@opt3) = split /,/, $opts_set[$i];
			local (@ecd3) = split /,/, $ecodes_set[$i];
			local (@stk3) = split /,/, $opt_set1[$i];

			#filter options for this stock
			if ( $stock ne 'A' ) {
				undef(@act_opt);
				for ( $opt_i = 0 ; $opt_i <= $#stk3 ; $opt_i++ ) {
					if ( $stock eq 'N' ) {
						if ( $stk3[$opt_i] eq 'T' or $stk3[$opt_i] eq 'P' ) {
							push( @act_opt, $opt_i );
						}
					}
					elsif ( $stk3[$opt_i] eq $stock ) {
						push( @act_opt, $opt_i );
					}
				}
				undef @opt3_1;
				undef @ecd3_1;
				undef @stk3_1;
				for ( $opt_i = 0 ; $opt_i <= $#act_opt ; $opt_i++ ) {
					$opt3_1[$opt_i] = $opt3[ $act_opt[$opt_i] ];
					$ecd3_1[$opt_i] = $ecd3[ $act_opt[$opt_i] ];
					$stk3_1[$opt_i] = $stk3[ $act_opt[$opt_i] ];
				}
				$opts_set[$i]   = join( ',', @opt3_1 );
				$ecodes_set[$i] = join( ',', @ecd3_1 );
				$opt_set1[$i]   = join( ',', @stk3_1 );
			}

			#push T to first pos.
			elsif ( $stk3[0] ne 'T' ) {
				$stk3_0 = $stk3[0];
				$opt3_0 = $opt3[0];
				$ecd3_0 = $ecd3[0];
			  COMMENTS: for ( $opt_i = 1 ; $opt_i <= $#stk3 ; $opt_i++ ) {
					if ( $stk3[$opt_i] eq 'T' ) {
						$stk3[0]      = $stk3[$opt_i];
						$stk3[$opt_i] = $stk3_0;
						$opt3[0]      = $opt3[$opt_i];
						$opt3[$opt_i] = $opt3_0;
						$ecd3[0]      = $ecd3[$opt_i];
						$ecd3[$opt_i] = $ecd3_0;
						last COMMENTS;
					}
				}
				$opts_set[$i]   = join( ',', @opt3 );
				$ecodes_set[$i] = join( ',', @ecd3 );
				$opt_set1[$i]   = join( ',', @stk3 );
			}
		}

		$i++;
	}
	$imax0 = $i;
	$imax  = $i - 1;
	$sql1->finish;

}

sub PrintHeader {
	return "Content-type: text/html\n\n";
}

# NEXT
sub Nextt {
	return
"<tr><td>&nbsp;</td><td align=right><a href='/cgi-bin/toys.cgi?af=$affiliate&text=$text3&init=$init&criteria=$criteria&fam=$fam&last=$last&dozen=$dozen1&letter=$letter&last_list=$last_list0&first_list=$first_list0&dozen_list=$dozen_list&init1=$init1$price_app'><img src='/ahtml/images/next.gif' border=0 alt='Next' HEIGHT=28 WIDTH=80></a><img src='/ahtml/images/spacer.gif' HEIGHT=6 WIDTH=6></td></tr>";
}

# PREVIOUS
sub Previous {
	return
"<tr><td><img src='/ahtml/images/spacer.gif' HEIGHT=6 WIDTH=6><a href='/cgi-bin/toys.cgi?af=$affiliate&text=$text3&init=$init&criteria=$criteria&fam=$fam&first=$first&dozen=$dozen0&letter=$letter&last_list=$last_list0&first_list=$first_list0&dozen_list=$dozen_list&init1=$init1$price_app'><img src='/ahtml/images/back.gif' HEIGHT=28 WIDTH=80 border=0 alt='Previous'></a></td><td></td></tr>";
}

# PREVIOUS-NEXT
sub PreviousNext {
	return
"<tr><td><img src='/ahtml/images/spacer.gif' HEIGHT=6 WIDTH=6><a href='/cgi-bin/toys.cgi?af=$affiliate&text=$text3&init=$init&criteria=$criteria&fam=$fam&first=$first&dozen=$dozen0&letter=$letter&last_list=$last_list0&first_list=$first_list0&dozen_list=$dozen_list&init1=$init1$price_app'><img src='/ahtml/images/back.gif' HEIGHT=28 WIDTH=80 border=0 alt='Previous'></a></td><td align=right><a href='/cgi-bin/toys.cgi?af=$affiliate&text=$text3&init=$init&criteria=$criteria&fam=$fam&last=$last&dozen=$dozen1&letter=$letter&last_list=$last_list0&first_list=$first_list0&dozen_list=$dozen_list&init1=$init1$price_app'><img src='/ahtml/images/next.gif' HEIGHT=28 WIDTH=80 border=0 alt='Next'></a><img src='/ahtml/images/spacer.gif' HEIGHT=6 WIDTH=6></td></tr>";
}

##########################################################################
sub get_cookie {
	local ( $chip, $val );
	foreach ( split( /; /, $ENV{'HTTP_COOKIE'} ) ) {

   # split cookie at each ; (cookie format is name=value; name=value; etc...)
   # Convert plus to space (in case of encoding (not necessary, but recommended)
		s/\+/ /g;    # Split into key and value.
		( $chip, $val ) = split( /=/, $_, 2 );    # splits on the first =.
		        # Convert %XX from hex numbers to alphanumeric
		$chip =~ s/%([A-Fa-f0-9]{2})/pack("c",hex($1))/ge;
		$val  =~ s/%([A-Fa-f0-9]{2})/pack("c",hex($1))/ge;

		# Associate key and value
		$cookie{$chip} .= "\1"
		  if ( defined( $cookie{$chip} ) );    # \1 is the multiple separator
		$cookie{$chip} .= $val;
	}
}

sub ReadParse {
	local (*in) = @_ if @_;
	local ( $i, $key, $val );

	# Read in text
	if (&MethGet) {
		$in = $ENV{'QUERY_STRING'};
	}
	elsif (&MethPost) {
		read( STDIN, $in, $ENV{'CONTENT_LENGTH'} );
	}

	@in = split( /[&;]/, $in );

	foreach $i ( 0 .. $#in ) {

		# Convert plus's to spaces
		$in[$i] =~ s/\+/ /g;

		# Split into key and value.
		( $key, $val ) = split( /=/, $in[$i], 2 );    # splits on the first =.

		# Convert %XX from hex numbers to alphanumeric
		$key =~ s/%(..)/pack("c",hex($1))/ge;
		$val =~ s/%(..)/pack("c",hex($1))/ge;

		# Associate key and value
		$in{$key} .= "\0"
		  if ( defined( $in{$key} ) );    # \0 is the multiple separator
		$in{$key} .= $val;

	}

	return scalar(@in);
}

sub MethGet {
	return ( $ENV{'REQUEST_METHOD'} eq "GET" );
}

# MethPost
# Return true if this cgi call was using the POST request, false otherwise

sub MethPost {
	return ( $ENV{'REQUEST_METHOD'} eq "POST" );
}