#!/usr/bin/perl
#
#
#use cPanelUserConfig;
use lib "../../lib";
use lib "/home/www/frontgeo/lib";
#use lib "z:/home/frontgeo_.ru/www/lib";
#use DBI;

$IGVersion = "1.04bl";
$dir = "pattern";
#$RunTime = time;
#$ct_table = "content_tree";
use locale;
use POSIX 'locale_h';
setlocale (LC_ALL, 'ru_RU.CP1251');
use XML::RSS;
use LWP::Simple;
use Encode;
use Data::Dumper;
use Socket;
use CGI;
use prop;
use cust;
use maps;
use publication;
use jobs;
use sbc;
use content;
use nd;
#use price;




($Mode,$Action,$News) = ('cont','','');
@month_array = ("Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь");
@wday_array = ("Воскресенье","Понедельник","Вторник","Среда","Четверг","Пятница","Суббота");

#______________________date_____________________
my ($Cur_mday,$Cur_month,$Cur_year,$Cur_wday)=(localtime)[3,4,5,6];
$Cur_year+=1900;
#______________________date___end_____________________


$query = new CGI;
foreach ($query->param) {$Params{$_} = $query->param($_);}

#______________________BASKET_____________________
#print "Content-Type: text/html; charset=windows-1251\n\n";
#_______GET_BASKET_____________________
my %b_hash;
%b_hash = get_basket();
if ($Params{b_id}){$b_hash{$Params{b_id}}=$Params{b_count};}
#print "<hr>@{[%b_hash]}<hr>";
#сборка значения basket
my $b_str;
my @b_mas = ();
my ($b_id,$b_count)=(0,0);
while (($b_id,$b_count) = each(%b_hash))
  {push @b_mas, "$b_id-$b_count" if $b_count;

  }
$b_str = join('|',@b_mas);
if($Params{action} eq 'order') {basket_request();$b_str='';%b_hash=[];}
print "Content-Type: text/html; charset=windows-1251\n";
print "Set-Cookie: basket=$b_str\n\n";
#print "Set-Cookie: basket=12-2|14-6\n\n";
#print "<hr>$b_str<hr>";
#______________________GET_BASKET_____________________

#______________________BASKET_____________________
if($Params{c_type} eq 'projects'){$Params{c_type} = 'jobs'}
if($Params{c_type} eq 'maps' || $Params{c_type} eq 'map' || $Params{c_type} eq 'jobs' ||
	$Params{c_type} eq 'publication' || $Params{c_type} eq 'sbc' || $Params{c_type} eq 'content' || $Params{c_type} eq 'nd' ){;}
else{$Params{c_type}='cust';}

if (exists($Params{_name})) {$Params{_id}=$Params{c_type}->get_id_by_name($Params{_name});}
$Main_content = get_main_content($Params{_id},$Params{c_type});
unless($Main_content->{_id}){$Main_content->{_id}=$Params{_id};}


if ($Params{c_type} eq 'maps'){$o_file = "maps.html";}
elsif ($Params{c_type} eq 'nd'){
	if($Main_content->{_id} eq '' || $Main_content->{_id} == 0){$o_file = "nd.html";}
	else {$o_file = "nd_detail.html";}
}
elsif ($Params{c_type} eq 'publication'){
	if($Main_content->{_id} eq '' || $Main_content->{_id} == 0){$o_file = "publication.html";}
	else {$o_file = "publication_detail.html";}
}
elsif ($Params{c_type} eq 'content'){
	if($Main_content->{_id} eq '' || $Main_content->{_id} == 0){$o_file = "index.html";}
	elsif($Main_content->{_name} eq 'about'){$o_file = "c_about.html";}
	elsif($Main_content->{_name} eq 'licence'){$o_file = "c_licence.html";}
	elsif($Main_content->{_name} eq 'contacts'){$o_file = "c_contact.html";}
        elsif($Main_content->{_name} eq 'weather'){$o_file = "c_weather.html";}
	else {$o_file = "c_default.html";}
}
elsif ($Params{c_type} eq 'sbc'){$o_file = "sbc.html";}
elsif ($Params{c_type} eq 'jobs'){
	if($Main_content->{_id} eq '' || $Main_content->{_id} == 0){$Main_content = get_main_content(jobs->get_first_root(),'jobs');}
        if($Main_content->{_child}){$Main_content = get_main_content($Main_content->{_child},'jobs');}

        if($Main_content->{_level}){ $o_file = "jobs_detail.html";}
        else {$o_file = "jobs.html";}
}
else {$Params{c_type}='cust';$o_file = "index.html";}
#if (exists($Params{basket}))
#  {$o_file = "basket.html";}
#if ($Params{action} eq 'order')
#  {$o_file = "ok.html";}
#
#
#my $MyChildMasRef=[];
#my $MyWayMasRef=[];
#my %MyWayMasRef_1;
#unless($Main_content->{_id} eq '' || $Main_content->{_id} == 0)
# {
#  $Params{c_type}->get_childs($Main_content->{_id},$MyChildMasRef,1);
#  $Params{c_type}->get_way($Main_content->{_id},$MyWayMasRef,0);
#  foreach (@{$MyWayMasRef})
#   {$MyWayMasRef_1{$_->{_id}}=1;}
# }
my $S_Count=0;
my $Action = $Params{"action"} || "";
if ($Action eq 'search'){$o_file = "search.html";}
elsif ($Action eq 'send'){basket_request();}

