<?php
 $mod='gl';
 require('include.inc.php4');
 if (isset($id)) {
//  $SitesSetting['Title']="Ростов Электронный - портал о Ростове: новости, афиша, электронный журнал, недвижимость, доска объявлений г. Ростова-на-Дону";
  $SitesSetting['Title']="Ростов Электронный - портал о Ростове: ";
  $index_tpl_file="index_foto.html";
  $page_title=$SitesSetting['Title'];
//echo "<br>#################= ".$index_tpl_file;
 }

 function order_cmp($a,$b)
  {   
    if ($a[sort]<$b[sort]) return -1;
    return (($a[sort]>$b[sort])||($a[sort]=$b[sort]&&$a[sort_inr]>$b[sort_inr]))?1:-1;
  }

 require('page.inc.php4');

 if (!isset($start)) $start=0;
 $r_info_ar=array();
 $rubric_page_site=$galery_rubric;
 $r_info_ar[0][id]=$site_galery_rubric;
 $image_path="./files/galery/";
 $img_gal_path=$relative_path."files/galery/";
 $value=array();

if (isset($id)) 
 { 
//echo "<br>??????????????????==== ".$index_tpl_file;
//
  $tpl='gallery_foto_info.html';
  $query_str="SELECT *,pa_name, DATE_FORMAT(ph_date,'DD.MM.YY') as date FROM parts,photogalery,photos WHERE pa_id=ph_rubric and ph_id=pg_ph_id";
  $query_str.=" and pg_id=".$id;
  $out=array();
  $query1->setQueryText($query_str);
  $result1=$query1->execQuery();
  if ($connection1->CountTuples($result1))
   { $phts=$connection1->fetchRow($result1,0);
     if ($phts[pg_photo]!=NULL&&file_exists($img_gal_path.$phts[pg_photo]))
      { $value['img']=$img_gal_path.$phts[pg_photo];
        $size=getZoomSizeImg($img_gal_path.$phts[pg_photo],$GallerySetting['DefaultWidthB']);
        $value['width']=$size['width'];
        $value['height']=$size['height'];
      }
      $value['ph_header']=$phts['ph_header'];
      $value['ph_resume']=$phts['ph_resume'];
//      $value['ph_shot_resume']=$photoinfo['ph_shot_resume'];
      $rubric=$phts[ph_rubric];
     $title=" \ ".$value['ph_header'];
   }
//ECHO "<BR>?????????????".$title;
  $value['IncludePath']=$IncludePath;
  $value['rubric']=$rubric;
  $PN_page->addMainValue('Title',$title);
  $PN_page->addMainValue('info',$value,$tpl);      
  $PN_page->printPage();
 } else {

  require("main_functions.php");
//  require('func_include_up2.php');
  require('func_include_up.php');


//  require("nws_config.php");
//  require("nws_connect.php");
//  require("nws_setting.php");
//  require("nws_attach.php");

  $entry=trim($entry);

  if (isset($photo)) 
   { 
     $tpl='galery_photo.html';

     $query_str="SELECT *,pa_name, DATE_FORMAT(ph_date,'DD.MM.YY') as date FROM parts,photogalery,photos WHERE pa_id=ph_rubric and ph_id=pg_ph_id";
     $query_str.=" and pg_ph_id=".$photo;
     $query_str.=" order by pg_sort";
 
     $query1->setQueryText($query_str);
     $result1=$query1->execQuery();
     $k=0;
     $photos_out=array();
     $is_photo=false;


//echo "<br>????????????????/ ".$connection1->CountTuples($result1);
     if ($connection1->CountTuples($result1)>0)  
      { for ($i=0;$i<$connection1->CountTuples($result1);$i++) 
         { 
          $phts=$connection1->fetchRow($result1,$i);
          if ($phts[pg_photo]!=NULL&&file_exists($img_gal_path.$phts[pg_photo]))
           { 
             $is_photo=true;
             $photos_out[$k]=$phts;
             $photos_out[$k]['photo']=$img_gal_path.$phts[pg_photo];
             $photos_out[$k]['photo_path']=$A_images_path;
             $photo_ingo=GetImageSize($img_gal_path.$phts[pg_photo]);
             $photos_out[$k]['width']=$photo_ingo[0];
             $photos_out[$k]['height']=$photo_ingo[1];
             if (trim($phts[pg_res])!="")
               $photos_out[$k]['resolution']=$phts[pg_res];
             else
               $photos_out[$k]['resolution']=$photo_ingo[0]."x".$photo_ingo[1];
             $photos_out[$k][pa_id]=$phts[pa_id];
             $rubric=$phts[pa_id];
             $photos_out[$k][rubric]=$rubric;
             $photos_out[$k]['hrefphoto']="javascript:viewfoto('".$PHP_SELF."?mod=gl&id=".$phts[pg_id]."',".$photo_ingo[0].",".$photo_ingo[1].",1,'photos')";
             $photos_out[$k]['HrefMiddlePhoto']=$IncludePath."galery.php4?mod=gl&photo=".$phts[ph_id];
             $photos_out[$k][rubric_name]=$phts['pa_name'];
             $photos_out[$k][name]=$phts['ph_header'];
             $photos_out[$k][sort]=$phts['pg_sort'];
             $k++;
           }
         }
//       $out_slice[$in][photo_imgs]=$photos_out;
      }
     $value['img']=$photos_out[0]['photo'];
     $size=getZoomSizeImg($photos_out[0]['photo'],500);
     $value['width']=$size['width'];
     $value['height']=$size['height'];
     $value['ph_header']=$photos_out[0][name];


     $width=500;
     $height=400;
     $src=$value['img'];
     $FileExp=".".substr(strrchr($src,"."),1);
     $Suffix=strtolower("_middle".$FileExp);
     $newsrc=str_replace($FileExp,$Suffix,$src);

     require('main_save_img_resize.php');
 
     if (file_exists($newsrc)) {
        $value['img']=$newsrc;
        $value['width']=$width;
        $value['height']=$height;
      }


     $value['photos']=$photos_out;
     $value['rubric_name']=$photos_out[0][rubric_name];

     $query_str="SELECT *,pa_name, DATE_FORMAT(ph_date,'DD.MM.YY') as date FROM parts,photogalery,photos WHERE pa_id=ph_rubric and ph_id=pg_ph_id";
     $query_str.=" AND ph_rubric=".$rubric;
     $query_str.=" order by ph_sort,pg_sort";
     $query1->setQueryText($query_str);
     $result1=$query1->execQuery();
     $photos_out=array();
     $photos=array();
     $is_photo=false;
     if ($connection1->CountTuples($result1))
      {$photos_out=array();
       $k=0;
       $j=0;
       for ($i=0;$i<$connection1->CountTuples($result1);$i++)
        {$phts=$connection1->fetchRow($result1,$i);
         if ($mem_ph_id!=$phts[ph_id]&&$i!=0) 
          {
           if ($is_photo) 
            {
             if ($mem_ph_id==$photo) $start=$j; 
             $photos_out[$j][ph_id]=$mem_ph_id;
             $photos_out[$j][href]=$IncludePath."galery.php4?photo=".$mem_ph_id;
             $j++;
            }
           $photos=array();
           $k=0;
           $is_photo=false;
          }
         if ($phts[pg_photo]!=NULL&&file_exists($img_gal_path.$phts[pg_photo]))
          { 
           $is_photo=true;
           $photos[$k]=$phts;
           $k++;
          }
         $mem_ph_id=$phts[ph_id];
        }
      }
      $value['prevhref']=($start!=0?$photos_out[$start-1][href]:false);
      $value['nexthref']=($start==count($photos_out)-1?false:$photos_out[$start+1][href]);
      $value['back_href']=$HTTP_REFERER;
      $title=" \ Подробно";
   } else {
     $tpl='galery_info.html';
     if (!isset($rubric)) $rubric=$galery_rubric; 
     if (!isset($page)) $page=0; 
     $rubric_class->setScriptName($PHP_SELF);
     $rubric_class->setRubric();
   
     $view_rubrics=$rubric_class->getRubricList($rubric,0,$field='');
     if (count($view_rubrics)&&!$detail) {
        $view_rubrics=$rubric_class->getRubricList($rubric,0,$field='');
      } else {
        $view_rubrics=$rubric;
      }
   
     $query_str="SELECT *,pa_name, DATE_FORMAT(ph_date,'DD.MM.YY') as date FROM parts,photogalery WHERE pa_id=ph_rubric";
     if (is_array($view_rubrics))
     { $where='';
       $where.=" OR ph_rubric=".$rubric;
       for ($i=0;$i<count($view_rubrics);$i++)
        { $where.=" OR ph_rubric=".$view_rubrics[$i][id];
        }
       $query_str.=" AND (".substr(trim($where),3).")";
     } else
     { $query_str.=" AND ph_rubric=".$view_rubrics;
     }
   
     $titletext="Все";
     $addtohref="";
     if ($favorite) { 
      $query_str.=" AND ph_favorite=1"; 
      $titletext="Избранное";
      $addtohref="&favorite=yes";
     }
   


     $search_string="";
     if($entry)
     {  //search
      if (strpos($entry,' ')) {
        $tmp=explode(' ',$entry);
//       $search_string="ph_name~*'".$tmp[0]."'";
         for ($j=0;$j<count($tmp);$j++) {
//          $search_string.=" AND ph_header~*'".$tmp[$j]."'";
          $search_string.=" AND ph_header LIKE '%".$tmp[$j]."%'";
          }
       } else {
//        $search_string="  AND ph_header~*'$entry'";
        $search_string=" AND ph_header LIKE '%$entry%'";
       }
       $query_str.=$search_string;
       $titletext="Поиск";
       $addtohref.="&entry=$entry";
//       $query_str.=" and ph_header~*'$entry'";
//       $r_name1="Результат поиска в фотогалерее по запросу: $entry";
     }
   
     $title=" \ ".$titletext;
     $out=array();
     $query1->setQueryText($query_str);
     $result1=$query1->execQuery();
     if ($connection1->CountTuples($result1))
     { $rubric_name='';
       $out=array();
       $k=0;
       for ($i=0;$i<$connection1->CountTuples($result1);$i++)
        { $gls=$connection1->fetchRow($result1,$i);
          if ($gls[ph_file]!=NULL&&file_exists($img_gal_path.$gls[ph_file]))
            { 
              $out[$k]=$gls;
              $out[$k]['img']=$img_gal_path.$gls[ph_file];
              $out[$k]['img_path']=$A_images_path;
              $img_ingo=GetImageSize($img_gal_path.$gls[ph_file]);
              $out[$k]['width']=$img_ingo[0];
              $out[$k]['height']=$img_ingo[1];
              $out[$k][root_rubric]=$rubric;
              $out[$k][pa_id]=$gls[pa_id];
              $out[$k][rubric_name]=$gls['pa_name'];
              $out[$k][name]=$gls['ph_header'];
              $out[$k][sort]=$gls['pa_sort'];
   
              $arr_rubs=array();
              $arr_rubs=getRubricInfo($galery_rubric,$gls[pa_id]," : ",'a');
   
              $out[$k][upr_arr]=$arr_rubs;
              $out[$k][id]=$gls[ph_id];
              $out[$k][sort_inr]=(int)$gls[ph_sort];
              if (is_array($view_rubrics))
               { for ($l=0;$l<count($view_rubrics);$l++)
                    {if ($view_rubrics[$l][id]==$gls[pa_id]) 
                       { 
                         $out[$k][sort]=$l+1;
                         break;
                       }
                    }
                } else {$out[$k][sort]=1;}
              $k++;
   
            }
        }
   
        usort($out,"order_cmp");
        $n=0;
        $amfrn=array();
        $amount_images=0;
   
        $pages=array();
        $memstart=0;
        $pl=0;
        $nir=0;                 // количество первых позиций в текущей рубрике
        $memidrubric=$out[0][pa_id];
        $out_show=array();
//          $pages[$memstart][back_href]="./index.php4?start=".$memstart."&rubric=".$memidrubric;
        $k=0;
        $in_str=0;            // количество позиций в текущей строке
        $pages=array();
        $indp=0;              // индекс массива страниц
        $AmountImgsPage=0;
        $memind=0;
   
        if (!$detail) 
         {
   
          for ($j=0;$j<count($out);$j++)
           { 
//    ----------- проверка смены рубрики начало --------------------------
             if ( $out[$j][rubric_name]!=$rubric_name || $j==0)
              { 
               if ($out_show[$memind][indetail]) {
//echo "<br> ????? j ==  ".$j;
                    $out[$j][preindetail]=true;
                    $out[$j][prehref_indetail]=$out_show[$memind][href_indetail];
                 }
                $memj=$j;           // запоминание индекса j
                $memind=$k;           // запоминание индекса первой картинки в текущей рубрике
                $NumStr=CEIL($nir/$GallerySetting['CountColumnG']);
                $Rest=($NumStr*$GallerySetting['CountColumnG'])-$nir;
                $RestStr='';
                for ($inr=0;$inr<$Rest;$inr++) { $RestStr.='<td>&nbsp;</td>'; }
                $prehtmlrb=$RestStr."</tr>";
                if ($j==0) $prehtmlrb="";
                $nir=0;
                $in_str=0;
/* 
здесь    может быть формирование  полного дерева  рубрики $outfrn 
*/
                $memprehtmlrb=$prehtmlrb;
                $out[$j][prehtmlrb]=$prehtmlrb;
                $rubric_name=$out[$j][rubric_name];
              } else {
                 $out[$j][rubric_name]=false; 
              }
//-------------- проверка смены рубрики конец --------------------------
      
             if ($nir>=$GallerySetting['CountFotoRubricG']) {
                $out_show[$memind][indetail]=true;
                $out_show[$memind][href_indetail]=$PHP_SELF."?detail=yes&rubric=".$out_show[$memind][pa_id].$addtohref;
                continue;
              }
      
             $lcount=($memind==0?$k:$memind);
             $next_lcount=$memind-$pages[$indp][start];
             $curind=$memind;
             if ($AmountImgsPage+1>$GallerySetting['CountFoto']) {
      
               $pages[$indp][selected]=false;
               if ($indp==$page) $pages[$indp][selected]=true;
      
               if ($indp==0) {
                 $pages[$indp][delimit]="";
                 $pages[$indp][start]=0;
                 $pages[$indp][count]=$lcount;
                 $pages[$indp][number]=$indp+1;
                 $pages[$indp][prehtmlrb]=$memprehtmlrb;
                 $pages[$indp][href]=$PHP_SELF."?page=0".$addtohref;
                } else {
                 $pages[$indp][delimit]=" - ";
                 $pages[$indp][start]=$pages[$indp-1][start]+$pages[$indp-1][count];
                 $out_show[$pages[$indp][start]][prehtmlrb]="";
                 $pages[$indp][count]=$curind-$pages[$indp][start];
                 $pages[$indp][number]=$indp+1;
                 $pages[$indp][prehtmlrb]=$memprehtmlrb;
                 $pages[$indp][href]=$PHP_SELF."?page=$indp".$addtohref;
                }
               $AmountImgsPage=$nir;
               $indp++;
              }
             if ($in_str<$GallerySetting['CountColumnG']) 
              {
               if ($nir==0) {
                 $prehtml="<tr>";
               } else {
                 $prehtml="";
               }
               $in_str++;
              } else {
      
               $prehtml='</tr><tr><td colspan='.$GallerySetting['CountColumnG'].'><table width="100%" height="10"  border="0" cellpadding="0" cellspacing="0" class="d_razd"><tr><td height="10"></td></tr></table></td></tr><tr>';
               $in_str=1;
              }
             $out[$j]['column']=$GallerySetting['CountColumnG'];
             $out[$j][prehtml]=$prehtml;
             $out_show[$k]=$out[$j];
             $AmountImgsPage++;
             $nir++;
             $name_rubric=$out_show[$k][rubric_name];
             $k++;
           }
          if ($out_show[$memind][indetail]) {
             $lastpreindetail=true;
             $lastprehref_indetail=$out_show[$memind][href_indetail];
           }
         } else {
      
          for ($j=0;$j<count($out);$j++)
           { 
//-------------- проверка смены рубрики начало --------------------------
             if ($j==0)
              { 
                $rubric_name=$out[$j][rubric_name]; 
      
                $memj=$j;           // запоминание индекса j
                $memind=$k;           // запоминание индекса первой картинки в текущей рубрике
                if ($j==0) $prehtmlrb="";
                $nir=0;
                $in_str=0;
      
                $memprehtmlrb=$prehtmlrb;
                $out[$j][prehtmlrb]=$prehtmlrb;
              } else {
                 $out[$j][rubric_name]=false; 
              }
//-------------- проверка смены рубрики конец --------------------------
      
             $lcount=$GallerySetting['CountFoto'];
             $curind=$k;
             $strrubric="&detail=yes&rubric=$rubric";
      
             if ($AmountImgsPage+1>$GallerySetting['CountFoto']) 
              {
               $NumStr=CEIL($AmountImgsPage/$GallerySetting['CountColumnG']);
               $Rest=($NumStr*$GallerySetting['CountColumnG'])-$AmountImgsPage;
               $RestStr='';
               for ($inr=0;$inr<$Rest;$inr++) { $RestStr.='<td>&nbsp;</td>'; }
               $prehtmlrb=$RestStr."</tr>";
               $memprehtmlrb=$prehtmlrb;
      
               $pages[$indp][selected]=false;
               if ($indp==$page) $pages[$indp][selected]=true;
      
               if ($indp==0) {
                 $pages[$indp][start]=0;
                 $pages[$indp][delimit]="";
                 $pages[$indp][count]=$lcount;
                 $pages[$indp][number]=$indp+1;
                 $pages[$indp][prehtmlrb]=$memprehtmlrb;
      
                 $pages[$indp][href]=$PHP_SELF."?page=0".$strrubric.$addtohref;
                } else {
                 $pages[$indp][delimit]=" - ";
                 $pages[$indp][start]=$pages[$indp-1][start]+$pages[$indp-1][count];
                 $out_show[$pages[$indp][start]][prehtmlrb]="";
                 $out[$pages[$indp][start]][rubric_name]=$rubric_name;
                 $pages[$indp][count]=$curind-$pages[$indp][start];
                 $pages[$indp][number]=$indp+1;
                 $pages[$indp][prehtmlrb]=$memprehtmlrb;
                 $pages[$indp][href]=$PHP_SELF."?page=$indp".$strrubric.$addtohref;
                }
      
               $AmountImgsPage=0;
               $nir=0;
               $indp++;
              }
             if ($in_str<$GallerySetting['CountColumnG']) 
              {
               if ($nir==0) {
                 $prehtml="<tr>";
               } else {
                 $prehtml="";
               }
               $in_str++;
              } else {
               $prehtml='</tr><tr><td colspan='.$GallerySetting['CountColumnG'].'><table width="100%" height="10"  border="0" cellpadding="0" cellspacing="0" class="d_razd"><tr><td height="10"></td></tr></table></td></tr><tr>';
               $in_str=1;
              }
             $out[$j]['column']=$GallerySetting['CountColumnG'];
             $out[$j][prehtml]=$prehtml;
             $out_show[$k]=$out[$j];
             $AmountImgsPage++;
             $nir++;
             $k++;
           }
      
         }
        $wsell=($GallerySetting['CountColumnG']==1?"100":ceil(abs(100/$GallerySetting['CountColumnG'])));   
        $RowStr='<tr>';
        for ($icol=0;$icol<$GallerySetting['CountColumnG'];$icol++) { $RowStr.="<td width=\"".$wsell."%\">&nbsp;</td>"; }
        $RowStr.='</tr>';
      
        $NumStr=CEIL($nir/$GallerySetting['CountColumnG']);
        $Rest=($NumStr*$GallerySetting['CountColumnG'])-$nir;
        $RestStr='';
        for ($inr=0;$inr<$Rest;$inr++) { $RestStr.='<td>&nbsp;</td>'; }
        $posthtmlrb=$RestStr."</tr>";
      
        $pages[$indp][selected]=false;
        if ($indp==$page) $pages[$indp][selected]=true;
      
        if($indp>0) {
          $pages[$indp][delimit]=" - ";
          $pages[$indp][start]=$pages[$indp-1][start]+$pages[$indp-1][count];
          $out_show[$pages[$indp][start]][preindetail]=false;
      
          $out_show[$pages[$indp][start]][prehtmlrb]="";
          $pages[$indp][count]=count($out_show)-$pages[$indp][start];
          $pages[$indp][number]=$indp+1;
          $pages[$indp][href]=$PHP_SELF."?page=$indp".$strrubric.$addtohref;
         } else { 
          $pages=false; 
         }
      
        if ( count($pages)>1&&$page<count($pages)-1 ) {
           $posthtmlrb=$pages[$page][prehtmlrb];
           $lastpreindetail=$out_show[$pages[$page+1][start]][preindetail];
           $lastprehref_indetail=$out_show[$pages[$page+1][start]][prehref_indetail];
         }
      
        $CountColumn=$GallerySetting['CountColumnG'];
        $value['column']=$CountColumn;
        $pages[$indp][start]=$pages[$indp-1][start]+$pages[$indp-1][count];
        $pages[$indp][count]=count($out_show)-$pages[$indp][start];
      
        $out_slice=array_slice($out_show,$pages[$page][start],$pages[$page][count]);
      
//------------------------- картинки под разрешения начало ----------------------
        foreach($out_slice as $in=>$val)
         { 
          $query_str="SELECT *,pa_name, DATE_FORMAT(ph_date,'DD.MM.YY') as date FROM parts,photogalery,photos WHERE pa_id=ph_rubric and ph_id=pg_ph_id";
          $query_str.=" and pg_ph_id=".$val[ph_id];
          $query_str.=" order by pg_sort";
      
          $query1->setQueryText($query_str);
          $result1=$query1->execQuery();
          $k=0;
          $photos_out=array();
          $is_photo=false;
          $out_slice[$in][HrefMiddlePhoto]=false;
          if ($connection1->CountTuples($result1)>0)  
            { for ($i=0;$i<$connection1->CountTuples($result1);$i++) 
               { 
                $phts=$connection1->fetchRow($result1,$i);
                if ($phts[pg_photo]!=NULL&&file_exists($img_gal_path.$phts[pg_photo]))
                 { 
                   $is_photo=true;
                   $photos_out[$k]=$phts;
                   $photos_out[$k]['photo']=$img_gal_path.$phts[pg_photo];
                   $photos_out[$k]['photo_path']=$A_images_path;
                   $photo_ingo=GetImageSize($img_gal_path.$phts[pg_photo]);
                   $photos_out[$k]['width']=$photo_ingo[0];
                   $photos_out[$k]['height']=$photo_ingo[1];
                   if (trim($phts[pg_res])!="")
                     $photos_out[$k]['resolution']=$phts[pg_res];
                   else
                     $photos_out[$k]['resolution']=$photo_ingo[0]."x".$photo_ingo[1];
      
                   $photos_out[$k][rubric]=$rubric;
                   $photos_out[$k]['hrefphoto']="javascript:viewfoto('".$PHP_SELF."?mod=gl&id=".$phts[pg_id]."',".$photo_ingo[0].",".$photo_ingo[1].",1,'photos')";
                   $photos_out[$k]['HrefMiddlePhoto']=$IncludePath."galery.php4?mod=gl&photo=".$phts[ph_id];
                   $photos_out[$k][pa_id]=$phts[pa_id];
                   $photos_out[$k][rubric_name]=$phts['pa_name'];
                   $photos_out[$k][name]=$phts['ph_header'];
                   $photos_out[$k][sort]=$phts['pg_sort'];
                   $k++;
                 }
               }
             if ($is_photo) $out_slice[$in][HrefMiddlePhoto]=$photos_out[0]['HrefMiddlePhoto'];
             $out_slice[$in][photo_imgs]=$photos_out;
            }
         }
//------------------------- картинки под разрешения конец ----------------------
        if($indp>0) {
         } else { 
          $pages=false; 
         }
        $value['action']=$PHP_SELF;
        $value['title']=$SitesSetting['Title'].$title;
        $value['entry']=$entry;
        $value['RowStr']=$RowStr;
        $value['photos']=$out_slice;
        $value['pages']=$pages;
        $value['content']=true;
      } else {
        $value['content']=false;
        $value['column']=$GallerySetting['CountFotoRubricG'];
      }
      $value['ImagesPath']=$A_images_path;
      $value['lpreindetail']=$lastpreindetail;
      $value['lprehref_indetail']=$lastprehref_indetail;
      
      $value['rubric']=$rubric;
      $value['isrubric']=true;
      $value['posthtmlrb']=$posthtmlrb;
   }

   $value['title']=$SitesSetting['Title'].$title;
   $value['entry']=$entry;
   $value['action']=$PHP_SELF;
   $value['IncludePath']=$IncludePath;

   exttemplate_printfile($IncludePath.$SitesSetting['Tpl'].$tpl,$value);
   require('func_include_down.php');
 } //end if (isset($id))
?>
