#!/usr/bin/perl
#!c:/Perl/bin/Perl.exe

use CGI::Carp qw/fatalsToBrowser/;
use CGI;
use CGI qw(:standard);
use CGI::Cookie;
use DBI;
#use LWP;
#use LWP::Simple;

require "function.pl";
require "blank.pl";

my $cgi= new CGI;
$act = $cgi->param('act');


$dbh = &connect;
################################################################################################
($domain, $cgidir, $mailer, $mailer2, $rootdir, $title, $describ, $keywords, $rows) = &getsetup("domain cgidir mailer mailer2 rootdir html_title html_describ html_keywords rows");
$filedir = $rootdir . $filedir;
($true, $status, $user_id, $discount, $session) = &access;
################################################################################################

if($act eq 'index') {
	&top;
	&top_text_describ;
	&present_side;
#	&speech_side;
	&end;
	}
	elsif($act eq 'text' || $act eq 'call' || $act eq 'call_accept' || $act eq 'catalog' || $act eq 'show' || $act eq 'caser' || $act eq 'order' || $act eq 'accept') {
		&top;
		&{$act};
		&end;
		}
		elsif($act eq 'pay' || $act eq 'click' || $act eq 'order_generate' || $act eq 'call_send') {
			&{$act};
			}
			else {

				if(&text) {
					&top;
					print "<table cellpadding=0 cellspacing=0 width=100%>";
					print "	<tr><td style='border:1px solid #dadada; padding:15px;' class=format>", &text, "</td></tr>";
					print "</table>";
					print "<table cellpadding=0 cellspacing=0><tr><td height=10></td></tr></table>";
					&end;
					}
					else {
						&top('404');
						print "<table cellpadding=0 cellspacing=0 width=100%>";
						print "	<tr>";
						print "		<td style='border:1px solid #dadada; padding:15px;' class=format>";
						print "			<div align=center>Возможно информация для этого раздела готовится<br><a href='javascript:history.back(-1);'>вернуться назад</a></div>";
						print "		</td>";
						print "	</tr>";
						print "</table>";
						print "<table cellpadding=0 cellspacing=0><tr><td height=10></td></tr></table>";
						&end;
						}

				}


###########################################################################################################
$dbh->disconnect;








###########################################################################################################################################
###########################################################################################################################################
sub present_side {

	print "<table cellpadding=0 cellspacing=0 width=100%>";
	print "<tr><td height=29 class=zag style='background:#5392C6;' colspan=50><img src='/img/zag.gif' width=8 height=9 style='margin-right:5px;'> <a href='' style='color:white;'>ГЛАВНАЯ</a> &nbsp; | &nbsp; <a href='/catalog' style='color:white;'>КАТАЛОГ</a></td></tr>";
	print "<tr><td height=5></td></tr>";
	print "<tr><td>";

	my $sth = $dbh->prepare ("SELECT id FROM catalog WHERE sklad >0");
	$sth->execute;
	while (@val = $sth->fetchrow_array()) {
		&card($val[0]);
		}
	$sth->finish;

	print "</td></tr>";
	print "</table>";
	}




###########################################################################################################################################
###########################################################################################################################################
sub card {
my $id = $_[0];

	$sth = $dbh->prepare ("SELECT category, subcategory, name, model, sex, price, price2, new FROM catalog WHERE id=?");
	$sth->execute($id);
	my $row = $sth->fetchrow_hashref;

	my $category = $row->{category};
	my $subcategory = $row->{subcategory};
	my $name = $row->{name};
	my $model = $row->{model};
	my $price = $row->{price};
	my $price2 = $row->{price2};
	my $sex = $row->{sex};
	my $new = $row->{new};

	$sth->finish;


	$image = &get_image($val[0], undef, "s");

	
	print qq(
	<div style="float:left; margin-right:20px; margin-bottom:20px; padding:10px 10px 0px 10px; width:200px; height:330px; border:1px solid #e8e8e8; text-align:center; background:#f6f6f6;">
		<table cellpadding=0 cellspacing=0 width=100% height=100% style='font-size:11px; font-family:tahoma;'>
			<tr><td colspan=2 height=1 style="text-align:center; margin-bottom:5px;"><a href="/show/&id=$id"><img src="$image" title="$category $subcategory - $model" style="border:0px;"></a></td></tr>
			<tr><td colspan=2 height=5></td></tr>
			<tr>
				<td colspan=2 height=1>
					$name - $model<br><img src='/img/dot.gif' width=1 height=5><br>
			);
					print "<u style='font-size:10px;'>$sex</u><br><img src='/img/dot.gif' width=1 height=5><br>" if($sex);
					print "<img src='/img/new.gif' alt='Новинка!' align=middle><br><img src='/img/dot.gif' width=1 height=5><br>" if($new);
			print qq(
				</td>
			</tr>

			<tr>
				<td colspan=2 height=1>
				);
				print "Цена: <span style='color:#8DC641;'><b>$price руб.</b></span>" if(!$price2);
				print "Цена: <span style='color:#8DC641;'><b><s style='color:#dddddd;'>$price руб.</s></b> | <b>$price2 руб.</b></span>" if($price2);

			print qq(
				</td>
			</tr>

			<tr><td colspan=2></td></tr>
			<tr><td colspan=2 height=1 style='text-align:center; border-top:1px solid #e8e8e8;'><a href='/pay/&id=$id' style='display:block; text-align:center; padding:12px 0px; color:#EA1414; font-size:12px;'><img src='/img/pay.gif' width=13 height=11 border=0 style='margin-top:-2px; margin-right:3px;' align=absmiddle><b>КУПИТЬ</b></a></td></tr>
		</table>
	</div>
	);
	}	
	
	
	
	



###########################################################################################################################################
###########################################################################################################################################
sub speech_side {
my($sth, $limit);


	print "<table cellpadding=0 cellspacing=0><tr><td height=10></td></tr></table>";
print qq(


					<table cellpadding=0 cellspacing=0 width=100%>
						<tr>
							<td style='border:1px solid #dadada;' class=text>
							<!-- speech_side -->


								<table cellpadding=0 cellspacing=0 width=100%>
									<tr><td height=29 class=zag colspan=3><img src='/img/zag.gif' width=8 height=9 style='margin-right:5px;'> Я ВЫБИРАЮ ДЛЯ:</td></tr>
									<tr><td height=10></td></tr>
									<tr>
										<td width=50% align=center><table cellpadding=0 cellspacing=0 width=100%><tr><td width=30></td><td width=12><img src='/img/arrow_blue.gif' width=5 height=7></td><td colspan=2><a href='/catalog' class=category style='color:#8DC641;'>ДЛЯ ПОДАРКА</a></td><td width=10></td></tr><tr><td height=3></td></tr></table></td>
										<td width=1 bgcolor=#DADADA><img src='/img/dot.gif' width=1 height=1></td>
										<td width=50% align=center><table cellpadding=0 cellspacing=0 width=100%><tr><td width=30></td><td width=12><img src='/img/arrow_blue.gif' width=5 height=7></td><td colspan=2><a href='/catalog' class=category style='color:#8DC641;'>ДЛЯ СЕБЯ</a></td><td width=10></td></tr><tr><td height=3></td></tr></table></td>
									</tr>
									<tr>
										<td width=50% align=center><table cellpadding=0 cellspacing=0 width=100%><tr><td width=30></td><td width=12><img src='/img/arrow_blue.gif' width=5 height=7></td><td colspan=2><a href='/catalog' class=category style='color:#8DC641;'>ДЛЯ ТЕБЯ</a></td><td width=10></td></tr><tr><td height=3></td></tr></table></td>
										<td width=1 bgcolor=#DADADA><img src='/img/dot.gif' width=1 height=1></td>
										<td width=50% align=center><table cellpadding=0 cellspacing=0 width=100%><tr><td width=30></td><td width=12><img src='/img/arrow_blue.gif' width=5 height=7></td><td colspan=2><a href='/catalog' class=category style='color:#8DC641;'>ДЛЯ НЕЕ</a></td><td width=10></td></tr><tr><td height=3></td></tr></table></td>
									</tr>
									<tr>
										<td width=50% align=center><table cellpadding=0 cellspacing=0 width=100%><tr><td width=30></td><td width=12><img src='/img/arrow_blue.gif' width=5 height=7></td><td colspan=2><a href='/catalog' class=category style='color:#8DC641;'>ДЛЯ ПОДАРКА НА СВАДЬБУ</a></td><td width=10></td></tr><tr><td height=3></td></tr></table></td>
										<td width=1 bgcolor=#DADADA><img src='/img/dot.gif' width=1 height=1></td>
										<td width=50% align=center><table cellpadding=0 cellspacing=0 width=100%><tr><td width=30></td><td width=12><img src='/img/arrow_blue.gif' width=5 height=7></td><td colspan=2><a href='/catalog' class=category style='color:#8DC641;'>ДЛЯ ПОДАРКА СОСЕДКЕ ВАЛЕНТИНЕ ПЕТРОВНЕ</a></td><td width=10></td></tr><tr><td height=3></td></tr></table></td>
									</tr>
									<tr><td height=10></td></tr>
								</table>
							</td>
						</tr>
					</table>

	);
					
	}

	
	





	