#Выводим на экран #substr($row1[3],0,60);
   open(FD,"<$dir/$o_file") || errmsg("Can't open file $dir/$o_file");
#srand();


#srand();
while($line = <FD>)
   {
     if($line =~ /<<&/)
      {unless($line =~ m|<<&/|)
       {
        while($temp = <FD>)
         {$line.=$temp;
         if($temp =~ m|<<&/|){last;}
         }
        }
      }
     $line =~ s!<<&LIST(.*)>>((.*\n?)*)<<&/LIST>>!draw_list($1,$2,$Main_content->{_id} || 0,$Params{c_type})!ge;
     $line =~ s!<<&LIST_L(.*)>>((.*\n?)*)<<&/LIST_L>>!draw_list($1,$2,$Main_content->{_id} || 0,$Params{c_type},1)!ge;
     $line =~ s!<<&RSS(.*)>>((.*\n?)*)<<&/RSS>>!draw_rss($1,$2)!ge;
     $line =~ s!<<&SEARCHLIST(.*)>>((.*\n?)*)<<&/SEARCHLIST>>!draw_s_list($1,$2,$Params{qw})!ge;
#     $line =~ s|<<&CATALOGMENU(.*)>>((.*\n?)*)<<&/CATALOGMENU>>|draw_catalog_menu($1,$2)|ge;
#     $line =~ s!<<&CHILDLIST(.*)>>((.*\n?)*)<<&/CHILDLIST>>!draw_child_list($1,$2,$Main_content->{_id} || 0,$Params{c_type})!ge;
#     $line =~ s!<<&CHILDLIST1(.*)>>((.*\n?)*)<<&/CHILDLIST1>>!draw_child_list1($1,$2,$Main_content->{_id} || 0,$Params{c_type})!ge;
#     $line =~ s!<<&WAYLIST(.*)>>((.*\n?)*)<<&/WAYLIST>>!draw_way($1,$2,$Main_content->{_id} || 0,$Params{c_type})!ge;
#     $line =~ s!<<&NEWSLIST(.*)>>((.*\n?)*)<<&/NEWSLIST>>!draw_news_list($1,$2)!ge;
#     $line =~ s!<<&BASKETLIST(.*)>>((.*\n?)*)<<&/BASKETLIST>>!draw_basket_list($1,$2)!ge;
     $line =~ s!<<&CONTENT(.*)>>((.*\n?)*)<<&/CONTENT>>!draw_content($1,$2)!ge;
#     $line =~ s!<<&SPECLIST(.*)>>((.*\n?)*)<<&/SPECLIST>>!draw_spec_list($1,$2,$Params{c_type})!ge;
#$Cur_mday,$Cur_month,$Cur_year,$Cur_wday
     $line =~ s!<<QW>>!$Params{qw}!ge;
#     
     $line =~ s!<<FILE(.*)>>!draw_file($1)!ge;
     $line =~ s!<<SMJLIST>>!draw_smjlist($Main_content->{_id} || 0,$Main_content->{_parent} || 0)!ge;
     $line =~ s!<<SJLIST>>!draw_sjlist($Main_content->{_id} || 0,$Main_content->{_level} || 0,$Main_content->{_parent} || 0)!ge;
     $line =~ s!<<NDTREE>>!draw_ndtree($Params{type}||0)!ge;
     $line =~ s!<<P_TITLE>>!draw_ptitle($Main_content->{_parent} || 0)!ge;
     $line =~ s|<<MONTHDAY>>|$Cur_mday|ge;
     $line =~ s|<<MONTH>>|$month_array[$Cur_month]|ge;
     $line =~ s|<<YEAR>>|$Cur_year|ge;
     $line =~ s|<<WEAKDAY>>|$wday_array[$Cur_wday]|ge;
     $line =~ s|<<RND>>|rand(65000)|ge;
     $line =~ s|<<URL_BY_NAME(.*)>>|get_url_by_name($1)|ge;
     $line =~ s|<<C_TYPE>>|$Params{c_type}|ge;
     $line =~ s|<<B_COUNT>>|get_basket_count()|ge;
     $line =~ s|<<B_SUMM>>|get_basket_summ()|ge;
     $line =~ s|<<img>>|$Main_content->{img} ne "" ? $Main_content->{img} : '/img/1x1.gif'|ge;
     $line =~ s/<<([^>]+)>>/exists($Main_content->{$1}) ? $Main_content->{$1} : ''/ge;
     print "$line";
   }

