###############################################################################
# BizDesign ImageFolio Lite Edition 4.2 (Four-dot-Two)
###############################################################################
#
#          ##          ###        VERSION       :  4.2
#        ####        ##   ##      RELEASED ON   :  02/15/2007
#      ##  ##              ##     LAST MODIFIED :  02/15/2007
#    ##########          ##       
#          ##   ###    ##         
#          ##   ###  ########     
#
###############################################################################
# Released by BizDesign, Inc.
# written by Dirk Koppers and Greg Raaum of BizDesign
#
# Purchasing :  http://imagefolio.com/purchase/
# Support    :  http://imagefolio.com/support/
# Phone      :  (214) 642-9787
# Email      :  sales@bizdesign.com
###############################################################################
# COPYRIGHT AND LICENSE INFORMATION :
#
# Copyright (c) 1999-2007 BizDesign, Inc. All rights reserved.
#
# Selling or distributing the code for this program without prior written
# consent is expressly forbidden.
#
# One licensed copy of the program may reside on a single server, in use by a
# single domain.  For each installed instance of the program, a separate
# license is required.
#
# Licensed users may alter or modify this software, at their own risk, of
# course.  They may also hire others to modify their own copy of the code, as
# long as the code is not transferred to or retained by the individual who is
# hired (unless he/she is also a license holder). Although license-holders
# may modify the code for their use, modified code may NOT be resold or
# distributed.
#
# THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BIZDESIGN,
# INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# BizDesign, Inc. is not liable for any conduct associated with image gallery
# activity, nor for any binary media posted using this program, including but
# not imited to images, photographs, movies, and clipart.
#
# The user must assume the entire risk of using the program.  Although this
# program has been thoroughly tested on BizDesign's servers, BizDesign does not
# warrant that it works on all servers and will not be held liable for anything,
# including but not limited to, misusage, error, or loss of data.  ANY
# LIABILITY OF THE SELLER WILL BE LIMITED EXCLUSIVELY TO PRODUCT REPLACEMENT
# OR REFUND OF PURCHASE PRICE.  Use at your own risk!
###############################################################################
# Do not modify below this line unless you know what you are doing.
###############################################################################

###############################################################################
# GEN IMAGE TABLE
# Makes the all important table containing images and image data
###############################################################################
sub gen_image_table {

   require "$libpath/thumbnails.pl";

   if (-e "$image_directory/$FORM{'direct'}/thumbnails.html") {
      $thumb_template = "$image_directory/$FORM{'direct'}/thumbnails.html";
   }



   &build_pull_down_menu;
   &parse_image_directory;
   &build_subcategory_list;
   $path = $FORM{'direct'};
   if ($if2_thumbcaption) {
      &get_thumbcaps;
   }
   &build_thumbnail_table;
   &build_nextprev_links;
   &build_nav;
   $pagelinks = build_title_linked($FORM{'direct'});

   if (-e "$image_directory/$FORM{'direct'}/thumbnails.html") {
     $thumb_template = "$image_directory/$FORM{'direct'}/thumbnails.html";
   }

   &get_template;

}