###########################################################################################################################################
###########################################################################################################################################
sub catalog {
my($row, $sth, $category, $subcategory, $brand, $sc, $br, $search_engine);


my $category = $cgi->param('category');
my $subcategory = $cgi->param('subcategory');
my $category_name = $dbh->selectrow_array ("SELECT category FROM catalog WHERE id=?", undef, $category);
if(!$category_name) { $category_name = $dbh->selectrow_array ("SELECT category FROM catalog WHERE translator=?", undef, $subcategory); } 
my $subcategory_name = $dbh->selectrow_array ("SELECT subcategory FROM catalog WHERE translator=?", undef, $subcategory);


my $sex = $cgi->param('sex');
my $speech = $cgi->param('speech');
if($speech) { $speech = $dbh->selectrow_array ("SELECT speech FROM catalog WHERE id=?", undef, $speech); } 
my $ot = $cgi->param('ot');
my $do = $cgi->param('do');
if($ot > $do) { $ot=$cgi->param('do'); $do = $cgi->param('ot');}




	# навигатор
	if($category || $subcategory) {
		my $id = $dbh->selectrow_array ("SELECT id FROM catalog WHERE category=? limit 1", undef, $category_name);

		$navigate = " &nbsp; | &nbsp; <a href='/catalog/&category=$id' style='color:white;'><b>". &uc($category_name) ."</b></a>";
		}
		if($subcategory) {
			$navigate .= " &mdash; <a href='/catalog/$subcategory/' style='color:white;'>$subcategory_name</a>";
			}
		
		

	# поиск
#	$search_engine = &search_engine("catalog", "brand, model", $search) if($search);
#	$where .= " " .$search_engine if($search_engine);




	# основная выборка
	###########################################################################################################
	$where = "";
	$where .= "category='$category_name' and " if($category_name);
	$where .= "translator='$subcategory' and " if($subcategory);
	$where .= "sex='Мужские' and " if($sex eq 1);
	$where .= "sex='Женские' and " if($sex eq 2);
	$where .= "speech='$speech' and " if($speech);
	$where .= "sklad>0 and ";

	
	$where .= "price > $ot and " if($ot);
	$where .= "price < $do and " if($do);

	
	
#	$where .= "subcategory='$subcategory' and " if($subcategory && param(subcategory));
#	$where .= "(subcategory is null or subcategory='') and " if(!$subcategory && param(subcategory));
#	$where .= "brand='$brand' and " if(param(brand));
	$where = "WHERE " . substr($where, 0, -5) if($where);
			

	my $page = $cgi->param('ch') || 9;
	my $ch = $cgi->param('ch') || 0;

	$all = $dbh->selectrow_array ("SELECT COUNT(*) FROM catalog $where");

	$start = $page*$ch;
	$limit = "LIMIT $start,$page";
	###########################################################################################################
	
	
	print "<table cellpadding=0 cellspacing=0 width=100%>";
	print "<tr><td height=29 class=zag style='background:#5392C6;' colspan=50><img src='/img/zag.gif' width=8 height=9 style='margin-right:5px;'> <a href='/catalog' style='color:white;'>КАТАЛОГ</a>$navigate</td></tr>";
	print "<tr><td height=5></td></tr>";
	print "<tr><td>";

	$sth = $dbh->prepare ("SELECT id FROM catalog $where $limit");
	$sth->execute;
	while (@val = $sth->fetchrow_array()) {
		&card($val[0]);
		$flags=1;
		}
	$sth->finish;

	print "</td></tr>";

	if(!$flags) {
		print "<tr><td style='border:1px solid #dadada; padding:15px;' class=format><div align=center>К сожалению, в Каталоге нет товаров удовлетворяющих Вашему запросу<br><a href='javascript:history.back(-1);'>вернуться назад</a></div></td></tr>";
		}
		else {
			print "<tr><td height=10></td></tr>";
			}
	
	print "<tr><td height=5></td></tr>";
	print "<tr><td height=29 class=zag style='background:#5392C6;' colspan=50>"; &page($all); print "</td></tr>";

	$add_text = $dbh->selectrow_array ("SELECT text FROM content WHERE translator=? and visible='1'", undef, $category);
	if($add_text) {
		print "<tr><td style='padding:10px;' class=text colspan=50>$add_text</td></tr>";
		}
		
	print "</table>";
	}
	



	
	
###########################################################################################################
sub page {
my($all) = $_[0];
my($text, $page, $ch);

my $category = $cgi->param('category');
my $subcategory = $cgi->param('subcategory');
my $sex = $cgi->param('sex');
my $speech = $cgi->param('speech');
my $ot = $cgi->param('ot');
my $do = $cgi->param('do');
my $page = $cgi->param('page') || 9;
my $ch = $cgi->param('ch') || 0;


$to = "/catalog/";
$to .= "$subcategory/" if($subcategory);
$to .= "&category=$category" if($category);
$to .= "&sex=$sex" if($sex);
$to .= "&speech=$speech" if($speech);
$to .= "&ot=$ot" if($ot);
$to .= "&do=$do" if($do);



print "<table cellpadding=0 cellspacing=0 width=100%>";
print "	<tr>";

if ($page < $all) {


print "		<td style='color:white; font-family:tahoma; font-size:10px;' width=1>Страница:</td>" if ($page ne "all" && $page < $all);
print "		<td>";
print "			<table cellpadding=0 cellspacing=1 align=left>";
print "				<tr>";


	$a =  int( ($all/$page-0.00001)) ;
	$pred = $ch-1;
	$nxt = $ch+1;
	
	if ($pred >-1 ){ print "<td width=18 class=passive onMouseOver=\"this.style.background='white'; this.style.color='#5392C6';\" onMouseOut=\"this.style.background='#5392C6';  this.style.color='white';\" onClick=\"window.location.href='$to&ch=$pred'\">&laquo;</td>"; }

	$l = $ch - 4;
	$r = $ch + 4;

	if($l < 0) {
		$l=0;
		if ($r<$a){ $r+=4;}
		}	

	if($r >$a) {
		$r=$a;
		if ($l>0 && $ch){ $l-=1;}
		}

	if ($l>0 && $r>=$a) {
		$l-=1; $r=$a;
		}

		for ($j=$l;$j<=$r;$j++) {
			$num = $j+1;
			if ($ch eq $j){ print "<td bgcolor=white width=18 height=18 class=active>$num</td>"; }
			else { print "<td width=18 class=passive onMouseOver=\"this.style.background='white'; this.style.color='#5392C6';\" onMouseOut=\"this.style.background='#5392C6';  this.style.color='white';\" onClick=\"window.location.href='$to&ch=$j'\">$num</td>"; }
			}

	if ($nxt < $a+1){ print "<td width=18 class=passive onMouseOver=\"this.style.background='white'; this.style.color='#5392C6';\" onMouseOut=\"this.style.background='#5392C6';  this.style.color='white';\" onClick=\"window.location.href='$to&ch=$nxt'\">&raquo;</td>"; }
print "					</tr>";
print "				</table>";
print "		</td>";
}
print "		<td></td>";
print "		<td style='color:white; font-family:tahoma; font-size:10px;' width=1><nobr>Всего: $all</nobr></td>";
print "	</tr>";
print "</table>";
}
	
	