# [];
#get_tree(get_first_root(),$MyMasRef = [],0,1);
#get_childs(0,$MyMasRef = [],0,1);
#@{$MyMasRef} = reverse(@{$MyMasRef});
#del_tree(3);
#$RunTime = $RunTime-time;
#print "<hr><h1>END $RunTime<hr>";
close FD;

sub sendMail {
my($from, $to, $subj, $comm);
$from=$_[0]; $to=$_[1]; $subj=$_[2]; $comm=$_[3];
open (MAIL,"|/usr/bin/sendmail -t") || &errmsg("Mail error $! \n");
print MAIL "From: $from\n";
print MAIL "To: $to\n";
print MAIL "Subject: $subj\n";
print MAIL "Content-Type: text/plain; charset=Windows-1251\n\n";
print MAIL $comm;
close(MAIL);
}

sub basket_request()
{
my $myemail = 'robot@frontgeo.ru'; # обратный адрес
my $toemail = 'info@frontgeo.ru'; # кому адресовать заявку
my $ra = $ENV{'REMOTE_ADDR'};
my $rn = gethostbyaddr(inet_aton($ra), AF_INET) || { $rn = "$!" };
my $rp = $ENV{'HTTP_REFERER'};
my $ltm = scalar localtime;
#if($rp !~ /http:\/\/www.bloknout.ru\//i) { &errmsg("403 Forbidden"); }
my $letter = << "EOL";
* Внимание поступило сообщение:

  $Params{name}
  $Params{org}
  $Params{phone}
  $Params{email}
  
  
  $Params{message}

* Local Date     : $ltm
* Remote Address : $ra ($rn)
* Remote Referer : $rp
EOL

# send letters
sendMail($myemail, $toemail, "Robot : www.frontgeo.ru", $letter);
}