###############################################################################
# PARSE IMAGE DIRECTORY
# navigate to the image directory and read in all files and subdirectories
###############################################################################
sub parse_image_directory {


   $cachefilename = "direct~$FORM{'direct'}";
   $cachefilename =~ s/[^0-9a-zA-Z\_]/~/g;
   $cachefilename .= "~sort5" if ($sortfiles == 5);
   $cacheloc = "$cache_directory/searches/$cachefilename";

   @names = ();
   @db_lines = ();
   @idx = ();
   @subdirectories = ();
   $totalnames = ();
   $found = ();

   if (-e "$cacheloc") { 
      if ((-M "$cacheloc" <= $cache_date) && !$force_cachereload) { 
         &get_direct_cache;
      }
      else { 
         &creat_direct_list;
      }
   }
   else {
      &creat_direct_list;
   }

   sub creat_direct_list {
      @idsort = ();
      opendir(IMAGEDIR,"$image_directory/$FORM{'direct'}")or &Error("Error Reading Directory: $!");
      @files = readdir(IMAGEDIR);
      closedir(IMAGEDIR);

      foreach $file (@files) {
         if ( -d "$image_directory/$FORM{'direct'}/$file" ) {   # make sure this really is a directory
            chop $file if ($file =~ /\/$/);
            next if $file =~ /^\.\.?$/;                   # weed out all .. directories
            next if $file =~ /_vti_cnf/i;                  # weed out front page directories
            push(@subdirectories, $file);                  # put the subdirectories in an array
            $found = "1";                              # if we found a good directory
         }
         else{
            if ($file =~ /^$mypattern/i ) {
               &add_this_to_list;
            }
#            elsif ( -B "$image_directory/$FORM{'direct'}/$file" && ($file !~ /^$mypattern_fullsize/i) && ($file ne "_category_image.jpg") && ($file ne 'index.html')) {
            elsif ($file !~ /^$mypattern_fullsize/i && $file !~ /(_category_image\.jpg|index\.html|\.count|\.vote)$/i) {
               my ($shortname) = $file =~ m,^(.*)\.\w+$,;
               if (-e "$image_directory/$FORM{'direct'}/$mypattern$shortname.jpg" or
                   -e "$image_directory/$FORM{'direct'}/$mypattern$shortname.JPG" or
                   -e "$image_directory/$FORM{'direct'}/$mypattern$shortname.gif" or
                   -e "$image_directory/$FORM{'direct'}/$mypattern$shortname.GIF" ) { # do nothing
               }
               else {
                  my ($extension) = ($file =~ /\.([^.]+)$/);
                  next if !exists($extensions{lc($extension)});
                  &add_this_to_list;
               }
            }
         }
      }
      sub add_this_to_list {
         $filedate = ();
         $my_count = ();
         $my_votes = ();
         $my_rates = ();
         &find_size_date($FORM{'direct'}, $file);
         ($name_base) = $file =~ m,^(.*)\.\w+$,;
         $name_base =~ s/^$mypattern//ig;
         my $countfile = qq|$image_directory/$FORM{'direct'}/$name_base.count|;
         if (-e $countfile) {
            open (FILE,"$countfile");
            while (<FILE>) {
               ($my_count) = split(/\t/, $_);
               last;
            }
            close(FILE);
         }
         my $votefile = qq|$image_directory/$FORM{'direct'}/$name_base.vote|;
         if (-e $votefile) {
            open (FILE,"$votefile");
            while (<FILE>) {
               ($my_votes, $my_rates) = split(/\t/, $_);
               last;
            }
            close(FILE);
         }
         push(@db_lines, "$filedate\t$file\t$my_count\t$my_rates\t$my_votes");
         push(@idsort, $name_base);
      }

      if ($found) {
         @subdirectories = sort { lc($a) cmp lc($b) } @subdirectories;
      }

      if (($sortfiles == 5) && @db_lines) {
          &shuffle_direct(\@db_lines);
      }
      else {
         @db_lines = @db_lines[ sort { lc($idsort[$a]) cmp lc($idsort[$b]) } 0 .. $#idsort ];
      }

      open (CACHE,">$cacheloc") or &Error("Unable to create cache file at $cacheloc: $!");
      foreach $subdirectory (@subdirectories) {
         print CACHE "subdirectory\t$subdirectory\t\n";
      }
      foreach $db_line (@db_lines) {
         print CACHE "$db_line\t\n";
      }
      close(CACHE);
      chmod(0666,"$cacheloc");

      @db_lines = ();
      @subdirectories = ();
      &get_direct_cache
   }

   sub get_direct_cache {
      open (FILE,"$cacheloc") or &Error("Can't Open $cacheloc: $!");
      while (<FILE>) {
         my ($filedate, $file, $my_count, $my_rates, $my_votes) = split(/\t/, $_);
         if ($filedate eq 'subdirectory') {
            push(@subdirectories, $file);
            $found = 1;
         }
         else {
            push(@db_lines, "$filedate\t$file\t$my_count\t$my_rates\t$my_votes");
            if ($sortfiles == 3) {
               push(@idx, $my_count);
            }
            elsif ($sortfiles == 4) {
               push(@idx, $my_rates);
            }
         }
      }
      close(FILE);
   }

   sub shuffle_direct {
      my $db_lines = shift;
      my $l;
      for ($l = @$db_lines; --$l; ) {
         my $m = int rand ($l+1);
         next if $l == $m;
         @$db_lines[$l,$m] = @$db_lines[$m,$l];
      }
   }

   if ($sortfiles == 1) {
      @names = sort { $b <=> $a } @db_lines;
   }
   elsif (($sortfiles == 2) or ($sortfiles == 5)) {
      @names = @db_lines;
   }
   elsif (($sortfiles == 3) or ($sortfiles == 4)) {
      @names = @db_lines[ sort { $idx[$b] <=> $idx[$a] } 0 .. $#idx ];
   }

   $totalnames=@names;
   @files = ();
}

###############################################################################
# BUILD SUBCATEGORY LIST
# if subdirectories were found, we build a 2 column linked list of those found
###############################################################################
sub build_subcategory_list {

   unless (!$found) {

      if ($maxsubdirectory) {
         &create_sub_cat_pagelinks;
      }

     $i=0;
     $j=0;

   $total_categories = $#subdirectories;

   if ($cat_columns == 2) {
      ($half) = int (($total_categories+2) / 2);
      $cat_column_width = 'width="50%"';
   }
   elsif ($cat_columns == 3) {
      ($half) = int (($total_categories+3) / 3);
      $cat_column_width = 'width="33%"';
   }
   else {
      $cat_column_width = 'width="100%"';
   }

   if (($FORM{'direct'} eq $current_cat_root) && $using_picturepost_mod) {
      require "$config_directory/post_config.pl";
      if ($main_users_cat eq $FORM{'direct'}) {
         $subcategories_name = "$main_users_cat Categories";
      }
      else {
         $subcategories_name = "Subcategories";
      }
   }
   else {
      $subcategories_name = "Subcategories";
   }
   $subcatlinks = ();

   $subcatlinks .= qq|
     <tr bgcolor="$main_header_bgcolor">
       <td>$hrstuff
         <table border="0" width="100%" cellspacing=0 cellpadding=4>
           <tr>
             <td align="$pagelinks_alignment"><font $main_header_font><b>$subcategories_name</b></font></td><td align=right>&nbsp;$d_page_links</td>
           </tr>
         </table>$hrstuff
       </td>
     </tr>| if !$do_cat_search;
   $subcatlinks .= qq|
     <tr bgcolor="$subcat_bgcolor">
       <td valign=top>
         <table border="0" width="100%" cellspacing=0 cellpadding=6>
           <tr>
             <td $cat_column_width valign=top>
               <table border=0 cellspacing=1 cellpadding=3 width="100%">|;

     $columncat = ();
     
     foreach $directory (@subdirectories) {
        if ($do_cat_search) {
            ($directory, $newcount, $newdate) = split(/\|/, $directory);
            $catmatch = $directory;
        }
        else {
           $catmatch = $FORM{'direct'} . "/$directory";
        }

       $ttcount = 0;
       $mydirectory = &get_clean_name($directory);    #remove underscores and replace slashes

       &create_category_column;

       $i++;
       $imagecount = "";
     }

     &create_jsrollovers;

     $subcatlinks .= $columncat;

     $subcatlinks .= qq|
               </table>
             </td>
           </tr>
         </table>
       </td>
     </tr>
     |;
   }
}

###############################################################################
# BUILD NEXTPREV LINKS
# Generate links to additional image pages and next/previous links if necessary
###############################################################################
sub build_nextprev_links {

   $num = $totalnames;
   $calc = int(($num / $numtolist) + '0.99');
   if (!$numtolist) { $numtolist = 10; }
   $base = $numtolist;
   $factor_min = $FORM{'img'} - ($pages_ahead_count * $numtolist);
   $factor_plus = $FORM{'img'} + ($pages_ahead_count * $numtolist);

   if (!$FORM{'img'} or $FORM{'img'} eq "0") {
     $FORM{'img'} = "0";
     $nextfactors = $numtolist;
     $nextlinks .= qq|(<b>1</b>) |;
     $thisfactor = 1;
   }
   elsif ($factor_min <= 0 ) {
      $nextlinks .= qq|<b><a href="$imagefolio_url?direct=$FORM{'direct'}&img=0">1</a></b> |;
   }


   foreach $factor(2..$calc) { 
      $factors = (($base * $factor) - $base);

      if ($FORM{'img'} == $factors) {
         $nextfactor = $factor + 1;
         $nextfactors = (($base * $nextfactor) - $base);
         $prevfactor = $factor - 1;
         $prevfactors = (($base * $prevfactor) - $base);
         $thisfactor = $factor;
         $nextlinks .= qq|(<b>$factor</b>) |;
      }
      elsif (($factors >= $factor_min) && ($factors <= $factor_plus)) {
         $nextlinks .= qq|<b><a href="$imagefolio_url?direct=$FORM{'direct'}&img=$factors">$factor</a></b> |;
      }

   $lastfactor = $factor;
   }


   if ($lastfactor > $thisfactor) {
     $next_page_link = "$imagefolio_url?direct=$FORM{'direct'}&img=$nextfactors";
     $nextpage = qq|<a href="$imagefolio_url?direct=$FORM{'direct'}&img=$nextfactors">Next [&gt;&gt;]</a>|;
   }
   else {
     $next_page_link = "";
     $nextpage = "";
   }

   if (!$FORM{'img'} or $FORM{'img'} eq "0") {
     $previous_page_link = "";
     $prevpage = "";
   }
   else {
     $previous_page_link = "$imagefolio_url?direct=$FORM{'direct'}&img=$prevfactors";
     $prevpage = qq|<a href="$imagefolio_url?direct=$FORM{'direct'}&img=$prevfactors">[&lt;&lt;] Prev</a> |;
   }

   if ($num > $numtolist) { $page = "pages"; }
   else { $page = "page"; }

   if ($most = $SIZE) {
      if ($quickdisplay) {
         $pageinfo = qq|$num files found|;
      }
      else {
         $pageinfo = qq|$num files found on $calc $page.<br>Displaying $numtolist files per page.<br>|;
      }
   }
}

###############################################################################
# BUILD NEXTPREV LINKS FOR SUBCATEGORIES
# Generate links to additional subcategories if necessary
###############################################################################
sub create_sub_cat_pagelinks {
   @subdirectories_temp = ();
   $totaldirect = @subdirectories;
   $d_factor = ($totaldirect / $maxsubdirectory);
   if ($d_factor > 1) {
      ($d_factor_count, $deci) = split(/\./,$d_factor);
#      $d_pages = ($d_factor_count + 1);
      $d_pages = ($d_factor_count);
      $d_pages += 1 if $deci;

      if (!$FORM{'cdp'}) {
         $FORM{'cdp'} = 1;
         $start_count = 0;
      }
      else {
         $start_count = (($FORM{'cdp'} - 1) * $maxsubdirectory);
      }
      if ($start_count > $totaldirect) {
         $FORM{'cdp'} = 1;
         $start_count = 0;
      }
      $target_count = ($start_count + $maxsubdirectory);
      if ($target_count > $totaldirect) {
         $target_count = $totaldirect;
      }

      for ($k=$start_count;$k<$target_count;$k++) {
         push(@subdirectories_temp, @subdirectories[$k]);
      }

      if ($FORM{'cdp'} > 1) {
         $prev = ($FORM{'cdp'} - 1);
         $d_page_links .= qq|<a href="$imagefolio_url?direct=$FORM{'direct'}&cdp=$prev"><$font>[&lt;&lt;] Prev</font></a>&nbsp;&nbsp;|;
      }

      for ($m=1;$m<=$d_pages;$m++) {
        if ($m == $FORM{'cdp'}) { $d_page_links .= qq|<$font>(<b>$m</b>)</font>&nbsp;&nbsp;|; }
        elsif (($m > $FORM{'cdp'} && $m < ($FORM{'cdp'} + $subcat_ahead_count)) or ($m < $FORM{'cdp'} && $m > ($FORM{'cdp'} - $subcat_ahead_count))) { $d_page_links .= qq|<b><a href="$imagefolio_url?direct=$FORM{'direct'}&cdp=$m"><$font>$m</font></a></b>&nbsp;&nbsp;|; }
      }

      if ($FORM{'cdp'} < $d_pages) {
         $next = ($FORM{'cdp'} + 1);
         $d_page_links .= qq|<a href="$imagefolio_url?direct=$FORM{'direct'}&cdp=$next"><$font>Next [&gt;&gt;]</font></a>|;
      }
      @subdirectories = @subdirectories_temp;
   }
}


1;