###########################################################################################################################################
###########################################################################################################################################
sub show {
my $id = $cgi->param('id');
my $num = $cgi->param('num');

my $sth = $dbh->prepare ("SELECT id, art, category, subcategory, name, translator, describ, sex, model, tip, mech, korpus, cifer, braslet, speech, sklad, price, price2, new FROM catalog where id=?");
$sth->execute($id);
$row = $sth->fetchrow_hashref;

my $art = $row->{art};
my $category = $row->{category};
my $subcategory = $row->{subcategory};
my $name = $row->{name};
my $translator = $row->{translator};
my $describ = $row->{describ};
my $sex = $row->{sex};
my $model = $row->{model};
my $tip = $row->{tip};
my $mech = $row->{mech};
my $korpus = $row->{korpus};
my $cifer = $row->{cifer};
my $braslet = $row->{braslet};
my $speech = $row->{speech};
my $sklad = $row->{sklad};
my $price = $row->{price};
my $price2 = $row->{price2};
my $new = $row->{new};
$sth->finish;


	# изображения
	if(!$num) {
		$num = $dbh->selectrow_array ("SELECT visible FROM image WHERE cid=?", undef, $id);
		}

	
	$image = &get_image($id, $num, "b");

	$image1 = &get_image($id, "1", "S") if($num ne '1');
	$image2 = &get_image($id, "2", "S") if($num ne '2');
	$image3 = &get_image($id, "3", "S") if($num ne '3');

	if($image) { $image = "<img src='$image' alt='$category $subcategory - $brand $model' border=0 style='border-color:#CCC8C8;'>"; }

	$image1L = &get_image($id, "1", "L") if($num eq '1');
	$image2L = &get_image($id, "2", "L") if($num eq '2');
	$image3L = &get_image($id, "3", "L") if($num eq '3');

	$image1 = "<a href='/show/&id=$id&num=1'><img src='$image1' alt='$category\\$subcategory - $brand $model (1)' width=54 height=54 border=0 style='border-color:gray;'></a>" if($image1 ne '/img/nophoto.gif' && $image1);
	$image2 = "<a href='/show/&id=$id&num=2'><img src='$image2' alt='$category\\$subcategory - $brand $model (2)' width=54 height=54 border=0 style='border-color:gray;'></a>" if($image2 ne '/img/nophoto.gif' && $image2);
	$image3 = "<a href='/show/&id=$id&num=3'><img src='$image3' alt='$category\\$subcategory - $brand $model (3)' width=54 height=54 border=0 style='border-color:gray;'></a>" if($image3 ne '/img/nophoto.gif' && $image3);
	
	
	print "<table cellpadding=0 cellspacing=0 width=100%>";
	print "<tr><td colspan=3 height=29 class=zag style='background:#5392C6;' colspan=50><img src='/img/zag.gif' width=8 height=9 style='margin-right:5px;'> <a href='/catalog' style='color:white;'>КАТАЛОГ</a>$navigate</td></tr>";
	print "<tr><td colspan=3 height=5></td></tr>";
	print "<tr>";
	print "	<td style='border:1px solid #dadada;'>";
	print "		<table cellpadding=0 cellspacing=0>";
	print "			<tr><td>$image</td></tr>";
	print "			<tr><td height=1 bgcolor=#dadada></td></tr>" if(($image1 && $image1 ne '/img/nophoto.gif') || ($image2 && $image2 ne '/img/nophoto.gif') || ($image3 && $image3 ne '/img/nophoto.gif'));
	print "			<tr>";
	print "				<td align=center>";
	print "					<table cellpadding=0 cellspacing=0>";
	print "						<tr>";

	if($image1 && $image1 ne '/img/nophoto.gif') { print "<td style='padding:10px;'><a href='/show/&id=$id&num=1'>$image1</a></td>"; }
	print "<td width=15><img src='/img/dot.gif' width=15 height=1></td><td width=1 bgcolor='#dadada'><img src='/img/dot.gif' width=1 height=1></td><td width=15><img src='/img/dot.gif' width=15 height=1></td>" if(($image1 && $image1 ne '/img/nophoto.gif') || ($image2 && $image2 ne '/img/nophoto.gif'));
	if($image2 && $image2 ne '/img/nophoto.gif') { print "<td style='padding:10px;'><a href='/show/&id=$id&num=2'>$image2</a></td>"; }
	print "<td width=15><img src='/img/dot.gif' width=15 height=1></td><td width=1 bgcolor='#dadada'><img src='/img/dot.gif' width=1 height=1></td><td width=15><img src='/img/dot.gif' width=15 height=1></td>" if(($image2 && $image2 ne '/img/nophoto.gif') || ($image3 && $image3 ne '/img/nophoto.gif'));
	if($image3 && $image3 ne '/img/nophoto.gif') { print "<td style='padding:10px;'><a href='/show/&id=$id&num=3'>$image3</a></td>"; }

	print "						</tr>";
	print "					</table>";
	print "				</td>";
	print "			</tr>";
	print "			</table>";
	print "	</td>";
	print "	<td style='border:1px solid #dadada; border-left:0px; padding-top:10px;' valign=top>";

	print "	<table cellpadding=2 cellspacing=0 width=100%>";
	print "		<tr><td width=10 rowspan=19><img src='/img/dot.gif' width=10 height=1></td><td></td><td width=10 rowspan=19><img src='/img/dot.gif' width=10 height=1></td></tr>";
	print "		<tr><td class=zag>НАИМЕНОВАНИЕ:</td></tr>";
	print "		<tr><td class=format><b>$category &mdash; $subcategory &mdash; $model</b></td></tr>";
	print "		<tr><td class=format><img src='/img/new.gif'></td></tr>" if($new);

	print "		<tr><td height=20></td></tr>";
	if($describ || $sex) {
	print "		<tr><td class=zag>ОПИСАНИЕ:</td></tr>";
	print "		<tr><td class=format>$describ</td></tr>" if($describ);
	print "		<tr><td height=10></td></tr>";
	print "		<tr><td class=format><b>Для кого:</b> $sex</td></tr>" if($sex);
	}
	
	if($tip || $mech || $korpus || $cifer || $braslet || $sklad ==0) {
	print "		<tr><td height=20></td></tr>";
	print "		<tr><td class=zag>ДОПОЛНИТЕЛЬНО:</td></tr>";
	print "		<tr><td class=format><b>Тип:</b> $tip</td></tr>" if($tip);
	print "		<tr><td class=format><b>Механизм:</b> $mech</td></tr>" if($mech);
	print "		<tr><td class=format><b>Корпус:</b> $korpus</td></tr>" if($korpus);
	print "		<tr><td class=format><b>Циферблат:</b> $cifer</td></tr>" if($cifer);
	print "		<tr><td class=format><b>Браслет:</b> $braslet</td></tr>" if($braslet);
	print "		<tr><td class=format><br><span style='border-bottom:1px dashed gray;'>Товара временно нет в наличии</span></td></tr>" if($sklad == 0);
	}
		
	print "		<tr><td height=20></td></tr>";
	print "		<tr><td class=zag>СТОИМОСТЬ:</td></tr>";
	print "		<tr><td class=format align=left style='padding-top:5px;'><span style='font-size:20px;'>$price руб.</span><br><img src='/img/dot.gif' width=1 height=5><br><a href='/pay/&id=$id' style='display:block; text-align:center; padding:12px 0px; color:#EA1414; font-size:12px;'><img src='/img/pay.gif' width=13 height=11 border=0 style='margin-top:-2px; margin-right:3px;' align=absmiddle><b>КУПИТЬ</b></a></td></tr>" if(!$price2);
	print "		<tr><td class=format align=left style='padding-top:5px;'><span style='font-size:20px;'><s style='color:#dddddd;'>$price руб.</s><br>Всего: $price2 руб.</span><br><img src='/img/dot.gif' width=1 height=5><br><a href='/pay/&id=$id' style='display:block; text-align:center; padding:12px 0px; color:#EA1414; font-size:12px;'><img src='/img/pay.gif' width=13 height=11 border=0 style='margin-top:-2px; margin-right:3px;' align=absmiddle><b>КУПИТЬ</b></a></td></tr>" if($price2);
	print "	</table>";
	print "	</td>";
	print "</tr>";

	print "<tr><td height=5></td></tr>";
	print "</table>";
	}
	
	