sub get_basket()
{
my $b_str='';
my @b_mas=split(/;/, $ENV{'HTTP_COOKIE'});
my %b_hash;
#Поиск кукиса basket
foreach (@b_mas)
 {s/ //;split /=/; if ($_[0] eq 'basket'){$b_str = $_[1]; last;}}
#разбор basket  _id=>count
@b_mas=split(/\|/, "$b_str");
foreach (@b_mas){split /-/;$b_hash{$_[0]}=$_[1];}
return %b_hash;
}

sub get_basket_count()
{
my ($res,$b_id,$b_count)=(0,0,0);
while (($b_id,$b_count) = each(%b_hash))
  {$res+=$b_count if $b_count;}
return $res;
}

sub get_basket_summ()
{
my ($res,$b_id,$b_count)=(0,0,0);
my $th=[];
while (($b_id,$b_count) = each(%b_hash))
  {
      unless($b_count){next;}
      $th=content->get_content_href_by_id($b_id);
      $th->{price} =~ s/,/'.'/ge;
      $res+=$b_count*$th->{price};
  }
return $res;
}

sub get_url_by_name
{
my $param = shift || return '';
my ($C_name,$C_type,$C_href);
$param = trim_ext($param);
my @fields=split(/ /,$param);
foreach (@fields)
 {
  if(/^c_type=(.*)/){$C_type = $1;}
  if(/^_name=(.*)/){$C_name=$1;}
 }
unless($C_name) {return '';}
unless($C_type) {return '';}
$C_href = $C_type->get_content_href_by_id($C_type->get_id_by_name($C_name));
unless ($C_href->{_id}) {return '';}
#if($C_type eq 'content')
# {return "?_id=$C_href->{_id}";}
#else{return "?_id=$C_href->{_id}&c_type=$C_type";}
return "?_id=$C_href->{_id}&c_type=$C_type";
}


sub draw_ptitle{
 my ($parent)=@_;
 my $C_href;
 $C_href= jobs->get_content_href_by_id($parent);
 return $C_href->{title};
}

sub draw_file{
 my ($param)=@_;
 my ($fname);
 $param = trim_ext($param);  my @fields=split(/ /,$param);
 foreach (@fields)  {if(/^fname=(.*)/){$fname=$1;}}
 unless($fname) {return '';}
 open(FD2,'<',"pattern/m_weather1.html") || errmsg("Can't open file $fname: $!");
 print <FD2>;
 close(FD2);
 return '';
}

sub draw_content{

 my ($param,$body)=@_;
# print"##########$body##################";
 my ($res,$qwer);
 my ($C_type,$C_name,$C_href);
 $param = trim_ext($param);
 my @fields=split(/ /,$param);
   foreach (@fields)
  {
   if(/^c_type=(.*)/){$C_type = $1;}
   if(/^_name=(.*)/){$C_name=$1;}
  }
unless($C_name) {return '';}
unless($C_type) {return '';}
$C_href = $C_type->get_content_href_by_id($C_type->get_id_by_name($C_name));
$body =~ s/<<([^>]+)>>/exists($C_href->{$1}) ? $C_href->{$1} : ''/ge;

return $body;
}

sub draw_news_list()
{
 my ($param,$body)=@_;
 my $MyMasRef=[];
 my $i=0;
 news->get_childs($C_id,$MyMasRef,0);
 foreach (@{$MyMasRef})
  {
      $qwer = $body;
      $qwer =~ s/<<([^>]+)>>/exists($_->{$1}) ? $_->{$1} : ''/ge;
      $res.=$qwer;
      ++$i;
      if($i==3){last;}
  }
 return $res;
}

sub draw_rss()
{
 my ($param,$body)=@_;
 my $i=0,$tmp=0,$s12,$t1,$t2,$t3,$t4;
#use encoding 'cp1251', STDOUT => 'cp1251';
# Declare variables for URL to be parsed
my $url2parse;
# Get the command-line argument
#my $arg = 'http://www.warandpeace.ru/ru/rss/';
my $arg = 'http://frontgeo.ru/wnprss/';
# Create new instance of XML::RSS
# Get the URL, assign it to url2parse, and then parse the RSS content
eval {
	my $ua=LWP::UserAgent->new;
	$ua->timeout(3);
	my $response=$ua->get($arg);
	if($response->is_success){
		$url2parse=$response->content;
	} else {
		warn "error fetching news,content: ".Dumper($response);
		return;
	}
};
if($@){
warn "Exception while fetching news: $@";
       return;
}
my $rss = new XML::RSS;
eval {
$rss->parse($url2parse);
};
if($@){
	warn "Exception while parsing news: $@";
	return;
}
foreach (@{$rss->{'items'}})
  {   next unless defined($_->{'title'}) && defined($_->{'link'});


$t1 = encode_utf8($_->{'title'});
$t2 = encode_utf8($_->{'link'});
$t3 = encode_utf8($_->{'description'});
$t4 = encode_utf8($_->{'pubDate'});
Encode::from_to($t1, "utf8", "cp1251");
Encode::from_to($t2, "utf8", "cp1251");
Encode::from_to($t3, "utf8", "cp1251");
Encode::from_to($t4, "utf8", "cp1251");

      $qwer = $body;

#      $qwer =~ s/<<([^>]+)>>/exists($_->{$1}) ? $_->{$1} : ''/ge;
      $qwer =~ s/<<title>>/$t1/ge;
      $qwer =~ s/<<link>>/$t2/ge;
      $qwer =~ s/<<description>>/$t3/ge;
      $qwer =~ s/<<pubDate>>/$t4/ge;

      $res.=$qwer;
      ++$i;
      if($i==3){last;}
  }
 return $res;
}



sub draw_part_name
{
 my ($C_id,$C_type)=@_;
 unless ($C_type) {return 0;}
 unless ($C_id) {$C_id=0;}
 my ($qwer, $res);
 my $MyMasRef=[];
 $C_type->get_way($C_id,$MyMasRef,0);
 if(@$MyMasRef){ return $MyMasRef->[$#$MyMasRef]->{title};}
 else{return '';}
}

sub draw_way
{
 my ($param,$body,$C_id,$C_type)=@_;
 my ($qwer, $res);
 unless ($C_type) {return 0;}
 unless ($C_id) {$C_id=0;}
 my $MyMasRef=[];

 $C_type->get_way($C_id,$MyMasRef,0);
 @{$MyMasRef} = reverse(@{$MyMasRef});
 foreach (@{$MyMasRef})
  {   # меняем местами год и день и тире заменяем на точки

#         print"<hr>$_->{name}<hr>";
      if($_->{_id} != $C_id)
      {
      $qwer = $body;
      $qwer =~ s/<<([^>]+)>>/exists($_->{$1}) ? $_->{$1} : ''/ge;
      $res.=$qwer;
      }
      #$res.="<hr>!!!!!!!!!!!!!!!!!!!!!!!!!!<hr>";
 }

 return $res;
}

sub draw_basket_list()
{
 my ($param,$body)=@_;
 my $res='';
 my $qwer='';
 my $th=[];
  foreach (keys %b_hash)
  {
      unless($b_hash{$_}){next;}
      $qwer = $body;
      $th=content->get_content_href_by_id($_);
      $th->{price} =~ s/,/'.'/ge;
      $qwer =~ s/<<b_count>>/$b_hash{$th->{_id}} || '0'/ge;
      $qwer =~ s/<<b_price>>/$b_hash{$th->{_id}}*$th->{price}/ge;
      $qwer =~ s/<<([^>]+)>>/exists($th->{$1}) ? $th->{$1} : ''/ge;
      $res.=$qwer;
  }
 return $res;
}

sub draw_child_list()
{
 my ($param,$body,$C_id,$C_type)=@_;
 my $res='';
 my $qwer='';
 foreach (@{$MyChildMasRef})
  {
      next unless $_->{_child};
      $qwer = $body;
      $qwer =~ s|<<img>>|$_->{img} ? $_->{img} : 'img/1x1.gif'|ge;
      $qwer =~ s/<<([^>]+)>>/exists($_->{$1}) ? $_->{$1} : ''/ge;
      $res.=$qwer;
  }
 return $res;
}

sub draw_child_list1()
{
 my ($param,$body,$C_id,$C_type)=@_;
 my $pre_res='';
 my $after_res='';
 my $res='';
 my $qwer='';
 $body =~ /<<START>>/; $pre_res =$`; $body=$';
 $body =~ /<<END>>/; $body =$`; $after_res=$';
 foreach (@{$MyChildMasRef})
  {
 #     print"<hr>1 $pre_res<hr>2 $body<hr>";
      next if $_->{_child};
      $qwer = $body;
      $qwer =~ s|<<img>>|$_->{img} ? $_->{img} : 'img/1x1.gif'|ge;
      $qwer =~ s/<<b_count>>/$b_hash{$_->{_id}} || '0'/ge;
      $qwer =~ s/<<([^>]+)>>/exists($_->{$1}) ? $_->{$1} : ''/ge;
      $res.=$qwer;
  }
 return '' unless $res;
 return $pre_res.$res.$after_res;
}

sub draw_spec_list()
{
 my ($param,$body,$C_type)=@_;
 unless ($C_type) {return '';}
 my $MyMasRef=[];
 my ($C__name,$qwer,$res)=('','','');
 $param = trim_ext($param);
 @fields=split(/ /,$param);
 foreach (@fields)
  {
   if(/^_name=(.*)/){$C__name = $1;}
  }
 unless ($C__name) {return '';}
 $C_type->get_content_hrefs_by_name1($C__name,$MyMasRef);
 foreach (@{$MyMasRef})
  {
      $qwer = $body;
      $_->{_name}=~ s/^\w+//;
      $qwer =~ s|<<img>>|$_->{img} ? $_->{img} : 'img/1x1.gif'|ge;
      $qwer =~ s/<<([^>]+)>>/exists($_->{$1}) ? $_->{$1} : ''/ge;
      $res.=$qwer;
  }
 return $res;
}


sub get_catalog_menu
{
 my $C_id = shift || 0;
 my $Ret_mas_ref = shift || []; #Массив хэшей для возврата
 my $hash_ref= [];
 content->get_childs($C_id,$hash_ref,1);
 foreach (@{$hash_ref})
 {
  if($_->{_child}) { push @{$Ret_mas_ref}, $_;}
  if($MyWayMasRef_1{$_->{_id}})
   {get_catalog_menu($_->{_id},$Ret_mas_ref);}
 }
 return $Ret_mas_ref;
}

sub draw_catalog_menu
{
 # print"##########$body##################";
 my ($param,$body)=@_;
 my ($res,$qwer,$i);
 my $MyMasRef=[];
 my $L0=
  '<tr>
   <td height="6" align="center"><img src="img/1x1w.gif" alt="" width="90%" height="2" border="0"></td>
   </tr>';
 get_catalog_menu(0,$MyMasRef);
 foreach (@{$MyMasRef})
  {  if($_->{_child} || $_->{_level} == 0)
      {
      $qwer = $body;       #  == 1
      if ($_->{_level} == 0 && $i){$qwer=$L0.$qwer;}
      $qwer =~ s/<<SPACES>>/get_spases(2 + $_->{_level}*3)/ge;
      $qwer =~ s/<<([^>]+)>>/exists($_->{$1}) ? $_->{$1} : ''/ge;
      $res.=$qwer;
      }
     $i=1;
  }
 return $res;
}

sub get_main_content
{
 my $C_id = shift || 0;
 my $C_type = shift || return 0;;
 my $Res=[];
 $Res= $C_type->get_content_href_by_id($C_id);
 return $Res;
}

sub get_spases
{
 my $Count = shift || 0;
 my $Res="";
 while ($Count)
 {
 $Res="$Res&nbsp;";
 --$Count;
 }
 return $Res;
}


sub get_date
{
my ($Cur_day,$Cur_month,$Cur_year)=(localtime)[3,4,5];
$Cur_month++;
$Cur_year+=1900;
$Cur_date = sprintf("%04d-%02d-%02d", $Cur_year,$Cur_month,$Cur_day);
return $Cur_date;
}

sub draw_ndtree
{
 my $Type = shift || 0;
 my $s1,$s2=('','');
 my $res='';
 my $qwer='';
 my $MyMasRef=[];
 my $fl=0;
 $s1='<tr><td colspan="2" class="alt_navi">&nbsp;</td></tr><tr><td colspan="2" class="alt_navi"><strong><<title>></strong></td></tr>';

# return unless $C_type;
 nd->get_tree_l(nd->get_first_root(),$MyMasRef,0,1);
 @{$MyMasRef} = reverse(@{$MyMasRef});
 foreach (@{$MyMasRef})
  {  # print"<hr>$fl($_->{_level}::$_->{type})         ";
     if($_->{'img'}){$s2='<tr><td width="28" align="right">&nbsp;</td><td valign="top"><br><a href="<<img>>" class="blue_text"><strong><<s_title>></strong>&nbsp;<<title>>&nbsp;<img src="img/load.gif" alt="Скачать" width="17" height="17" border="0"></td></tr>';}
#     if($_->{'img'}){$s2='<tr><td width="48" align="right">&nbsp;&nbsp;</td>    <td valign="top"><br><a href="<<img>>" class="blue_text"><strong><<title>><br></strong>&nbsp;&nbsp;<a href="<<img>>" title="Скачать файл"><img src="img/load.gif" alt="Скачать" width="17" height="17" border="0"></a></td></tr>';}
     else {$s2='<tr><td width="28" align="right">&nbsp;</td><td valign="top"><br><a href="?c_type=nd&_id=<<_id>>" class="blue_text"><strong><<s_title>></strong><<title>></td></tr>';}
      if((int($_->{type}) & int($Type)) || $_->{_level}==0 || $Type==0){
    	  if ($_->{_level}) {$res.=$qwer if $fl; $qwer = $s2; $fl=0;}
      	  else {$qwer=$s1; $fl=1}
     	  $qwer =~ s/<<([^>]+)>>/exists($_->{$1}) ? $_->{$1} : ''/ge;
      	  $res.=$qwer unless $fl;
      }
    #  print"::$fl<hr>";
  }
 return $res;
}



sub draw_sjlist
{
 my ($C_id,$C_level,$C_parent)=@_;
 my $s1,$s2=('','');
 my $res='';
 my $qwer='';
 my $MyMasRef=[];
 $s1='<a href="?c_type=projects&_id=<<_id>>" class="alt_navi2"><<title>>&nbsp;</a><br><img src="img/1x1.gif" alt="" width="1" height="5" border="0"><br>';
 $s2='<span class="alt_navi2" style="background-color: #edeef2"><<title>>&nbsp;</span><br><img src="img/1x1.gif" alt="" width="1" height="5" border="0"><br>';
# return unless $C_type;
 if ($C_level){jobs->get_childs_l($C_parent,$MyMasRef,0);}
 else{jobs->get_childs_l($C_id,$MyMasRef,0);}

 foreach (@{$MyMasRef})
  {
      if ($_->{_id} == $C_id) {$qwer = $s2;}
      else {$qwer=$s1;}
      $qwer =~ s/<<([^>]+)>>/exists($_->{$1}) ? $_->{$1} : ''/ge;
      $res.=$qwer;
  }
 return $res;
}



sub draw_smjlist
{
 my ($C_id,$C_parent)=@_;
 my $s1,$s2=('','');
 my $res='';
 my $qwer='';
 my $MyMasRef=[];
 $s1='<a href="?c_type=projects&_id=<<_id>>" class="alt_navi" title="<<title>>">&nbsp;<<s_title>></a><br><img src="img/1x1.gif" alt="" width="1" height="5" border="0"><br>';
 $s2='<span class="alt_navi" style="background-color: #edeef2">&nbsp;<<s_title>>&nbsp;</span><br><img src="img/1x1.gif" alt="" width="1" height="15" border="0">';
# return unless $C_type;
 jobs->get_childs_l(0,$MyMasRef,0);
 foreach (@{$MyMasRef})
  {
      if ($_->{_id} == $C_id ||$_->{_id} == $C_parent) {$qwer = $s2;}
      else {$qwer=$s1;}
      $qwer =~ s/<<([^>]+)>>/exists($_->{$1}) ? $_->{$1} : ''/ge;
      $res.=$qwer;
  }
 return $res;
}

sub draw_s_list
{
 my ($param,$body,$qw)=@_;
 my $res='';
 my $qwer='';
 my $MyMasRef=[];
 my $C_type;
 jobs->search($qw,$MyMasRef);
 $C_type='jobs';
 foreach (@{$MyMasRef})
  {   $S_Count+=1;
      $qwer = $body;
      $qwer =~ s!<<S_COUNT>>!$S_Count!ge; 
      $qwer =~ s/<<c_type>>/$C_type/ge;
      $qwer =~ s/<<([^>]+)>>/exists($_->{$1}) ? $_->{$1} : ''/ge;
      $res.=$qwer;
  }
 
 my $MyMasRef1=[];
 $C_type='publication';
 $C_type->search($qw,$MyMasRef1);
 foreach (@{$MyMasRef1})
  {   $S_Count+=1;
      $qwer = $body;
      $qwer =~ s!<<S_COUNT>>!$S_Count!ge; 
      $qwer =~ s/<<c_type>>/$C_type/ge;
      $qwer =~ s/<<([^>]+)>>/exists($_->{$1}) ? $_->{$1} : ''/ge;
      $res.=$qwer;
  }
  
 my $s1='<br>Найдено <strong><<S_COUNT>></strong> страниц<br><br><table width="100%" cellspacing="0" cellpadding="0" border="0">';
 $s1 =~ s!<<S_COUNT>>!$S_Count!ge; 
 return $s1.$res;
}

sub draw_list
{
 my ($param,$body,$C_id,$C_type,$IsLite)=@_;
 my $res='';
 my $qwer='';
 $param = trim_ext($param);
 my @fields=split(/ /,$param);
 my $MyMasRef=[];
 foreach (@fields)
  {
   if(/^c_type=(.*)/){$C_type = $1;}
   if(/^c_id=(.*)/){$C_id=$1;}
  }
 return unless $C_type;

 if($IsLite){$C_type->get_childs_l($C_id,$MyMasRef,0);}
 else{$C_type->get_childs($C_id,$MyMasRef,0);}

 foreach (@{$MyMasRef})
  {
      $qwer = $body;
      if(($C_type eq 'cust') && ($_->{'href'})){$qwer =~ s|<<cname>>|'<a href="http://<<href>>" class="z_link"><<cname>></a>'|;}
      if($C_type eq 'prop')
              {  if($_->{'href'}) {$qwer='<tr><td width="9">&nbsp;</td><td><a href="http://<<href>>" class="main_text"><<pname>></a></td></tr>';}
                 else {$qwer = '<tr><td width="9">&nbsp;</td><td><span class="main_text"><<pname>></span></td></tr>';}
              }   #<td width="9" rowspan="5">&nbsp;</td>
      #if 
#      $qwer =~ s|<<img>>|$_->{img} ? $_->{img} : 'img/1x1.gif'|ge;
      $qwer =~ s/<<([^>]+)>>/exists($_->{$1}) ? $_->{$1} : ''/ge;
      $res.=$qwer;
  }
 return $res;
}

sub draw_newslist
{
 my ($param,$body)=@_;
# print"##########$body##################";
 my ($res,$qwer);
 my ($column,$srt,$ert);
 $param = trim_ext($param);
 @fields=split(/ /,$param);
 foreach (@fields)
  {
   if(/^column=(.*)/){$column = $1;}
   if(/^startrowtext=(.*)/){$srt=$1;}
   if(/^endrowtext=(.*)/){$ert=$1;}
  }
 $sqlstatement = "SELECT * FROM $table ORDER BY date DESC , id DESC";
 $sth = $dbh->prepare($sqlstatement) || errmsg("Невозможно выполнить SQL-запрос. $sqlstatement");
 $sth->execute || errmsg("Невозможно выполнить SQL-запрос. $sqlstatement");
 while (@row=$sth->fetchrow_array)
  {   # меняем местами год и день и тире заменяем на точки
      $row[1] =~ s/(\d+)-(\d+)-(\d+)/"$3.$2.$1"/e;
      $qwer = $body;
      $qwer =~ s/<<NEWSID>>/$row[0]/ge;
      $qwer =~ s/<<NEWSDATE>>/$row[1]/ge;
      $qwer =~ s/<<NEWSNAME>>/$row[2]/ge;
      $qwer =~ s/<<NEWSABOUT>>/$row[3]/ge;
      $qwer =~ s|<<NEWSTEXT>>|$row[4]|ge;
      $qwer =~ s|<<NEWSURL>>|$row[5]|ge;
      $qwer =~ s|<<NEWSURLNAME>>|$row[6]|ge;
      $qwer =~ s|<<CHARNUM>>|$charnum|ge;
      $qwer =~ s|<<CHAR>>|$charname|ge;
      $res.=$qwer;
  }
return $res;
}

############# Очищает строку много от чего ####################
sub trim_ext
{
 local($res)=@_;
 # Удаляет начальные и конечные пробелы и левые символы
 $res =~ s/[\t"\n]/ /g;
 $res =~ s/^\s+|\s+$//g;
 # Удаляет "длинные" пробелы
 $res =~ s/\s+/ /g;
 # Удаляет пробелы у "равно"
 $res =~ s/\s*=\s*/=/g;
 return $res;
}

sub errmsg
{
print <<EOF;
<HTML>
<HEAD>
<TITLE>Error message</TITLE>
<BODY>
<H2>Error message</H2>
<HR>
@_<BR>
Error: $! <br>
<HR>
</BODY>
</HTML>
EOF
exit(0);
}