###########################################################################################################
sub search_engine {
my(@id, @words, $fromcatalog, $value, $rows);
my($table, $rows, $text) = @_;
undef @id;


# поиск по столбцам
if($rows eq 1) { $rows= "param, describ"; }
elsif($rows eq 2) { $rows= "art"; }


@rows = split(", ", $rows);

$text = &lc($text);
@words = split (/ /, $text);

my $sth = $dbh->prepare("SELECT id, category, $rows FROM $table");
$sth->execute;

	while (my @val = $sth->fetchrow_array) {
		if(!$dbh->selectrow_array ("SELECT COUNT(*) FROM category_close WHERE name=?", undef, $val[1])) {
	
			for($i=0; $i<=$#rows;$i++) {
				$val[$i+2] = &clear($val[$i+2], 1);
				$val[$i+2] = &lc($val[$i+2]);
				$fromcatalog .= " " . $val[$i+2];
				$fromcatalog =~ s/<[A-za-z]([^'">]*['"][^'"]*?['"])*[^>]*>//sig; #убийство тегов
				}
		
			if ($fromcatalog =~ $text) {
				push(@id, $val[0]);
				$flag=1;
				}

			if(!$flag) {
			for(@words) {  
				if ($fromcatalog =~ $_) {
					push(@id, $val[0]);
					last;
					}
				}
			}
		undef $fromcatalog;
		}
		}
$sth->finish;


for(@id) {
	$value .= " or id='$_'";
	}

if($value)	{
	$value = "and (" . substr($value, 4) . ")";
	}
	else {
		$value = "and id=0";
		}	
	
return $value;
}









###########################################################################################################
sub caser {
my $do = $cgi->param('do');
my $id = $cgi->param('id');


	if($do eq 'delete') {
		$dbh->do("DELETE FROM caser WHERE session=? and id=?", undef, $session, $id);
		&go("/caser");
		}
		elsif($do eq 'change') {
			$dbh->do("UPDATE caser SET size=? WHERE session=? and cid=?", undef, param('size'), $session, $id);
			&go("/caser");
			}
		
		
	$all = $dbh->selectrow_array ("SELECT COUNT(*) FROM caser WHERE session=?", undef, $session);





	print "<table cellpadding=0 cellspacing=0 width=100%>";
	print "<tr><td height=29 class=zag style='background:#5392C6;' colspan=50><img src='/img/zag.gif' width=8 height=9 style='margin-right:5px;'> КОРЗИНА ТОВАРОВ, ДОБАВЛЕНО: $all</td></tr>";
	print "<tr><td height=5></td></tr>";
	print "<tr>";


	undef $sum, $price;
	print "<table cellpadding=0 cellspacing=0 width=100%>";
	my $sth = $dbh->prepare ("SELECT caser.id, caser.cid, caser.size, catalog.category, catalog.subcategory, catalog.name, catalog.model, catalog.describ, catalog.sex, catalog.price, catalog.price2 FROM caser, catalog WHERE session=? and catalog.id=caser.cid");
	$sth->execute($session);
		while (my @val = $sth->fetchrow_array()) {
	
			$price = $val[9] * $val[2] if(!$val[10]);
			$price = $val[10] * $val[2] if($val[10]);
			$sum+= $price;
			$image = &get_image($val[1], undef, "s");
			$image = "<a href='/show/&id=$val[1]'><img src='$image' alt='- $val[5] $val[6]' border=0></a>";

			print "<tr>";
			print "	<td>";
			print "		<table cellpadding=0 cellspacing=0 width=100%>";
			print "			<tr>";
			print "				<td width=10></td>";
			print "				<td>";
			
			print "					<table cellpadding=0 cellspacing=0 width=100%>";
			print "						<tr><td height=15></td></tr>";

			print "						<tr>";
			print "							<td>$image</td>";
			print "							<td width=5><img src='/img/dot.gif' width=5 height=1></td>";
			print "							<td width=100% valign=top>";

			print "								<table cellpadding=3 cellspacing=0 width=100%>";

			print "									<tr>";
			print "										<td width=100%>";
			print "											<span style='font-size:11px; font-weight:bold; color:#2374B2; font-family:tahoma;'>$val[3] &mdash; $val[4]</span>";
			print "											<span style='font-size:11px; font-weight:bold; color:#939393;'>|</span> <span style='font-size:11px; font-weight:bold; color:#BC2B29; font-family:tahoma;'>$val[5] $val[6]</span><br><span style='color:#444444; font-family:tahoma; font-size:11px;'><u>$val[8]</u>";
			print "											</span>";
			print "										</td>";
			print "										<td width=3><img src='/img/dot.gif' width=5 height=1></td>";
			print "										<td class=text style='color:black;'><b>кол-во</b></td>";
			print "										<td width=3><img src='/img/dot.gif' width=5 height=1></td>";
			print "										<td class=text style='color:black;'><b>убрать</b></td>";
			print "										<td width=3><img src='/img/dot.gif' width=5 height=1></td>";
			print "										<td class=text style='color:black;'><b>цена</b></td>";
			print "									</tr>";

			print "									<tr><td height=3></td></tr>";
			print "									<tr><td colspan=7 height=1 background='/img/bg.gif'><img src='/img/dot.gif' width=1 height=1></td></tr>";
			print "									<tr><td height=3></td></tr>";
			print "									<tr>";
			print "										<td style='color: #444444; font-family:tahoma; font-size:11px;'><br>$val[7]";
#			print "											<br><span style='font-size:11; font-weight:bold; color:#BC2B29; font-family:tahoma;'>Скидка на товар!</span>";
			print "										</td>";

			print "										<td width=3><img src='/img/dot.gif' width=5 height=1></td>";

			print "										<form action='$cgidir/main.pl' method=get name=calc$val[0]>";
			print "										<td align=left>";

			print "											<table cellpadding=0 cellspacing=0>";
			print "												<tr>";
			print "													<td><input type=text name=size value=$val[2] style='width:25px; font-size:10px;'></td>";
			print "													<td>";
			print "														<table cellpadding=0 cellspacing=0>";
			print "															<tr><td><a href='' onClick='return false;' onFocus='this.blur(); return false;'  onMouseOut='incstop(1,0, \"calc$val[0]\"); return false;' onMouseUp='incstop(1, 0, \"calc$val[0]\"); return false;' onMouseDown='incstart(1,0); return false;'><img name='arrup0' src='/img/arr_up_1.gif' width='8' height='8' border='0' alt='+1'></a></td></tr>";
			print "															<tr><td height=1></td></tr>";
			print "															<tr><td><a href='' onClick='return false;' onFocus='this.blur(); return false;'  onMouseOut='incstop(-1,0, \"calc$val[0]\"); return false;' onMouseUp='incstop(-1, 0, \"calc$val[0]\"); return false;' onMouseDown='incstart(-1,0); return false;'><img name='arrdown0' src='/img/arr_down_1.gif' width='8' height='8' border='0' alt='-1'></a></td></tr>";
			print "														</table>";
			print "													</td>";
			print "													<td>&nbsp;<input type=submit value='пересчитать' class=text style='color:black; cursor:pointer;'></td>";
			print "													<input type=hidden name=act value=$act>";
			print "													<input type=hidden name=do value=change>";
			print "													<input type=hidden name=id value='$val[1]'>";
			print "												</tr>";
			print "											</table>";
			print "										</td>";
			print "										</form>";

			print "										<td width=3><img src='/img/dot.gif' width=5 height=1></td>";
			print "										<td class=text style='color:black;' align=center bgcolor=#F0F4F0><a href='/caser/&do=delete&id=$val[0]'><img src='/img/admin/del.gif' border=0></a></td>";
			print "										<td width=3><img src='/img/dot.gif' width=5 height=1></td>";
			print "										<td class=text style='color:black;'><nobr>$price руб.</nobr></td>";
			print "									</tr>";
			print "									<tr><td height=3></td></tr>";
			print "									<tr><td colspan=7 height=1 background='/img/bg.gif'><img src='/img/dot.gif' width=1 height=1></td></tr>";
			print "									<tr><td height=3></td></tr>";
			print "								</table>";
			
			print "							</td>";
			print "						</tr>";

			print "						<tr><td height=15></td></tr>";
			print "						<tr><td height=1 bgcolor=#c3c3c3 colspan=3></td></tr>";
			print "					</table>";

			print "				</td>";
			print "				<td width=10></td>";
			print "			</tr>";
			print "		</table>";
			print "	</td>";
			print "</tr>";
			}
	$sth->finish;


	if($all) {
		print "<tr><td align=right class=text style='padding: 10px 10px 0px 10px; font-weight: bold; font-size:16px; font-family: Trebuchet MS, Verdana, Arial, Helvetica, sans-serif; color:#2374B2;'>Итого к оплате: <b>$sum руб.</b></td></tr>";
		print "<tr><td height=5></td></tr>";
		print "<tr><td align=right style='padding:0px 10px 10px 10px;'><input type=submit value='Оформить заказ' class=text style='color:black; font-size:12px; width:150px; height:30px; font-weight:bold; cursor:pointer;' onClick=\"document.location.href='/order/'\"></td></tr>";
		}
		else {
			print "	<tr><td style='border: 1px solid #dadada; padding:15px;' class=format><div align=center>Ваша корзина пуста. Добавьте товар из каталога.</div></td></tr>";
			}



	print "</tr>";
	print "</table>";

	}






	
	
sub order {
	my $error = $cgi->param('error');
	
	$all = $dbh->selectrow_array ("SELECT COUNT(*) FROM caser WHERE session=?", undef, $session);
	print "<table cellpadding=0 cellspacing=0 width=100%>";
	print "<tr><td height=29 class=zag style='background:#5392C6;' colspan=50><img src='/img/zag.gif' width=8 height=9 style='margin-right:5px;'> ОФОРМЛЕНИЕ ЗАКАЗА НА ПОКУПКУ</td></tr>";
	print "<tr><td height=5></td></tr>";


	if($error eq 1) {
		print "	<tr><td height=5></td></tr>";
		print "	<tr><td colspan=2 class=text style='color:red; padding-left:10px;'>Ошибка, проверьте правильность заполнения полей.</td></tr>";
		}
#		elsif($error eq 2) {
#			print "	<tr><td height=5></td></tr>";
#			print "	<tr><td colspan=2 class=text style='color:red; padding-left:10;'>Ошибка, пользователь с таким e-mail уже существует.<br>Чтобы сделать заказ \"<a href='/enter/' style='color:red;'>авторизуйтесь</a>\"</td></tr>";
#			}
	
	
	
	if($all) {

	print "<tr><td style='padding:10px;' valign=top>";
	print "<table cellpadding=4 cellspacing=1 width=100% bgcolor=#5392C6>";
	print "	<tr><td height=24 colspan=3 background='/img/bg_goods.gif' class=text style='font-size:10px; color:white;' align=left>&nbsp;<b>СПИСОК ЗАКАЗАНОЙ ПРОДУКЦИИ</b></td></tr>";
	
	my $sth = $dbh->prepare ("SELECT caser.id, caser.cid, caser.size, catalog.category, catalog.subcategory, catalog.name, catalog.model, catalog.describ, catalog.sex, catalog.price, catalog.price2 FROM caser, catalog WHERE session=? and caser.cid=catalog.id");
	$sth->execute($session);
		while (my @val = $sth->fetchrow_array()) {


			$image = "http://" . $domain . &get_image($val[1], undef, "s");
			$image = "<a href='http://$domain/show/&id=$val[1]'><img src='$image' alt='$val[3] $val[4] &mdash; $val[5] $val[6]' width=117 border=0></a>";
			$price = $val[9] * $val[2] if(!$val[10]);
			$price = $val[10] * $val[2] if($val[10]);
			$sum+= $price;
		
			$out = qq(
			<tr class=text style='color:black; font-size:11px;'>
			<td bgcolor='#ffffff' width=1>$image</td>
			<td bgcolor='#ffffff'>$val[3] $val[4] &mdash; $val[5] $val[6]<br><u>$val[8]</u></td>
			<td bgcolor='#ffffff'>$val[2] шт.</td>
			<td bgcolor='#ffffff' width=75 align=center><nobr>$price руб.</nobr><br><img src='/img/dot.gif' width=75 height=1></td>
			</tr>
			);			
			
		
			print $out;
			$order .= $out;
			}
	$sth->finish;
	print "</table>";

	
	print "<table cellpadding=4 cellspacing=1 width=100%>";
	print "<tr class=text style='color:black; font-size:11px;'>";
	print "	<td colspan=2 align=right><b>Итоговая стоимость:</b></td>";
	print "	<td bgcolor='#ffffff' width=75 align=center><nobr><b>$sum руб.</b></nobr><br><img src='/img/dot.gif' width=75 height=1></td>";
	print "</tr>";
	print "	<tr><td height=20></td></tr>";
	print "</table>";



	

	print "<form action='$cgidir/main.pl' method=post name=order>";
	print "<input type=hidden name=act value=order_generate>";
	print "<input type=hidden name=sum value='$sum'>";
	print "<input type=hidden name=order value=\"$order\">";



	# форма оплаты
	print "<table cellpadding=0 cellspacing=0 width=100% class=text style='color:black; font-size:11px;'>";
	print "	<tr><td height=24 bgcolor=#5392C6 colspan=3 background='/img/bg_goods.gif' class=text style='padding-left:10px; font-size:10px; color:white;' align=left><b>ФОРМА ОПЛАТЫ</b></td></tr>";

	$num=1;
	$sth = $dbh->prepare ("SELECT text FROM pay WHERE visible=1 ORDER BY sort");
	$sth->execute;
	while (@val = $sth->fetchrow_array()) {
		print "	<tr><td style='padding-left:10px;'><input type=radio name=pay value=\"$val[0]\""; print " checked" if($num eq 1); print ">$val[0]</td></tr>";
		$num++;
		}
	$sth->finish;

	print "	<tr><td height=40></td></tr>";
	print "</table>";
	###################

	

	# тип доставки
	print "<table cellpadding=0 cellspacing=0 width=100% class=text style='color:black; font-size:11px;'>";
	print "	<tr><td height=24 bgcolor=#5392C6 colspan=3 background='/img/bg_goods.gif' class=text style='padding-left:10px; font-size:10px; color:white;' align=left><b>ТИП ДОСТАВКИ</b></td></tr>";

	$num=1;
	$sth = $dbh->prepare ("SELECT text FROM delivery WHERE visible=1 ORDER BY sort");
	$sth->execute;
	while (@val = $sth->fetchrow_array()) {
		print "	<tr><td style='padding-left:10px;'><input type=radio name=delivery value=\"$val[0]\""; print " checked" if($num eq 1); print ">$val[0]</td></tr>";
		$num++;
		}
	$sth->finish;

	print "	<tr><td height=40></td></tr>";
	print "</table>";
	###################




	# контактные данные
	print "<table cellpadding=3 cellspacing=0 width=100% class=text style='color:black;'>";
	print "	<tr><td height=24 bgcolor=#5392C6 colspan=3 background='/img/bg_goods.gif' class=text style='padding-left:10px; font-size:10px; color:white;' align=left><b>КОНТАКТНЫЕ ДАННЫЕ</b></td></tr>";
	print "	<tr><td height=3 colspan=3></td></tr>";

	print "			<tr>";
	print "				<td class=text style='padding-left:12px; color:black; font-size:11px;' width=1><nobr><b>Введите Ваше Имя: </b></nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=name value='$name' class=login style='height:22px; width:360px;'></td>";
	print "			</tr>";
	print "			<tr>";
	print "				<td class=text style='padding-left:12px; color:black; font-size:11px;' width=1><nobr>Телефон с кодом города: <span style='color:red'>(*)</span></nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=phone value='$phone' class=login style='height:22px; width:360px;'></td>";
	print "			</tr>";
	print "			<tr>";
	print "				<td class=text style='padding-left:12px; color:black; font-size:11px;' width=1><nobr>E-mail: <span style='color:red'>(*)</span></nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=mail value='$mail' class=login style='height:22px; width:360px;'></td>";
	print "			</tr>";



	print "			<tr>";
	print "				<td class=text style='padding-left:12px; color:black; font-size:11px;' width=1><nobr>Страна: </nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=country value='$country' class=login style='height:22px; width:360px;'></td>";
	print "			</tr>";
	print "			<tr>";
	print "				<td class=text style='padding-left:12px; color:black; font-size:11px;' width=1><nobr>Город: </nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=city value='$city' class=login style='height:22px; width:360px;'></td>";
	print "			</tr>";
	print "			<tr>";
	print "				<td class=text style='padding-left:12px; color:black; font-size:11px;' width=1><nobr>Индекс: </nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=postindex value='$postindex' class=login style='height:22px; width:360px;'></td>";
	print "			</tr>";
	print "			<tr>";
	print "				<td class=text style='padding-left:12px; color:black; font-size:11px;' width=1><nobr>Адрес: </nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=addr value='$addr' class=login style='height:22px; width:360px;'></td>";
	print "			</tr>";
	print "			<tr>";
	print "				<td class=text style='padding-left:12px; color:black; font-size:11px;' width=1><nobr>Желаемое время доставки: </nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=delivery_time value='$delivery_time' class=login style='height:22px; width:360px;'></td>";
	print "			</tr>";
	print "			<tr>";
	print "				<td class=text style='padding-left:12px; color:black; font-size:11px;' width=1><nobr>Комментарий по доставке: </nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=dop value='$dop' class=login style='height:22px; width:360px;'></td>";
	print "			</tr>";
	print "			<tr>";
	print "				<td class=text style='text-align:right;' width=1><input type='checkbox' name=subscribe value='Да' checked></td>";
	print "				<td class=text style='color:black;' width=100%>Подписаться на ежемесячную рассылку здоровья<br />(статьи об оздоровлении организма, информация о скидках)</td>";
	print "			</tr>";

	print "	<tr><td height=15></td></tr>";
	print "<tr><td width=100% colspan=2 height=1 bgcolor=#dadada></td><tr>";
	print "</table>";

	print "	</td></tr>";
	print "<tr><td height=5></td></tr>";
	print "<tr><td align=right style='padding:0px 10px 10px 10px;'><input type=submit value='Сделать Заказ!' class=text style='color:black; font-size:12px; width:150px; height:30px; font-weight:bold; cursor:pointer;' onClick=\"javascript: if(!document.order.phone.value || !document.order.mail.value) { alert('Заполните КОНТАКТНЫЕ ДАННЫЕ'); return false; }\"></td></tr>";
	}
	else {
		print "	<tr><td style='border:1px solid #dadada; padding:15px;' class=format><div align=center>Ваша корзина пуста. Добавьте товар из каталога.</div></td></tr>";
		}

	print "</form>";
	print "<tr><td height=100%></td><tr>";
	print "</table>";
	}
	
	
	
	
	

###########################################################################################################################################
###########################################################################################################################################
sub order_generate {

my $sum = $cgi->param('sum');
my $order = $cgi->param('order');
my $pay = $cgi->param('pay');
my $delivery = $cgi->param('delivery');
my $org = $cgi->param('org');
my $name = $cgi->param('name');
my $addr = $cgi->param('addr');
my $phone = $cgi->param('phone');
my $dop = $cgi->param('dop');
my $mail = $cgi->param('mail');
my $country = $cgi->param('country');
my $city = $cgi->param('city');
my $postindex = $cgi->param('postindex');
my $delivery_time = $cgi->param('delivery_time');
my $subscribe = $cgi->param('subscribe') || "Нет";

my $all = $dbh->selectrow_array ("SELECT COUNT(*) FROM caser WHERE session=?", undef, $session);
if(!$name || !$phone || !$mail) { &go("/order/&name=$name&phone=$phone&dop=$dop&error=1"); }



$num_zak = $dbh->selectrow_array ("SELECT value FROM setup WHERE name='num_zak'");
$dbh->do("UPDATE setup SET value=value+1 WHERE name='num_zak'");



$n = "<br>\n";
### формируем body -----------------------------------------------------------------------------------------------------------
$body = "<html><body>";
$body .= "<table cellpadding=2 cellspacing=0 style='padding-top:30px; font-family: tahoma; font-size:11px;'>";

$body .= "<tr><td><b>ЗАКАЗ: №</b></td><td width=10></td><td>$num_zak</td></tr>";
$body .= "<tr><td>ФОРМА ОПЛАТЫ:</td><td width=10></td><td>$pay</td></tr>";
$body .= "<tr><td>ТИП ДОСТАВКИ:</td><td width=10></td><td>$delivery</td></tr>";

$body .= "<tr><td>Контактное лицо:</td><td width=10></td><td>$name</td></tr>";
$body .= "<tr><td>Телефон:</td><td width=10></td><td>$phone</td></tr>";
$body .= "<tr><td>E-mail:</td><td width=10></td><td>$mail</td></tr>";

$body .= "<tr><td>Время доставки:</td><td width=10></td><td>$delivery_time</td></tr>" if($delivery_time);
$body .= "<tr><td>Индекс:</td><td width=10></td><td>$postindex</td></tr>" if($postindex);
$body .= "<tr><td>Страна:</td><td width=10></td><td>$country</td></tr>" if($country);
$body .= "<tr><td>Город:</td><td width=10></td><td>$city</td></tr>" if($city);
$body .= "<tr><td>Адрес доставки:</td><td width=10></td><td>$addr</td></tr>" if($addr);
$body .= "<tr><td>Доп. информация:</td><td width=10></td><td>$dop</td></tr>" if($dop);
$body .= "<tr><td>Подписка на рассылку:</td><td width=10></td><td>$subscribe</td></tr>";
$body .= "<tr><td>Всего к оплате:</td><td width=10></td><td>$sum руб.</td></tr>";
$body .= "</table>";

$body .= "<table cellpadding=0 cellspacing=0 style='padding-top:30px; font-family: tahoma; font-size:10px;'><tr><td colspan=4><b>ПЕРЕЧЕНЬ ЗАКАЗА:</b></td></tr>" . $order . "</table>";
$body .= "</body></html>";
### --------------------------------------------------------------------------------------------------------------------------

$mail_manager = $dbh->selectrow_array ("SELECT mail FROM delivery WHERE text=?", undef, $delivery);

# пишем администратору, менеджеру и клиенту ----------------------------------------------------------------
if($mailer) { 			&send_html ("Интернет-магазин <$mailer>", $mailer, "Заказ №$num_zak с сайта http://$domain", $body); }
if($mailer2) { 			&send_html ("Интернет-магазин <$mailer>", $mailer2, "Заказ №$num_zak с сайта http://$domain", $body); }
if($mail_manager) {		&send_html ("Интернет-магазин <$mailer>", $mail_manager, "Заказ №$num_zak с сайта http://$domain", $body); }
if(&TrueMail($mail)) {	&send_html ("Интернет-магазин <$mailer>", $mail, "Заказ №$num_zak с сайта http://$domain", $body); }
### --------------------------------------------------------------------------------------------------------

# удаляем ненужные данные ---------------------------------------------------------------------------------------
$dbh->do("DELETE FROM caser WHERE session=?", undef, $session);
### --------------------------------------------------------------------------------------------------------

$num_zak = $num_zak . "-" .int(rand(12));
&go("/accept/&zakaz=$num_zak");
}








###########################################################################################################################################
###########################################################################################################################################
sub title {
my($sth, $row);


	if(($act eq 'show' && param('id')) || ($act eq 'catalog' && !param('subcategory'))) {
		$sth = $dbh->prepare ("SELECT category, subcategory, name, model FROM catalog where id=?");
		$sth->execute(param('id'));
		$row = $sth->fetchrow_hashref;
		my $category = $row->{category};
		my $subcategory = $row->{subcategory};
		my $name = $row->{name};
		my $model = $row->{model};
		$sth->finish;

		$title2 .= "$category $subcategory &mdash; $model";
		if($act ne 'catalog') {
			$title = $title2;
			}
		}
		elsif($act eq 'catalog' && param('subcategory')) {

			$sth = $dbh->prepare ("SELECT category, subcategory FROM catalog where translator=?");
			$sth->execute(param('subcategory'));
			$row = $sth->fetchrow_hashref;
			my $category = $row->{category};
			my $subcategory = $row->{subcategory};
			$sth->finish;

			$title = "$category $subcategory &mdash; http://$domain/catalog/". param('subcategory') . "/";
			}
			else {
				my($id) = $cgi->param('id');
				$id = &translator if(!$id);
	
				($title2, $describ2, $keywords2) = $dbh->selectrow_array ("SELECT title, describ, keywords FROM content WHERE id=?", undef, $id);
				$title = $title2 if($title2);
				$describ = $describ2 if($describ2);
				$keywords = $keywords2 if($keywords2);
				}
		

print "<head>\n";
print "	<title>$title</title>\n";
print "	<meta name=description content=\"$describ\">\n";
print "	<meta name=keywords content=\"$keywords\">\n";
print " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1251\">\n";
print "</head>";
}






###########################################################################################################################################
###########################################################################################################################################
sub top_text {
my $text = &text("7");

if($text) {
	print $text;
	}

}
					


###########################################################################################################################################
###########################################################################################################################################
sub top_text_describ {
my $text = &text("8");

if($text) {
	print "<table cellpadding=0 cellspacing=0 width=100%>";
	print "	<tr>";
	print "		<td style='border:1px solid #dadada; padding:15px;' class=text>$text</td>";
	print "	</tr>";
	print "</table>";
	print "<table cellpadding=0 cellspacing=0><tr><td height=10></td></tr></table>";
	}

}








###########################################################################################################################################
###########################################################################################################################################
sub catalog_list {
my($id, $categoryName, $sth, $sth2, $category, $subcategory);

my $category = $cgi->param('category');
my $subcategory = $cgi->param('subcategory');


if($dbh->selectrow_array ("SELECT COUNT(*) FROM catalog")) {
	print "<table cellpadding=0 cellspacing=0 width=100%>";
	print "<tr><td height=29 class=zag><img src='/img/zag.gif' width=8 height=9 style='margin-right:5px;'> КАТАЛОГ ТОВАРОВ</td></tr>";
	print "<tr><td height=3 bgcolor='#ECECEB'></td></tr>";
	print "<tr>";
	print "	<td style='border-right:1px solid #dadada; border-bottom:1px solid #dadada; border-left:1px solid #dadada; padding-top:10px; padding-bottom:20px;'>";

	print "<table cellpadding=0 cellspacing=0 width=100%>";

	
		
	$sth = $dbh->prepare("SELECT id, category, translator FROM catalog GROUP BY category DESC");
	$sth->execute;
	while (my @box = $sth->fetchrow_array) {
		$num_sub = &num_subcategory($box[1]);
	
		$link = "/catalog/&category=$box[0]";
	

		if($category eq $box[0]) { $red = " style='color:red; text-decoration: underline;'"; }
			else { undef $red; }

	
		print "<tr>";
		print "	<td width=20></td>";
		print "	<td width=17><img src='/img/arrow_black.gif' width=5 height=7></td>";
		print "	<td colspan=2><a href='$link' class=category $red>", &uc($box[1]) ,"</a></td>";
		print "	<td width=10></td>";
		print "</tr><tr><td height=3></td></tr>";
	

		if($num_sub) {
			$sth2 = $dbh->prepare("SELECT id, subcategory, translator FROM catalog WHERE category=? GROUP BY subcategory ORDER BY subcategory");
			$sth2->execute($box[1]);
			while (my @box2 = $sth2->fetchrow_array) {

				if($subcategory eq $box2[2]) { $red = " style='color:red; text-decoration: underline;'"; }
					else { undef $red; }

				print "<tr><td width=20></td><td width=17></td><td width=14><img src='/img/arrow_gray.gif' width=5 height=7></td><td><a href='/catalog/$box2[2]/' class=subcategory $red>$box2[1]</a></td><td width=10></td></tr><tr><td height=1></td></tr>";
				}
			}
				

		if($num_sub) { print "<tr><td height=15></td></tr><tr><td colspan=5><hr noshade color=#ECECEB width=90% size=1></td></tr><tr><td height=15></td></tr>"; }
		}
	$sth->finish;


	print "</table>";
	print "	</td>";
	print "</tr>";
	print "</table>";
	print "<table cellpadding=0 cellspacing=0><tr><td height=10></td></tr></table>";


	# поисковая форма
	&call_form;
	}
	

	}



	

###########################################################################################################################################
###########################################################################################################################################
sub text_list {


if($dbh->selectrow_array ("SELECT COUNT(*) FROM content")) {
	print "<table cellpadding=0 cellspacing=0 width=100%>";
	print "<tr><td height=29 class=zag><img src='/img/zag.gif' width=8 height=9 style='margin-right:5px;'> ИНТЕРНЕТ МАГАЗИН </td></tr>";
	print "<tr><td height=3 bgcolor='#ECECEB'></td></tr>";
	print "<tr>";
	print "	<td style='border-right:1px solid #dadada;  border-bottom:1px solid #dadada; border-left:1px solid #dadada; padding-top:10px; padding-bottom:10px;'>";

	print "<table cellpadding=0 cellspacing=0 width=100%>";

	
	$sth = $dbh->prepare("SELECT id, category, translator FROM content WHERE id2=1 and visible=1 ORDER BY sort");
	$sth->execute;
	while (my @box = $sth->fetchrow_array) {

		if($box[2]) { $link = "/$box[2]"; }
			else { $link = "/text/&id=$box[0]"; }
				
	
		if($act && ($act eq $box[2] || ($act eq 'text' && param('id') eq $box[0]))) { $red = " style='color:red; text-decoration: underline;'"; }
			else { undef $red; }

		print "<tr>";
		print "	<td width=20></td>";
		print "	<td width=17><img src='/img/arrow_black.gif' width=5 height=7></td>";
		print "	<td colspan=2><a href='$link' class=category $red>", &uc($box[1]) ,"</a></td>";
		print "	<td width=10></td>";
		print "</tr><tr><td height=3></td></tr>";
		}
	$sth->finish;


	print "</table>";
	print "	</td>";
	print "</tr>";
	print "</table>";
	print "<table cellpadding=0 cellspacing=0><tr><td height=10></td></tr></table>";
	}
	

	}
	
	
	
	
	
	

	
sub num_subcategory {
my($num);

	my $sth = $dbh->prepare("SELECT id, translator FROM catalog WHERE category=?");
	$sth->execute($_[0]);
	while (my @box = $sth->fetchrow_array) {

		if(!$flag) {
			$num = $box[1];
			$flag =1;
			}
			else {
				if($num eq $box[1]) { return 1; }
				}


		}

		
	return 0;
	}	
	

	
	
	
###########################################################################################################################################
###########################################################################################################################################
sub call_form {
	print "<table cellpadding=0 cellspacing=0 width=100%>";
	print "	<tr><td height=29 class=zag><img src='/img/zag.gif' width=8 height=9 style='margin-right:5px;'> ЗАКАЗ ОБРАТНОГО ЗВОНКА</td></tr>";
	print "	<tr><td height=3 bgcolor='#ECECEB'></td></tr>";
	print "	<tr><td bgcolor=#ECECEB style='border-right:1px solid #dadada; border-bottom:1px solid #dadada; border-left:1px solid #dadada; padding:7px; font-size:14px; font-family:tahoma; color:#4874B2;' align=center>Мы перезвоним Вам сами<br>в течении 30 минут,<br>где бы Вы не находились!<br><br><input type='button' value='ЗАКАЗАТЬ ОБРАТНЫЙ ЗВОНОК' onclick=\"location.href='/call';\" style='font-size:11px; width:200px;'></td></tr>";
	print "</table>";
	}



										

	

###########################################################################################################################################
###########################################################################################################################################
sub registration {

	my $org = $cgi->param('org');
	my $name = $cgi->param('name');
	my $addr = $cgi->param('addr');
	my $dop = $cgi->param('dop');
	my $mail = $cgi->param('mail');
	my $login = $cgi->param('login');
	my $error = $cgi->param('error');


	print "<table cellpadding=0 cellspacing=0 width=100% height=100%>";
	print "	<tr><td width=415 align=center style='color:black; padding:10px;'>";
	
	print "		<table cellpadding=0 cellspacing=1>";
	print "		<form action='$cgidir/main.pl' method=post>";
	print "		<input type=hidden name=act value=registration_user>";

	print "			<tr><td colspan=2><h2 style='color:#5D6B92;'>Зарегистрируйтесь на Нашем сайте и Вы сможете купить продукцию.</h2></td></tr>";

					

	print "			<tr><td colspan=2 class=text style='font-size:12px; color:red;'>Ошибка, проверьте правильность заполнения полей.</td></tr>" if($error eq 1);
	print "			<tr><td colspan=2 class=text style='font-size:12px; color:red;'>Ошибка, пользователь уже существует. Если Вы забыли пароль обратитесь к администратору.</td></tr>" if($error eq 2);
	print "			<tr><td colspan=2 height=10></td></tr>";
		
	print "			<tr>";
	print "				<td class=text style='font-size:11px; color:black;' width=1><nobr>Организация:&nbsp;<nobr></td>";
	print "				<td style='color:black;' width=100%><input type=text name=org value='$org' class=login style='width:300px; height:21px;'></td>";
	print "			</tr>";
	print "			<tr><td></td><td height=20 valign=top class=text style='color:#676767;' width=100%>(если есть)</td></tr>";

	print "			<tr>";
	print "				<td class=text style='font-size:11px; color:black;' width=1><nobr><b>Контактное лицо <b>(<font color=red>*</font>)</b>:</b>&nbsp;</nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=name value='$name' class=login style='width:300px; height:21px;'></td>";
	print "			</tr>";
	print "			<tr><td></td><td height=20 valign=top class=text style='color:#676767;' width=100%>(Ф.И.О.)</td></tr>";

	print "			<tr>";
	print "				<td class=text style='font-size:11; color:black;' width=1><nobr>Адрес, телефон <b>(<font color=red>*</font>)</b>:&nbsp;</nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=addr value='$addr' class=login style='width:300px; height:21px;'></td>";
	print "			</tr>";
	print "			<tr><td></td><td height=20 valign=top class=text style='color:#676767;' width=100%>(точный адрес доставки и контактный телефон)</td></tr>";
	
	print "			<tr>";
	print "				<td class=text style='font-size:11px; color:black;' width=1><nobr>Доп, информация:&nbsp;</nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=dop value='$dop' class=login style='width:300px; height:21px;'></td>";
	print "			</tr>";
	print "			<tr><td></td><td height=20 valign=top class=text style='color:#676767;' width=100%>(код домофона, удобное время доставки и прочее...)</td></tr>";


	print "			<tr>";
	print "				<td class=text style='font-size:11px; color:black;' width=1><nobr>E-mail:&nbsp;</nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=mail value='$mail' class=login style='width:200px; height:21px;'></td>";
	print "			</tr>";

	print "			<tr>";
	print "				<td class=text style='font-size:11px; color:black;' width=1><nobr>Логин <b>(<font color=red>*</font>)</b>:&nbsp;</nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=text name=login value='$login' class=login style='width:200px; height:21px;'></td>";
	print "			</tr>";

	print "			<tr>";
	print "				<td class=text style='font-size:11px; color:black;' width=1><nobr>Пароль <b>(<font color=red>*</font>)</b>:&nbsp;</nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=password name=pass class=login style='width:200px; height:21px;'></td>";
	print "			</tr>";
	
	print "			<tr>";
	print "				<td class=text style='font-size:11px; color:black;' width=1><nobr>Повтор пароля <b>(<font color=red>*</font>)</b>:&nbsp;</nobr></td>";
	print "				<td class=text style='color:black;' width=100%><input type=password name=pass2 class=login style='width:200px; height:21px;'></td>";
	print "			</tr>";

	print "			<tr>";
	print "				<td height=30></td>";
	print "				<td><input type=image src='/img/ok.gif'></td>";
	print "			</tr>";

	print "		</form>";
	print "		</table>";
	
	print "	</td><tr>";
	print "	<tr><td width=100% height=100%></td><tr>";
	print "</table>";
	}


	
	
	


###########################################################################################################################################
###########################################################################################################################################
sub pay {
my $id = $cgi->param('id');
#my $size = 1; #$cgi->param('size');


my $add = $dbh->prepare ("SELECT cid FROM caser WHERE cid=? and session=?");
$add->execute($id, $session);
$row = $add->fetchrow_hashref();
$add->finish;

if(defined $row->{cid}) { 
	$dbh->do("UPDATE caser SET size=size+1 WHERE cid=? and session=?", undef, $id, $session);
	}
	else {
		$dbh->do("INSERT INTO caser (cid, session, size, time) VALUES ('$id', '$session', '1', NOW())");
		}

#&go("$ENV{'HTTP_REFERER'}");
&go("/caser");
}



						
												

###########################################################################################################################################
###########################################################################################################################################
sub text {
my($id) = $_[0];
if(!$id) { $id = $cgi->param('id'); }
if(!$id) { $id = &translator; }

	return $dbh->selectrow_array ("SELECT text FROM content WHERE id=?", undef, $id);
	}


###########################################################################################################################################
###########################################################################################################################################
sub translator {
return $dbh->selectrow_array ("SELECT id FROM content WHERE translator=?", undef, param('act'));
}
	



###########################################################################################################################################
###########################################################################################################################################
sub logo {
$value = $dbh->selectrow_array ("SELECT file FROM logo WHERE type='logo'");
$value =~ s/..\/files/http\:\/\/$domain\/files/g;
print "<td width=227 height=68 style='background-image: url($value); background-repeat: no-repeat; background-position: left;'><a href='/'><img src='/img/dot.gif' width=227 height=68 alt='на главную' border=0></a></td>";
}




###########################################################################################################################################
###########################################################################################################################################
sub background {
$value = $dbh->selectrow_array ("SELECT file FROM logo WHERE type='background'");
$value =~ s/..\/files/http\:\/\/$domain\/files/g;

print qq(
<td width=80% height=68>
<div style="border:2px solid #2374B2; height:64px; text-align:center;"><img src="$value" style="margin:10px 22px 0px 22px;"></div>
</td>
);
}


###########################################################################################################################################
###########################################################################################################################################
sub icons {
print "<table cellpadding=0 cellspacing=0>";
print "	<tr>";
print "		<td><a href='/'><img src='/img/home.gif' width=17 height=18 border=0></a></td>";
print "		<td width=30></td><td><a href='mailto:$mailer'><img src='/img/mail.gif' width=17 height=18 border=0></a></td>";
print "		<td width=30></td>";
print "		<td><a href='/link'><img src='/img/hand.gif' width=17 height=18 border=0></a></td>";
print "	</tr>";
print "</table>";
}




###########################################################################################################################################
###########################################################################################################################################
sub caser_status {
my($sum);

	my $sth = $dbh->prepare ("SELECT caser.size, catalog.price FROM caser, catalog WHERE caser.session=? and catalog.id=caser.cid");
	$sth->execute($session);
	while (my @val = $sth->fetchrow_array) {
		$all+=$val[0];
		$sum+=$val[1]*$val[0];
		}
	$sth->finish;
	$sum = $sum . " руб.";

	if($all) {
		print "<td width=120 height=68 bgcolor=#F0F4F0 style='border:1px solid #d7d8d7; padding-left:9px; cursor:pointer;' title='перейти в корзину' onClick=\"window.open('/caser', '_self');\">";
		print "	<nobr>";
		print "		<span style='font-size:11px; font-family:tahoma;'><b>В корзине товаров:&nbsp;&nbsp;</b></span>";
		print "		<br><img src='/img/dot.gif' width=1 height=2><br>";
		print "		<span style='font-family:verdana; font-size:11px; color:#696969;'><b>$all</b> на сумму:</span><br>";
		print "		<span style='font-family:verdana; font-size:11px; color:#8DC641;'><b>$sum</b></span><br>";
		print "	</nobr>";
		print "</td>";
		}
		else {
			print "<td width=120 height=68 bgcolor=#F0F4F0 style='border:1px solid #d7d8d7; padding-left:9px;' title='корзина пуста, добавьте товар из каталога'>";
			print "		<span style='font-size:11px; font-family:tahoma;'><b>В корзине<br>нет товаров:<br><img src='/img/dot.gif' width=1 height=5><br><a href='/catalog'>перейти в каталог</a></b></span><br><img src='/img/dot.gif' width=120 height=1>";
			print "</td>";
			}


	}
	
	



###########################################################################################################################################
###########################################################################################################################################
sub accept {
my($zakaz) = $cgi->param('zakaz');

	print "<table cellpadding=0 cellspacing=0 width=100%>";
	print "<tr><td height=29 class=zag style='background:#5392C6;' colspan=50><img src='/img/zag.gif' width=8 height=9 style='margin-right:5px;'> ВАШ ЗАКАЗ ПРИНЯТ!</td></tr>";
	print "<tr><td height=5></td></tr>";
	print "	<tr><td style='border:1px solid #dadada; padding:15px;' class=format><div align=center><span style='color:#A50000; font-size:11px; font-family:tahoma; font-weight:bold;'>Ваш заказ №: <u>$zakaz</u></span><br><br>В самое ближайшее время наши менеджеры свяжутся с Вами.<br><a href='/'>на главную страницу</a></div></td></tr>";
	print "</table>";
	}



###########################################################################################################################################
###########################################################################################################################################
sub banner {

if($dbh->selectrow_array ("SELECT COUNT(*) FROM banners WHERE visible='1'")) {
	my $sth = $dbh->prepare ("SELECT id, code FROM banners WHERE visible=1 ORDER BY RAND() LIMIT 1");
	$sth->execute;
	my $row = $sth->fetchrow_hashref;
	my $code = $row->{code};
	my $id = $row->{id};
	$sth->finish;

	if($code) {
#		print "<table cellpadding=0 cellspacing=0><tr><td height=10></td></tr></table>";
#		print "<table cellpadding=0 cellspacing=0 width=100%><tr><td bgcolor=#8DC641 style='border:1px solid #dadada; padding:7px;'><a href='/click/&id=$id' style='font-family:tahoma; font-size:11px; color:white;'>$code</a></td></tr></table>";
		print "<div style='margin-top:10px;'><a href='/click/&id=$id' style='font-family:tahoma; font-size:11px; color:white;'>$code</a></div>";

		$dbh->do("UPDATE banners SET host=host+1 WHERE id=?", undef, $id);
		}

	}
}
	
	

###########################################################################################################################################
###########################################################################################################################################
sub click {
my($id) = $cgi->param('id');
$link = $dbh->selectrow_array ("SELECT link FROM banners WHERE id=?", undef, $id);

	if($link) {
		$dbh->do("UPDATE banners SET hit=hit+1 WHERE id=?", undef, $id);
		&go("$link");
		}
		else {
			&go("$ENV{'HTTP_REFERER'}");
			}
	}




###########################################################################################################################################
###########################################################################################################################################
sub call {

	print "<table cellpadding=0 cellspacing=0 class=text style='margin:15px;'>";
	print "<form name=form action='$cgidir/main.pl' method=post>";
	print "<input type=hidden name=act value=call_send>";
print qq(
<tr>
	<td colspan=2>
Сообщите как Вас зовут и свой номер телефона, и мы обязательно сами перезвоним Вам в течении 30 минут, где бы Вы не находились!<br><br>
Служба "Обратный звонок" работает семь дней в неделю, с 7.30 до 21.30 по московскому времени.<br>
По возможности, пожалуйста, указывайте желаемое время звонка, особенно если часовой пояс в Вашем регионе отличается от московского.<br><br>

<b>Нам будет трудно совершить звонок в следующих случаях:</b><br>
- троекратное получение сигнала «занято» или «недоступен» в течение 15 минут;<br>
- номер, указанный в заявке, не существует или заблокирован;<br><br>

Поля, отмеченные звёздочкой *, являются обязательными для заполнения.
<br><br><br>
	</td>
</tr>


);

	print "	<tr><td>ФАМИЛИЯ И ИМЯ <font color=red>*</font>:</td><td><input type=text name=name value='' class=text style='width:200px;'></td></tr>";
	print "	<tr><td>ТЕЛЕФОН <font color=red>*</font>:</td><td><input type=text name=phone value='' class=text style='width:200px;'></td></tr>";
	print "	<tr><td>ПРИМЕЧАНИЕ:</td><td><textarea name=dop class=text style='width:400px; height:50px; overflow:auto;'></textarea></td></tr>";
	print "	<tr><td></td><td><input type=submit value='отправить' class=text style='cursor:pointer;'></td></tr>";
	print "</form>";

	print "</table>";
	}


	
	
###########################################################################################################################################
###########################################################################################################################################
sub call_send {
my $name = $cgi->param('name');
my $phone = $cgi->param('phone');
my $subject = "Обратный звонок $domain";
my $dop = $cgi->param('dop');


	$n = "<br>";
	### формируем body -----------------------------------------------------------------------------------------------------------
	$text .= "<table cellpadding=2 cellspacing=0 style='padding-top:30px; font-family: tahoma; font-size:11px;'>";

	$text .= "<tr><td>Здравствуйте!</td></tr>";
	$text .= "<tr><td height=10></td></tr>";
	$text .= "<tr><td>Этот вопрос пришел с сайта <a href='http://$domain'>http://$domain</a>, следующего содержания: <br><br><b>Имя:</b> $name<br><b>Телефон:</b> $phone<br><b>Примечание:</b> $dop</td></tr>";
	$text .= "</table>";
	### --------------------------------------------------------------------------------------------------------------------------


	# пишем письмо ---------------------------------------------------------------------------------------------
	&send_html("Интернет-магазин <$mailer>", $mailer, $subject, $text);
	### --------------------------------------------------------------------------------------------------------

	&go("/call_accept");
	}



###########################################################################################################################################
###########################################################################################################################################
sub call_accept {
	print qq(
	<table cellpadding=0 cellspacing=0 class=text>
		<tr><td><h4>Спасибо. Ваша заявка принята.</h4></td></tr>
		<tr><td>Ожидайте пожалуйста звонка.</td></tr>
		<tr><td height=10></td></tr>
		<tr><td style='padding-top:10px;'><a href='/'><b>вернуться на главную</b></a></td></tr>
	</table>
	);
}	
