############################################################
#
# shite_pages.pl
#
# Functions which are responsible for drawing a Shitespace page
#
############################################################

#require "shite_html.pl";
require "shite_vote.pl";

use File::Basename;

#sub sortbytitle { $shiteHash->{$a}->{title} cmp $shiteHash->{$b}->{title}; }
sub sortbytitle { $a->{title} cmp $b->{title}; }

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

sub shite_title         # all Shitespace pages' HTML starts here
{
    my ($title, $description) = @_;

    $title = "Shitespace: " . $title;
    $description = "The most puerile site on the internet" if ($description eq "");

    print <<EOT;
Content-type: text/html

<html>
<head>
  <title>$title</title>
  <meta name="Author" content="Shite Publications">
  <meta name="Description" content="$description">
  <meta name="Keywords" content="mike, kate, prospects, k-days, kday, events,
              poetry, poems, humour, humor, literature, poo, pooclub, poo club, shite,
              shiterati, poetry, poems, humour, humor, literature">
  <link type="text/css" rel="stylesheet" href="${CSSDIR}/tripe_style.css" />	
</head>

<body style="background-color: #f0ece0;" text="black" link="brown" vlink="#806050">



    <table border="0" width="750" cellspacing="0" cellpadding="0" align="center"
           style="background-color: white;" />
     <tr>
      <td align="left" valign="top">




<!--------- Header Banner ---------------->
<table width="100%" bgcolor="brown" align="left" border="0"
 cellpadding="0" cellspacing="0">
 <tr>
  <td class="menulink" align="left" width="50">
   &nbsp;
  </td>
  <td class="menulogo" align="left">
   <b class="menulogo">Shite</b>space
  </td>
  <form method="get" action="http://www.google.com/custom">
   <input type="hidden" name="domains" value="shite.org">
   <input type="hidden" name="sitesearch" value="shite.org">
  <td class="menulink" align="right" valign="middle" color="white" bgcolor="brown">
   <table align="right" border="0">
    <tr>
     <td align="left">
      <input type="text" name="q" value="" size="31" maxlength="255">
      <input type="submit" name="sa" value="Search">
     </td>
    </tr>
    <tr>
     <td class="menulink" align="left">
      <a class="menulink" href="${THIS_CGI}?p=shite">Home</a> |
      <a class="menulink" href="${THIS_CGI}?p=archives">The Bowels</a> |
      <a class="menulink" href="${THIS_CGI}?p=authors">The Authors</a> |
      <a class="menulink" href="${THIS_CGI}?p=index">Index</a> |
      <a class="menulink" href="${THIS_CGI}?p=map">Map</a>
     </td>
    </tr>
   </table>
  </td>
  </form>
 </tr>
</table><br clear="all">
<!--------- /Header Banner ---------------->

EOT
}

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

sub shite_menubar       # the brown menubar at the bottom of every Shitespace page
{
    print qq(

<!--------- Footer Bar ---------------->
<table width="100%" bgcolor="brown" align="left" border="0"
 cellpadding="0" cellspacing="0">
 <tr>
  <td class="menulink" align="left" width="50">
   &nbsp;
  </td>
  <td class="barlogo" align="left">
   <b class="barlogo">Shite</b>space
  </td>
  <td class="menulink" align="right" valign="middle" color="white" bgcolor="brown" zzwidth="300">
   <table align="right" border="0">
    <tr>
     <td class="menulink" align="left">
      <a class="menulink" href="${THIS_CGI}?p=shite">Home</a> |
      <a class="menulink" href="${THIS_CGI}?p=archives">The Bowels</a> |
      <a class="menulink" href="${THIS_CGI}?p=authors">The Authors</a> |
      <a class="menulink" href="${THIS_CGI}?p=index">Index</a> |
      <a class="menulink" href="${THIS_CGI}?p=map">Map</a>
      &nbsp;&nbsp;&nbsp;
     </td>
    </tr>
   </table>
  </td>
 </tr>
</table>
<!--------- /Footer Bar ---------------->





</td></tr></table>



    );
}

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

sub shite_menubar_oldish       # the brown menubar at the bottom of every Shitespace page
{
    print <<EOT;
<!--------- Menu bar ---------------->
<table width="100%" bgcolor="brown" align="left" border="0"
 cellpadding="0" cellspacing="0">
 <tr>
  <td align="center" valign="middle" width="50">
   <a href="$THIS_CGI?p=shite&$date_args">
   <img src="$IMGDIR2/left.gif" alt="Home" border="0" width="15"></a>
  </td>

  <td align="center" valign="bottom" bgcolor="#ffffc0" width="200">
   <a href="$THIS_CGI?p=shite&$date_args"><img src="$IMGDIR2/logob.gif" alt="Home" border="0"></a>
  </td>

  <td align="left" valign="middle" color="white" bgcolor="brown" width="250">
   <nobr>
   &nbsp;
   <a href="$THIS_CGI?p=archives&$date_args">
    <font face="arial,times" size="2" color="white">The Bowels</font></a>
    <font face="arial,times" size="2" color="white"> | </font>
   <a href="$THIS_CGI?p=authors&$date_args">
    <font face="arial,times" size="2" color="white">The Authors</font></a>
   </nobr>
  </td>

  <td align="right" valign="middle" color="white" bgcolor="brown" width="100%">
   <nobr>
   <a href="$THIS_CGI?p=index&$date_args">
    <font face="arial,times" size="2" color="white">Index</font></a>
    <font face="arial,times" size="2" color="white"> | </font>
   <a href="$THIS_CGI?p=pages&$date_args">
    <font face="arial,times" size="2" color="white">Map</font></a>
   &nbsp;&nbsp;
   </nobr>
  </td>
 </tr>
</table>
EOT
}

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

sub shite_menubar_old       # the brown menubar at the bottom of every Shitespace page
{
    print <<EOT;
<!--------- Menu bar ---------------->
<table width="100%" bgcolor="brown" align="left"
 cellpadding="0" cellspacing="0">
 <tr>
  <td align="center" valign="middle" width="50">
   <a href="$THIS_CGI?p=shite&$date_args">
   <img src="$IMGDIR2/left.gif" alt="Home" border="0" width="15"></a>
  </td>

  <td align="center" valign="middle" bgcolor="beige" width="200">
   <a href="$THIS_CGI?p=shite&$date_args"><img src="$IMGDIR2/logob.gif" alt="Home" border="0"></a>
  </td>

  <td align="right" valign="middle" color="white" width="100%">
   &nbsp;
   <a href="$THIS_CGI?p=authors&$date_args">
    <font face="times" size="3" color="white">Authors</font></a>
    <font face="times" size="3" color="white"> | </font>
   <a href="$THIS_CGI?p=archives&$date_args">
    <font face="times" size="3" color="white">Archives</font></a>
   &nbsp;&nbsp;
  </td>
 </tr>
</table>
EOT
}

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

sub multipage_menu      # displays the "Title Page 1 2 3 4 5 Next" menu
{
    my ($title, $baseId, $partName, $pageNum, $numPages) = @_;

    if ($pageNum > 0 && $numPages > 1)
    {
        print <<EOT;
          <br>
          <font face="verdana,arial,times" size="3" color="brown">
           <b>$title</b><br>
          </font>
          <font face="verdana,arial,times" size="3" color="black">
           $partName&nbsp;
EOT
        for ($i = 1; $i <= $numPages; $i++)
        {
            if ($i == $pageNum)
            {
                print " <b>$i</b>";
            }
            else
            {
                print <<EOT;
                <a href="$THIS_CGI?p=$baseId$i&$date_args">$i</a>
EOT
            }
        }

        if ($pageNum < $numPages)
        {
            $next = $pageNum+1;
            print <<EOT;
            &nbsp;&nbsp;&nbsp;<a href="$THIS_CGI?p=$baseId$next&$date_args"><b>Next</b><img src="$IMGDIR2/right.gif" alt="
Next" border="0" width="12"></a>
EOT
        }

        print "</font>";
    }
}

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

sub cannot_find_shitem  # displays "Oops!" message in place of a missing poem or short story
{
    my ($shiteId, $title, $author) = @_;
    print <<EOT;
 <!--- $title --->
 <tr>
  <td align="left" valign="top" width="$marginwidth">
   <font face="times,arial,verdana" size="3" color="brown"><i>
    $margintext
   </i></font>
  </td>
  <td align="left" valign="top" width="$poemwidth">
   <a name="$shiteId"></a>
   <font face="arial" size="4" color="brown"><b>
    $title
   </b></font>
    <br>
   <font face="times" size="2"><i>($author)</i></font><br><br>
   <font face="times" size="5"><i>Oops!</i></font><br>
   <font face="times,arial" size="3"><i>
   Cannot find shite file for this item.  Please complain bitterly to
   <a href="mailto:shite\@shite.org">shite\@shite.org</a>
   quoting shite Id "$shiteId".</i>
   <br>
EOT
}
############################################################

sub cannot_find_poem_of_the_day
{
    my ($shiteId, $title, $author) = @_;
    print <<EOT;
   <font face="times" size="5"><i>Oops!</i></font><br>
   <font face="times,arial" size="3"><i>
   Cannot find shite file for this item.  Please complain bitterly to
   <a href="mailto:shite\@shite.org">shite\@shite.org</a>
   quoting shite Id "$shiteId".</i>
   <br>
EOT
}

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

sub get_description
{
    my ($category, $altTitle) = @_;
    my $description = "";

    $category = uc($category);
    $description = "";
    $description = "Not Released"        if ($category eq "N");
    $description = "An Anthology Of Poetry" if ($category eq "A");
    $description = "The Shiterati"      if ($category eq "R");
    $description = "A Short Story"         if ($category eq "S");
    $description = "The Bible"          if ($category eq "B");
    $description = "A Shitespace Epic"           if ($category eq "E");
    $description = "Tales From Beyond The Enchanted Prong Hills"   if ($category eq "H");
    $description = "Parochial Plops" if ($category eq "L");
    $description = "War Poetry" if ($category eq "W");
    $description = "Crappalot's Page"    if ($category eq "C");
    $description = "Splashback! Behind The Scenes"            if ($category eq "Y");
    $description = ""            if ($category eq "X");

    if ($altTitle ne "")
    {
        if ($category eq "X" || $category eq "E")
        {
            $description = $altTitle;
        }
    }

    return $description;
}

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

sub get_image           # gets the full pathname of an image for a shitem
{
    my ($shiteId, $imageCode) = @_;

    my $imageFile = "";
    my $foundImage = 0;
    $imageCode =~ s/\s+//g;

    my ($fname, $path, $suffix) = fileparse($imageCode, '\..*');
#print "FISH: imageFile=$imageFile fname=$fname path=$path suffix=$suffix\n";
    my $id = $fname;
    $id     =~ s/$suffix$//;
    $id     =~ s/\.$//;       # remove trailing .
    $path   =~ s/\/$//;       # remove trailing /
    $suffix =~ s/^\.//;       # remove preceding .
    my $dir = basename($path);
#print "FISH: path=$path dir=$dir id=$id suffix=$suffix\n";


    if ($suffix ne "")
    {
        $id = $shiteId if ($id eq "");

        if ($dir eq "" || $dir eq ".")
        {
            $dir = "$IMGSHITEDIR";
        }
        else
        {
            $dir = "$IMGHOMEDIR/$dir";
        }

        $imageFile = "${dir}/${id}.${suffix}";
    }
    elsif ($imageCode ne "")  # the imageCode hasn't parsed so assume that it is a suffix only
    {
        $imageFile = "$IMGSHITEDIR/${shiteId}.${imageCode}";
    }


#    if ($id ne "" && $suffix ne "" && ($dir eq "" || $dir eq "."))  # filename is given but no dir (eg $imageFile="parsnip.jpg")
#    {
#        $imageFile = "$IMGSHITEDIR/$imageFile";  # ...so use default dir
#print "FISH2\n";
#    }
#    elsif ($imageFile ne "")                # only the file extension (image type) is given (eg $imageFile="jpg")
#    {
#        $imageFile = "$IMGSHITEDIR/$shiteId.$imageFile";  # ...so use shiteId as filename
#print "FISH3\n";
#    }
#    else   # assume full path is given (eg $imageFile="images1/horse.gif")
#    {
#        $imageFIle = "$IMGHOMEDIR/$imageFile";
#print "FISH1\n";
#    }

    $foundImage = 1 if ($imageFile ne "");

    if ($foundImage < 1)
    {
        # No image has been provided by the shite index table, but let's see if
        # we can find one anyway in $IMGSHITEDIR that matches the shite id.

        $imageFile = "$IMGSHITEDIR/$shiteId.gif" if (-s "$IMGSHITEDIR/$shiteId.gif" > 0);
        $imageFile = "$IMGSHITEDIR/$shiteId.jpg" if (-s "$IMGSHITEDIR/$shiteId.jpg" > 0);
        $foundImage = 1 if ($imageFile ne "");
    }

    if ($foundImage < 1)  # The -s file flag doesn't seem to work on titanhosts
    {                     # so let's try a messier approach...

        open (GIFFD, "$IMGSHITEDIR/$shiteId.gif") or $foundImage = 0;
        close (GIFFD);

        if ($foundImage > 0)
        {
            $imageFile = "$IMGSHITEDIR/$shiteId.gif";
        }
        else
        {
            $foundImage = 1;
            open (JPGFD, "$IMGSHITEDIR/$shiteId.jpg") or $foundImage = 0;
            close (JPGFD);

            if ($foundImage > 0)
            {
                $imageFile = "$IMGSHITEDIR/$shiteId.jpg";
            }
        }
    }

    return $imageFile;
}

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

sub show_shitem         # generates HTML for a poem or short story within a page
{
    my ($type, $shiteId, $title, $author, $imageCode, $marginwidth, $poemwidth, $rightcolwidth) = @_;

    $marginwidth   = 195 if ($marginwidth eq "" || $marginwidth < 1);
    $poemwidth     = 500 if ($poemwidth eq "" || $poemwidth < 1);
    $rightcolwidth = 105 if ($rightcolwidth eq "" || $rightcolwidth < 1);
    $border        = 0;
    my $lines = 0;
    my $textlines = 0;   # non-blank lines
    $margintext = "";
    $rightcoltext = "";

    my $dir = $POETRYDIR;
    $dir = $STORYDIR if ($type eq "S");
    my $shitemFile = "$dir/$shiteId" . ".txt";

    my $imageFile = get_image ($shiteId, $imageCode);
    my $imageText = "";

    if ($imageFile ne "")
    {
        $imageText = qq(
            <img src="$imageFile" alt="$title" width="$marginwidth">
            <br clear="all"><br>
        );
    }


    # Now start reading shitem file

    open (SHITEM, $shitemFile) or cannot_find_shitem($shiteId, $title, $author);

    while (<SHITEM>)
    {
        chop;
        next if (/^#/);                      # comment line
        next if (/^\s*$/ && $textlines < 1); # blank line before start of text

        substitute_vars (\$_);
        add_date_args_to_link (\$_);

        if ($_ =~ /^\//)  # It's a data formatter
        {
            $dataname = $_;
            $datatext = $_;
            $dataname =~ s/^\///;         # cut preceding /
            $dataname =~ s/\s+.*$//;      # cut all text after dataname
            $datatext =~ s/^\/\w+\s*//;   # cut /dataname
            $$dataname = $datatext;
            next;
        }
        else
        {
            $textlines++;

            if ($textlines == 1)   # It's the first line so print the title, author etc.
            {
                $displayAuthor = "";
                $displayAuthor = "$author" if ($author ne "");

                print <<EOT;
                 <!--- $title --->
                 <tr>
                  <td align="left" valign="top" width="$marginwidth">
                   <div class="itemMargin">
                    $margintext
                    $imageText
                   </div>
                  </td>
                  <td class="itemText" align="left" valign="top" width="$poemwidth">
                   <a name="$shiteId"></a>
EOT

                if (lc($type) eq $type)     # It's information about a page
                {
                     print <<EOT;
                    <div class="aboutText">
EOT
                }
                else    # It's a normal poem (or story) so show title
                {
                    print <<EOT;
                   <div class="itemTitle">$title</div>
                   <div class="itemAuthor">$displayAuthor</div><br>
                   <div class="itemText">
EOT
                }

            }
    
            # Now print the line
            if (uc($type) eq "P")
            {
                print "$_<br>\n";
            }
            elsif (uc($type) eq "S")
            {
                print qq(<p class="itemText">) if ($_ =~ /^\s*$/);          # blank line
#                print "&nbsp;&nbsp;" if ($_ =~ /^\s+/);  # indented start of paragraph

                if ($_ =~ /^\s+\S/)  # indented start of paragraph
                {
                    print <<EOT;
<table><td cellpadding="5"></td></table><table align="left"><td cellpadding="5"></td></table>
EOT
                }
                print "$_\n";
            }
            else
            {
                print "$_<br>\n";
            }
        }
    }

    close (SHITEM);

    print "<br>" if ($type eq "S");
 #   print "</i>" if (lc($type) eq $type);

    print <<EOT;
    <br>
   </div>
EOT

    if ("$rightcoltext")
    {
        print <<EOT;
         <div class="itemMargin" align="right">
           $rightcoltext
         </div>
EOT
    }

    print <<EOT;
  </td>
  <td align="left" valign="bottom" width="$rightcolwidth">
   &nbsp;
<!------------------------
   <font face="times,arial,verdana" size="3" color="brown">
    $rightcoltext
   </font>
--------------------->
  </td>
 </tr>

EOT
}

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

# should be renamed "single_author_page"

sub anthology_page      # generates an anthology or short stories page
{
    my ($myPageId, $pageTitle, $altTitle, $date, $category, $pageNum, $numPages) = @_;
    my $pTitle = $pageTitle;
    $pTitle = $altTitle if ($altTitle ne "");
    my $pDescription = get_description ($category, $altTitle);
    my $returnLink = "";

    shite_title ("$pageTitle", "$pDescription");

    print <<EOT;
<table border="0" bgcolor="white" align="left" bordersize="0" 
 cellspacing="0" cellpadding="10">

 <!--- Anthology Title --->
 <tr>
  <td align="left" valign="top" width="195">
EOT

    if (uc($category) eq "R")  # Add link back to Shiterati homepage
    {
        $returnLink = qq(
     <font face="verdana,arial,times" size="3">
     <a href="$THIS_CGI?p=shiterati&$date_args"><img src="$IMGDIR2/left.gif" alt="Shiterati Home" border="0" width="12">The Shiterati</a>
     </font>
);

        $pTitle = "Shiterati: " . $pTitle;
    }

    if (uc($category) eq "L")  # Add link back to Parochial Plops homepage
    {
        $returnLink = qq(
     <font face="verdana,arial,times" size="3">
     <a href="$THIS_CGI?p=parochial&$date_args"><img src="$IMGDIR2/left.gif" alt="Parochial Plops Home" border="0" width="12">Parochial Plops</a>
     </font>
);
    }


    if (uc($category) eq "W")  # Add link back to War Poetry homepage
    {
        $returnLink = qq(
     <font face="verdana,arial,times" size="3">
     <a href="$THIS_CGI?p=war_poetry&$date_args"><img src="$IMGDIR2/left.gif" alt="War Poetry Home" border="0" width="12">War Poetry</a>
     </font>
);
    }

    print <<EOT;
      $returnLink
  </td>
  <td align="left" valign="top">
   <div class="pageTitle">$pTitle</div>
EOT

    if ($pageNum > 0 && $numPages > 0)  # It's a multi-page anthology
    {
        print <<EOT;
            <p><font face="verdana,arial,times" size="3">Volume $pageNum</font>
EOT
    }

    print <<EOT;
  </td>
  <td align="left" valign="top" width="105">
   &nbsp;
  </td>
 </tr>
EOT


    open (SHITE, $SHITE_INDEX_FILE) or die "anthology_page: Cannot open SHITE_INDEX_FILE=$SHITE_INDEX_FILE\n";

    while (<SHITE>)
    {
        chop;
        next if (/^#/);       # comment line
        next if (/^\s*$/);    # blank line

        ($potd, $type, $shiteId, $shiteTitle, $author, $pageId, $imageCode) = split /;/, $_;

        $potd =~ s/\s+//g;
        $type =~ s/\s+//g;
        $shiteId =~ s/\s+//g;
        $pageId =~ s/\s+//g;
        $shiteTitle =~ s/^\s*//;
        $shiteTitle =~ s/\s*$//;
        $author =~ s/^\s*//;
        $author =~ s/\s*$//;
        $imageCode =~ s/^\s*//;
        $imageCode =~ s/\s*$//;

        if ($pageId eq $myPageId)     # print this shitem
        {
            show_shitem ($type, $shiteId, $shiteTitle, $author, $imageCode);
        }
    }

    close (SHITE);

    my $baseId = $myPageId;
    $baseId =~ s/\d+$//;
    my $pubDate = "";  # Format the publication date

    if ($date =~ /\-/)    # Range of dates
    {
        my ($date1, $date2) = split /-/, $date;
        my ($dow1, $day1, $month1, $year1) = split /;/, parse_date($date1);
        my ($dow2, $day2, $month2, $year2) = split /;/, parse_date($date2);
        $year1 = "" if ($year1 eq $year2);
        $pubDate = "$month1 $year1 - $month2 $year2";
    }
    else   # single date or list of comma separated dates
    {
        for $d (split /,/, $date)
        {
            my ($dow1, $day1, $month1, $year1) = split /;/, parse_date($d);
            $pubDate = $pubDate . ", " if ($pubDate ne "");
            $pubDate .= "$month1 $year1";
        }
    }

    print <<EOT;

 <!--- Credits --->
 <tr>
  <td align="left" valign="top" width="$marginwidth">
   $returnLink &nbsp;
  </td>
  <td align="left" valign="top" width="$poemwidth">
       <table align="right"><tr>
        <td class="pageDate" align="left">
          $pubDate
        </td>
       </tr></table>
EOT

    multipage_menu ($pageTitle, $baseId, "Volume", $pageNum, $numPages);

    print <<EOT;
  </td>
  <td align="left" valign="top" width="$rightcolwidth">
   &nbsp;
  </td>
 </tr>
</table>
<br clear="all"><br>
EOT

    shite_menubar();
}

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

sub multiauthor_page    # generates an epic page or bible page
{
    my ($srcFile, $category) = @_;
    
    my ($fname, $path, $suffix) = fileparse($srcFile, '\..*');
    my $pageId = $fname;
    $pageId =~ s/$suffix$//;
    my $baseId = $pageId;
    $baseId =~ s/\d+$//;
    $path =~ s/\/$//;
    my $type = basename($path);
    my $returnLink = "";

    # Eg. srcFile="/data/multi/the_french2.txt"
    # fname="the_french2.txt", path="/data/multi", suffix=".txt",
    # pageId="the_french2", baseId="the_french", type="multi"

    # defaults
    $marginwidth = 150;
    $authorwidth =  50;
    $poemwidth   = 500;
    $border      = 0;

    $supertitle  = "";
    $title       = "";
    $subtitle    = "";
    $by          = "";
    $author      = "AUTHOR";
    $date        = "MONTH YEAR";
    $description = "";
    $margintext  = "";
    $bottomleft  = "&nbsp;";
    $chapter     = 0;
    $nchapters   = 0;
    $linebreak   = "<br>";
    $part        = "";
    $partName    = "Part";
    $rowspan     = 0;
    $rowspanTag  = "";
    $imageCode   = "";

    my $imageFile = "";
    my $supertitleSize = 6;
    my $supertitleColour = "black";

#    $image = "$IMGSHITEDIR/$pageId.gif" if (-s "$IMGSHITEDIR/$pageId.gif" > 0);
#    $image = "$IMGSHITEDIR/$pageId.jpg" if (-s "$IMGSHITEDIR/$pageId.jpg" > 0);

    if (uc($category) eq "B")
    {
        $partName = "Chapter";
    }

    $partName = "Page" if ((uc($category) eq "S") || (uc($category) eq "H"));

    if (uc($category) eq "H")
    {
        $supertitleSize = 5;
        $supertitleColour = "gray";
    }

    open (INFILE, $srcFile) or die "multiauthor_page: Cannot open srcFile=$srcFile\n";
    
    $verseCount = 0;

    while (<INFILE>)
    {
        chop;
        next if (/^#/);       # comment line
    
        if ($_ =~ /^\/verse/) # new verse
        {
            s/\/verse//;   # cut preceding /verse tag
    
            if ($verseCount == 0)  # It's the first verse so print title stuff first
            {
                 my $bracketSubtitle = "";
                 my $bracketBy = "";
                 my $keywords = "$author, $supertitle, $title, $subtitle";
                 my $tablewidth  = $marginwidth + $authorwidth + $poemwidth;
             
                 if ($supertitle ne "")
                 {
                     $supertitle =
                       "<font face=\"times,verdana,arial\" size=\"$supertitleSize\" color=\"$supertitleColour\">"
                      ."<i>$supertitle</i></font><p>";
                 }
             
                 if ($title ne "")
                 {
                     $titleFormat = #qq(<div class="itemTitle">$title</div>);
                       "<font face=\"arial,verdana,times\" size=\"5\" color=\"brown\"><b>$title</b></font>";
                 }
             
                 if ($subtitle ne "")
                 {
                     $bracketSubtitle = "(".$subtitle.")";
                     $subtitle =
                       "<p><font face=\"arial,verdana\" size=\"4\" color=\"black\">$subtitle</font>";
                 }
             
                 if ($chapter > 0)
                 {
                     $part =
                       "<p><font face=\"arial,verdana\" size=\"4\" color=\"black\">$partName $chapter</font>";
                 }

                 if ($rowspan > 0)
                 {
                     $rowspanTag = "rowspan=\"$rowspan\"";
                 }

                 if ($freetext > 0)
                 {
                     $linebreak = "";
                 }

                 if ($imageCode ne "")
                 {
                     $imageFile = get_image ($pageId, $imageCode);
                 }

                 $bracketBy = $by if ($by ne "");  # archaic name - we don't bracket the authors' names anymore

                 shite_title($title, $description);

                 if (uc($category) eq "B")   # Set return link for Bible
                 {
                     $returnLink = qq(
         <font face="verdana,arial,times" size="3" color="brown">
          <a href="$THIS_CGI?p=bible&$date_args"><img src="$IMGDIR2/left.gif" alt="Bible" border="0" width="12">The Bible</a>
         </font>
                     );
                 }
                 elsif (uc($category) eq "L")   # Set return link for Parochial Plops
                 {
                     $returnLink = qq(
         <font face="verdana,arial,times" size="3" color="brown">
          <a href="$THIS_CGI?p=parochial&$date_args"><img src="$IMGDIR2/left.gif" alt="Parochial Plops" border="0" width="12">Parochial Plops</a>
         </font>
                     );
                 }
                 elsif (uc($category) eq "H")   # Set return link for Prong Hills
                 {
                     $returnLink = qq(
         <font face="verdana,arial,times" size="3" color="brown">
          <a href="$THIS_CGI?p=prong&$date_args"><img src="$IMGDIR2/left.gif" alt="Prong Hills Menu" border="0" width="12"><nobr>More Prong Hills Tales</nobr></a>
         </font>
                     );
                 }

                 print <<EOT;
               <table align="left" border="$border" width="$tablewidth">
                <tr>
                 <td align="left" valign="top" width="$marginwidth" $rowspanTag>
                  <br clear="all"><br>
                  $returnLink
EOT

                 if (uc($category) eq "B")  # Add bible picture to margin
                 {
                     print <<EOT;
                  <br><br>
                  <a href="$THIS_CGI?p=bible&$date_args"><img src="$IMGSHITEDIR/the_bible.gif" alt="The Bible - Home Page" border="0" width="$marginwidth"></a>
                  <br clear="all">
                  </font>
EOT
                 }

                 if ($imageFile ne "" || $margintext ne "")   # Add imgshite picture to margin
                 {
                     $imagetext = "";
                     if ($imageFile ne "")
                     {
                         $imagetext = qq(<img src="$imageFile" width="$marginwidth">);
                     }

                     if ($rowspan < 1)  # Not using rowspan so we can add it to the margintext
                     {
                         $margintext .= "<br><br>" if ($margintext ne "");
                         $margintext .= $imagetext;
                     }
                     else   # rowspan means next margin won't be drawn, so show picture here
                     {
                         substitute_vars (\$margintext);
                         add_date_args_to_link (\$margintext);

                         print <<EOT;
                           <font face="times,arial" size="3" color="brown">
                           <br><br>$margintext<br><br>$imagetext
                           </font>
EOT
                     }
                 }

                 print <<EOT;
                 </td>
                 <td align="left" valign="top" width="$authorwidth">
                  &nbsp;
                 </td>
                 <td align="left" valign="top" width="$poemwidth">
                  <table align="left"><tr><td align="center">
                     $supertitle
                     $titleFormat
                     $subtitle
                    <br>
                    <div class="itemAuthor">$bracketBy</div>
                     $part
                  </td></tr></table>
                  <br clear="all"><br>
                  <font face="arial,verdana,times" size="2" color="black">
EOT
            }

            $verseCount++;
    
            print <<EOT;
         </font>
        </td>
       </tr>
       <tr>
EOT

            $rowspan-- if ($rowspan > 0);

            if ($rowspan < 1)
            {
                substitute_vars (\$margintext);
                add_date_args_to_link (\$margintext);

                print <<EOT;
        <td align="left" valign="top" width="$marginwidth">
         <font face="times,arial,verdana" size="3" color="brown">
          $margintext
         </font>
        </td>
EOT
            }

            print <<EOT;
        <td align="right" valign="top" width="$authorwidth">
         <font face="times" size="2" color="brown">
          <i>$_&nbsp;&nbsp;</i>
         </font>
        </td>
        <td align="left" valign="top" width="$poemwidth">
         <font face="arial,verdana,times" size="2" color="black">
EOT

            $margintext = "";
        }
        elsif ($_ =~ /^\//)  # It's a data formatter
        {
            $dataname = $_;
            $datatext = $_;
            $dataname =~ s/^\///;         # cut preceding /
            $dataname =~ s/\s+.*$//;      # cut all text after dataname
            $datatext =~ s/^\/\w+\s*//;   # cut /dataname
            $$dataname = $datatext;
        }
        elsif ($verseCount > 0) # print line within same verse
        {
            if ($freetext < 1)   # Poetry format 
            {
                substitute_vars (\$_);
                add_date_args_to_link (\$_);
                print "$_<br>\n";
            }
            elsif ($freetext == 2)  # Story format
            {
                    print "<p>" if ($_ =~ /^\s*$/);          # blank line
                    if ($_ =~ /^\s+\S/)  # indented start of paragraph
                    {
                        print <<EOT;
<table><td cellpadding="5"></td></table><table align="left"><td cellpadding="5"></td></table>
EOT
                    }
                    print "$_\n";
            }
            else   # Free format
            {
                if ($_ =~ /^\s*$/)
                {
                    print "<p>\n";
                }
                else
                {
                    substitute_vars (\$_);
                    add_date_args_to_link (\$_);
                    print "$_\n";
                }
            }
        }
    }
    
    close (INFILE);


    substitute_vars (\$margintext);
    add_date_args_to_link (\$margintext);

    print <<EOT;
         </font>
        </td>
       </tr>

       <tr>  <!------ Bottom row ---->
        <td align="left" valign="bottom" width="$marginwidth">
         <font face="times,arial,verdana" size="3" color="brown">
          $margintext<p>
          $returnLink
         </font>
        </td>
        <td align="left" valign="top" width="$authorwidth">
         <font face="verdana,arial,times" size="3" color="brown">
          &nbsp;
         </font>
        </td>
        <td align="left" valign="top" width="$poemwidth">
EOT

    # Author credits
    if ($chapter == $nchapters || uc($category) eq "B")
    {
      print <<EOT;
     <table border="0" align="right"><tr>
      <td align="left">
       <font face="times,arial" size="2" color="gray"><i>
        $author
        - $date
       </i></font>
      </td>
     </tr></table>
EOT
    }

    # Index of links to other Parts
    multipage_menu ($title, $baseId, $partName, $chapter, $nchapters);

    print <<EOT;
    </td>
   </tr>
  </table>
  <br clear="all"><br>
EOT

    shite_menubar();
}

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

sub get_blob_image
{
    my $authorCode = shift(@_);
    my $blob = "blob_grey.gif";

    $blob = "blob_mike.gif" if ($authorCode eq "m");
    $blob = "blob_kate.gif" if ($authorCode eq "k");
    $blob = "blob_both.gif" if ($authorCode eq "b");

    return $blob;
}

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

sub add_page_links      # displays list of pages of a given category (with blobs)
{
    my $myCategory = shift(@_);
    my ($authorCode, $pick, $category, $pageFormat, $date, $pageId, $title);
    my $blob;

    print <<EOT;
      <font face="arial,verdana,times" size="2">
EOT
    open (FD, "$PAGE_INDEX_FILE") or print "add_page_links: Cannot open PAGE_INDEX_FILE=$PAGE_INDEX_FILE";

    while (<FD>)
    {
        chop;
        ($authorCode, $pick, $category, $pageFormat, $date, $pageId, $title) = split /;/, $_;

        $category = substr ($category, 0, 1);
        $pageId   =~ s/^\s+//;
        $pageId   =~ s/\s+$//;
        $title    =~ s/^\s+//;
        $title    =~ s/\s+$//;
        $title    =~ s/\s1\s*$//;  # cut trailing digit '1'

        if ($category eq $myCategory)
        {
            $blob = get_blob_image($authorCode);

            print <<EOT;
              <img src="${IMGDIR2}/$blob" alt="$pageId" border="0">
               <a href="${THIS_CGI}?$date_args&p=$pageId">$title</a><br>
EOT
        }
    }
    print <<EOT;
      </font>
EOT
}

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

sub add_home_link       # displays link back to Shitespace Home, in top left corner
{
    my $arg = shift(@_);

    my $logofile = "$IMGDIR2/logo.gif";
    $logofile = "$IMGDIR2/logoy.gif" if ($arg eq "yellow");

    print <<EOT;
      <a href="$THIS_CGI?p=shite&$date_args"><nobr><img src="$IMGDIR2/left.gif" alt="Home" border="0"><img src="$logofile" alt="Shitespace Home" border="0"></nobr></a>
EOT
}

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

sub add_poem_of_the_day # displays the Poem Of The Day on Shitespace homepage
{
    my $startPoint = $arg1;
    $startPoint = 0 if (!$startPoint);
    my $poem_record = todays_poem($r_yyyymmdd);
    my $lineCount  = 0;
    my $linesSoFar = 0;
    my $poemsSoFar = 0;

    my ($shiteId, $poemTitle, $poemAuthor, $poemType, $imageCode) = split /;/, $poem_record;
    my $shitemFile = "$POETRYDIR/$shiteId.txt";
    my $imageFile = get_image ($shiteId, $imageCode);
    my $imageWidth = "150";

    if ($imageFile eq "")
    {
        $imageFile = "${IMGSHITEDIR}/default_pic.jpg";
        $imageWidth = "100";
    }

    print <<EOT;
         <table border="0" width="600">
EOT

    if ($startPoint < 1)  # Don't display Poem Of Day if we're on a second page, etc.
    {
        print <<EOT;
          <a name="$shiteId"></a>
          <font face="times,verdana,arial" color="brown" size="5">
           <i><nobr>Poem Of The Day . . .</nobr></i>
          </font>
          <p>

           <tr>
            <td align="left" valign="top" width="160">
             <img src="$imageFile" alt="$poemTitle" width="$imageWidth">
            </td>
            <td align="left" valign="top" width="440">
                   <font face="arial" size="4" color="brown"><b>
                    $poemTitle
                   </b></font>
                    <br>
                   <font face="times" size="2"><i>($poemAuthor)</i></font><br><br>
                   <font face="arial" size="2">
EOT

        open (SHITEM, $shitemFile) or cannot_find_poem_of_the_day($shiteId, $poemTitle, $poemAuthor);
        while (<SHITEM>)
        {
            next if (/^#/);
            next if (/^\//);
            substitute_vars (\$_);
            add_date_args_to_link (\$_);

            if ($lineCount > 0 || !/^\s*$/)
            {
                print "$_<br>\n";
                $lineCount++;
            }
        }
        close (SHITEM);
        $linesSoFar += $lineCount;

        print <<EOT;
           </font><br><br>
          </td></tr>
          <tr><td align="left" colspan="2">
EOT

        poems_opinion("whatisshite", "gray", 380, "$shiteId", "$poemTitle");
        user_form("left");

        print <<EOT;
           <br clear="all">
          </td></tr>
EOT
   }

    print <<EOT;

      <tr><td align="left" colspan="2">



           <!--------- Shite Sniffer ------->
           <table align="left" border="0" cellspacing="0" cellpadding="0" width="500">
            <tr>
             <td align="left" valign="top" width="240">
                <!-- Atomz Search HTML for Shite Space --> 
                 <form method="get" action="http://search.atomz.com/search/"> 
                 <font face="times,arial,verdana" size="5" color="brown"><i>Shite&nbsp;Sniffer</i></font><br>
              <font face="arial,verdana,times" size="2" color="gray">
               Not quite what you're looking for?
               Use Shite Sniffer to find the perfect
               words for your mood right now.
              </font>
                 <input size="25" name="sp-q"><br>
                 <input type="submit" value="Search"> 
                 <input type="hidden" name="sp-a" value="sp1001d5eb"></form> 
             </td>

             <td align="left" valign="top" width="20">
              &nbsp;
             </td>

             <!----------- Poemfactory ---------------->
             <td align="left" valign="top" width="240">
              <a href="http://www.poemfactory.com">
               <img src="${IMGSHITEDIR}/poemfactory_banner.jpg" alt="poemFactory" border="0" width="178" height="42"></a>
              <br clear="all">
              <font face="arial,verdana,times" size="2" color="gray">
              Trouble at t'mill?  Well, it's nothing compared to the mayhem you can cause at <a href="http://www.poemfactory.com">poemfactory</a>.
              Get your credit card out and send your loved one a really vulgar poem.
              </font>
             </td>
            </tr>
           </table>
           <br clear="all"><br>
           <!------------------------------->



           <font face="arial,verdana,times" size="2">
            Or if like most readers you can't be arsed with all these fabulous features,<br>
            just browse through our selected poetry for today...
           </font>

          </td></tr>
          <tr><td align="left" valign="top" colspan="2">
           <a name="more"></a>
           <br>
           <font face="times" size="5" color="brown"><i>
            More Of Today's Poetry . . .
           </i></font><p>
          </td></tr>
EOT






    # Now display random selection of poems
    my $i = 0;

    my $shiteHash = {};
    my $shiteList = ();
    my $pageHash = {};
    my $pageList = ();
    get_pages(\$pageHash, \@pageList, "a");  # get all pages
    get_shitems(\$shiteHash, \@shiteList, "d");  # get all shitems
    my $shiteListSize = scalar(@shiteList);
    my $pageListSize = scalar(@pageList);


    random_sort(\@shiteList, $r_yyyymmdd);

    $i = $startPoint;



    while ($linesSoFar < 200 && $poemsSoFar < 10)
    {
        $id = $shiteList[$i];

        if ($id ne $shiteId) 
        {                     # skip Poem Of Day 'cos we've already displayed it
            $poemTitle = $shiteHash->{$id}->{title};
            $poemAuthor = $shiteHash->{$id}->{author};
            $imageCode = $shiteHash->{$id}->{imageCode};

            $shitemFile = "$POETRYDIR/$id.txt";
            $imageFile = get_image ($id, $imageCode);
            $imageWidth = "150";


            print <<EOT;
          </td></tr>
          <tr><td align="left" valign="top" width="160">
EOT
            if ($imageFile)
            {
                print qq(<img src="$imageFile" alt="$poemTitle" width="$imageWidth">);
            }
            else
            {
                print "&nbsp;";
            }

            print <<EOT;
          </td>
          <td align="left" valign="top" width="440">
                   <font face="arial" size="4" color="brown"><b>
                    $poemTitle
                   </b></font>
                    <br>
                   <font face="times" size="2"><i>($poemAuthor)</i></font><br><br>
                   <font face="arial" size="2">
EOT

            $lineCount = 0;

            open (SHITEM, $shitemFile);
            while (<SHITEM>)
            {
                next if (/^#/);
                next if (/^\//);
                substitute_vars (\$_);
                add_date_args_to_link (\$_);

                if ($lineCount > 0 || !/^\s*$/)
                {
                    print "$_<br>\n";
                    $lineCount++;
                }
            }
            close (SHITEM);

            print "</font><br><br>";


            $poemsSoFar++;
            $linesSoFar += $lineCount;
        }

        $i++;
        $i -= $shiteListSize if ($i >= $shiteListSize);

##print "linesSoFar=$linesSoFar poemsSoFar=$poemsSoFar lineCount=$lineCount<br>\n";
    }

    print <<EOT;

         </td></tr>
         <tr><td align="left" valign="middle" width="160">
          <font face="arial" size="2" color="brown">
EOT
    if ($startPoint > 0)
    {
        print qq(<a href="$THIS_CGI?$date_args&p=shite&a=0#todays_poem"><img src="$IMGDIR2/left.gif" border="0"> Poem Of The Day</a>);
    }
    

    print <<EOT;
          </font>
         </td><td align="right" valign="middle" width="440">
          <font face="arial" size="2" color="brown">
          <a href="${THIS_CGI}?$date_args&p=shite&a=$i#more">More poems <img src="$IMGDIR2/right.gif" border="0"></a>  
          </font>
        </td>
       </tr>
      </table>
EOT
}

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

sub add_whatisshite_form
{
    my $poem_record = todays_poem($r_yyyymmdd);
    my ($shiteId, $poemTitle, $poemAuthor, $poemType, $imageCode) = split /;/, $poem_record;

    poems_opinion('shite#todays_poem', "brown", 380, "$shiteId", "$poemTitle");
    user_form("left");
}

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

sub add_shitespace_slogan
{
    my $myseed = random_seed();
    my $slogan = random_line ("${DATADIR}/lists/shitespaceslogans.list", $myseed);
    print qq($slogan);
}

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

sub add_pick_of_the_day # displays links to today's selected anthologies
{
    my @newList = ();
    my @anthList = ();
    my @storyList = ();
    my $titleHash = {};
    my $authorHash = {};
    my $categoryHash = {};
    my $daysOld = -1;
    my $blob;
    my $id;
    my $i;

    open (PAGEFILE, "$PAGE_INDEX_FILE");
    while (<PAGEFILE>)
    {
        chop;
        next if (/^#/ || /^\s*$/);
        ($authorCode, $pick, $category, $pageFormat, $date, $pageId, $title) = split /;/, $_;
        next if ($pick ne "d");

        $date = substr ($date, -8, 8);
        $pageId =~ s/\s+//g;
        $title =~ s/^\s+//;
        $title =~ s/\s+$//;

        $daysOld = 999999;

        if ($date =~ /[1-2][0-9][0-9][0-9][0-1][0-9][0-3][0-9]/ && ($date % 100 > 0))
        {
            $daysOld = date_calc("-c $date $r_yyyymmdd");
        }

        if ($daysOld < 31)
        {
            push @newList, $pageId;
        }
        elsif ($category eq "S")
        {
            push @storyList, $pageId;
        }
        else
        {
            push @anthList, $pageId;
        }

        $titleHash->{$pageId}    = $title;
        $authorHash->{$pageId}   = $authorCode;
        $categoryHash->{$pageId} = $category;
    }

    random_sort(\@newList, $r_yyyymmdd);
    random_sort(\@storyList, $r_yyyymmdd);
    random_sort(\@anthList, $r_yyyymmdd);
    my $count = 0;

    for $id (@newList)   # Show new stuff first
    {
        $blob = get_blob_image ($authorHash->{$id});
        $title = $titleHash->{$id};
        $title = "Shiterati: $title" if ($categoryHash->{$id} eq "R" || $id =~ /shiterati_/);
        $title =~ s/ 1$//;  # Remove "1" from multiple page title

        print <<EOT;
          <nobr><img src="${IMGDIR2}/$blob" alt="$title" border="0">
          <a href="${THIS_CGI}?$date_args&p=$id">$title</a><img src="${IMGDIR2}/new.gif" alt="New" border="0"></nobr><br>
EOT
        $count++;
    }

    for ($i = 0; $i < 5-$count; $i++)   # Now use whatever space is left for random anthologies
    {
        $id = $anthList[$i];
        $blob = get_blob_image ($authorHash->{$id});
        $title = $titleHash->{$id};
        $title = "Shiterati: $title" if ($categoryHash->{$id} eq "R" || $id =~ /shiterati_/);
        $title =~ s/ 1$//;  # Remove "1" from multiple page title
  
        print <<EOT;
          <nobr><img src="${IMGDIR2}/$blob" alt="$title" border="0">
          <a href="${THIS_CGI}?$date_args&p=$id">$title</a></nobr><br>
EOT
    }

    $id = $storyList[0];   # Finally stick a random story at the bottom
    $blob = get_blob_image ($authorHash->{$id});
    print <<EOT;
          <img src="${IMGDIR2}/$blob" alt="$titleHash->{$id}" border="0">
          <a href="${THIS_CGI}?$date_args&p=$id">$titleHash->{$id}</a>
EOT
}

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

sub textformat_page     # assumes most html formatting is in sourceFile
{
    my ($sourceFile, $title, $description, $funcArg) = @_;

    open (TEXTFILE, "$sourceFile") or die "textformat_page: Cannot open sourceFile=$sourceFile\n";

    shite_title($title, $description);

    while (<TEXTFILE>)
    {
        chop;
        next if (/^#/);

        if (/^\//)   # It's a formatter
        {
            s/\s+/ /g;
            @formatter = split / /, $_;

            if ($formatter[0] eq "/function")
            {
                add_home_link($formatter[2])  if ($formatter[1] eq "add_home_link");
                add_page_links($formatter[2]) if ($formatter[1] eq "add_page_links"); 
                add_poem_of_the_day()         if ($formatter[1] eq "add_poem_of_the_day");
                add_pick_of_the_day()         if ($formatter[1] eq "add_pick_of_the_day");
                add_stuff_today_links()       if ($formatter[1] eq "add_stuff_today_links");
                add_pooclub_menu()            if ($formatter[1] eq "add_pooclub_menu");
                add_whatisshite_form()        if ($formatter[1] eq "add_whatisshite_form");
                add_shitespace_slogan()       if ($formatter[1] eq "add_shitespace_slogan");
            }
            else
            {
                $dataname = $_;
                $datatext = $_;
                $dataname =~ s/^\///;         # cut preceding /
                $dataname =~ s/\s+.*$//;      # cut all text after dataname
                $datatext =~ s/^\/\w+\s*//;   # cut /dataname
                $$dataname = $datatext;
            }
        }
        else
        {
            substitute_vars (\$_);
            add_date_args_to_link (\$_);
            print $_, "\n";
        }
    }
    close (TEXTFILE);

    shite_menubar();
}

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

sub noformat_page       # assumes all html formatting is in sourceFile
{
    my $sourceFile = shift(@_);

    open (INFILE, "$sourceFile") or die "noformat_page: Cannot open sourceFile=$sourceFile\n";

    while (<INFILE>)
    {
        print $_;
    }
    close (INFILE);

    # Note no html title, menubar or copyright.  Everything is in the sourceFile.
    # In fact, we even have to exit here to stop the copyright function being called.

    exit(0);
}

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

sub pages_table         # for authors' use only
{
    my ($authorCode, $pick, $category, $pageFormat, $date, $pageId, $title);
    my $pageType;
    my $pageCount = 0;

    shite_title("Pages Table", "The complete catalogue of Shitespace pages");

    print <<EOT;
      <h2>Table Of Shitespace Pages</h2>
      <table border="0" align="left">
       <tr>
        <td align="left" valign="top"><b>Page Type</b></td>
        <td align="left" valign="top"><b>Page Id</b></td>
        <td align="left" valign="top"><b>Page Title</b></td>
       </tr>
EOT

    open (INFILE, "$PAGE_INDEX_FILE");

    while (<INFILE>)
    {
        chop;
        next if (/^#/);
        next if (/^\s*$/);

        ($authorCode, $pick, $category, $pageFormat, $date, $pageId, $title) = split /;/, $_;

        $pageCount++;
        $category = substr ($category, 0, 1);
        $category = uc($category);    # to upper case
        $pageId   =~ s/^\s+//;
        $pageId   =~ s/\s+$//;
        $title    =~ s/^\s+//;
        $title    =~ s/\s+$//;

        $pageType = "";
        $pageType = "Not Released"        if ($category eq "N");
        $pageType = "Anthology Of Poetry" if ($category eq "A");
        $pageType = "Shiterati Page"      if ($category eq "R");
        $pageType = "Short Story"         if ($category eq "S");
        $pageType = "Bible Page"          if ($category eq "B");
        $pageType = "Epic Page"           if ($category eq "E");
        $pageType = "Prong Hills Story"   if ($category eq "H");
        $pageType = "Parochial Plops Page" if ($category eq "L");
        $pageType = "Crappalot's Page"    if ($category eq "C");
        $pageType = "Clagnuts"            if ($category eq "X");

        print <<EOT;
          <tr>
           <td align="left" valign="top"><nobr> $pageType </nobr></td>
           <td align="left" valign="top">&nbsp;<a href="$THIS_CGI?$date_args&p=$pageId">$pageId</a>&nbsp;</td>
           <td align="left" valign="top"> $title </td>
          </tr>
EOT
    }

    close (INFILE);

    print <<EOT;
       </tr>
      </table>
      <br clear="all"><br>
      Total number of pages: $pageCount
      <br><br>
EOT

    shite_menubar();
}

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

sub write_shite         # top level function for generating a Shitespace page - just give it the pageId
{
    # actually, this function doesn't generate a page
    # but chooses which function is going to be used

    my $myPageId = shift(@_);
    my $found = 0;
    my ($authorCode, $pick, $category, $format, $date, $pageId, $title, $altTitle);
    my ($pageFormat, $pageNum, $numPages);

    # Redirect old-style pageIds
#    $myPageId = "rate" if ($myPageId eq "" || $myPageId eq "shitespace" ||
#                           $myPageId eq "home" || $myPageId eq "front" ||
#                           $myPageId eq "shite" || $myPageId eq "vote");
#    $myPageId = "map" if ($myPageId eq "pages");
#    $myPageId = "bowels" if ($myPageId eq "archives");
#    $myPageId = "votes"  if ($myPageId eq "viewlogs");
#    $myPageId = "league" if ($myPageId eq "viewvotes");
#    $myPageId = "hits"   if ($myPageId eq "viewhits");
    $myPageId = convert_pageId($myPageId);

    open (INFILE, $PAGE_INDEX_FILE) or print "write_shite: Cannot open PAGE_INDEX_FILE=$PAGE_INDEX_FILE<p>\n";

    while (<INFILE>)
    {
        chop;
        next if (/^#/);
        next if (/^\s*$/);

        ($authorCode, $pick, $category, $format, $date, $pageId, $title, $altTitle) =
            split /;/, $_;
        ($pageFormat, $pageNum, $numPages) = split /,/, $format;
        $pageId   =~ s/^\s+//;
        $pageId   =~ s/\s+$//;

        if ($myPageId eq $pageId)
        {
            $found++;
            last;
        }
    }
    close (INFILE);

    # strip preceding and trailing whitespace
    $date     =~ s/^\s+//;
    $date     =~ s/\s+$//;
    $title    =~ s/^\s+//;
    $title    =~ s/\s+$//;
    $altTitle =~ s/^\s+//;
    $altTitle =~ s/\s+$//;


    if ($found < 1)
    {
        shite_title("Bad Page Id", "$pageId");

        print <<EOT;
          write_shite: Cannot find pageId=$myPageId in PAGE_INDEX_FILE=$PAGE_INDEX_FILE<p>
          Please complain to <a href="mailto: bollocks\@shite.org">bollocks\@shite.org</a>
          quoting the above error message.
          <p>
          Links which might work:
          <ul>
          <li><a href="${THIS_CGI}?$date_args&p=shite">Shitespace</a>
          <li><a href="${THIS_CGI}?$date_args&p=stuff">Stuff Today</a>
          </ul>
EOT
        return;
    }


#        $remote_addr = $ENV{'REMOTE_ADDR'};
#        $remote_host = $ENV{'REMOTE_HOST'};
#        $remote_user = $ENV{'REMOTE_USER'};
#        $http_from   = $ENV{'HTTP_FROM'};

    # Write to pages log file
    write_log();

#    my $month = substr ($r_yyyymmdd, 0, 6);
#    $LOG_FILE = "${WRITEDIR}/pages_${month}.log";
#
#    open (PAGELOG, ">>$LOG_FILE");  # Record hit in log file
#    print PAGELOG "${r_yyyymmdd};${r_now};${pageId};${target};${remote_addr};${name};${b_yyyymmdd};${u_sex};\n";
#    close (PAGELOG);

    $pageId = "shite" if ($pageId eq "old");  # Finds text/shite.html for old-style front page
    $pageId = "archives" if ($pageId eq "bowels");

    # TODO: Can we add login to view the Shite in production?
    #if ($UBERACC{'USERNAME'} eq "") # if not logged into poopages

    if ($siteHost ne "dev") # Only allow the Shite to be accessed in dev environment
    {
        my $title = 'CANCELLED';
        my $description = "We're not in the nineties anymore";
        textformat_page ("$DATADIR/text/cancelled.html", $title, $description);
    }
    elsif ($pageId eq "drawing_board" || $pageId eq "drawingboard")
    {
        drawing_board();
    }
    elsif ($pageId eq "pages_table")
    {
        pages_table();
    }
    elsif ($pageId eq "map")
    {
        pages_page();
    }
    elsif ($pageId eq "index")
    {
        index_page();
    }
    elsif ($pageId eq "rate")
    {
        voting_page();
    }
    elsif ($pageId eq "hits")
    {
        view_pagelogs();
    }
    elsif ($pageId eq "votes")
    {
        view_logs();
    }
    elsif ($pageId eq "league")
    {
        view_votes();
    }
    elsif ($pageFormat eq "M")
    {
        multiauthor_page ("$MULTIDIR/${pageId}.txt", $category);
    }
    elsif ($pageFormat eq "B")
    {
        multiauthor_page ("$BIBLEDIR/${pageId}.txt", $category);
    }
    elsif ($pageFormat eq "P" || $pageFormat eq "S")
    {
        anthology_page ($pageId, $title, $altTitle, $date, $category, $pageNum, $numPages);
    }
    elsif ($pageFormat eq "T")
    {
        $description = get_description($category, $altTitle);
        textformat_page ("$DATADIR/text/${pageId}.html", $title, $description);
    }
    elsif ($pageFormat eq "C")
    {
#        textformat_page ("$DATADIR/text/crappalots_page.html", "Crappalot's Page", $title, $pageId);
        crappalots_page ($pageId, $title);
    }
    else # unknown format so just read it from a file
    {
        my $dir = "";
        $category = uc($category);    # to upper case

        $dir = "main"      if ($category eq "X");
        $dir = "crappalot" if ($category eq "C");
        $dir = "par"       if ($category eq "L");
        $dir = "rat"       if ($category eq "R");
        $dir = "sto"       if ($category eq "H");
        $dir = "sto"       if ($category eq "S");
        $dir = "epics"     if ($category eq "E");
        $dir = "bible"     if ($category eq "B");
        $dir = "ant"       if ($category eq "A");

        if ($dir eq "")
        {
            print "write_shite: Cannot find format or sourceFile for pageId=$pageId format=$format category=$category<p>\n";
            return;
        }

        my $sourceFile = "$HOMEDIR/$dir/${pageId}.html";

        noformat_page($sourceFile);
    }
}


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

sub add_stuff_today_links
{
    my $lightBlue = "#e0f0ff";
    my $myBlue1 = "#d0e8ff";
    my $myBlue2 = "#b0d8ff";
    my $myBlue3 = "#a0c0ff";
    my $myBlue4 = "#90b0ff";
    my $myBlue5 = "#80a0ff";
    my $mediumBlue  = "#80a0ff";
$myBlue2 = "#d0e8ff";
$myBlue1 = "#ffffff";
$myBlue2 = "#ffffff";


    # Write Calendar
    print qq(
      <!----- calendar --->
      <table cellpadding=1 cellspacing=1 border=0 width="80" bgcolor="$myBlue2" align="center">
       <tr><td align="center">
        <table cellpadding=1 cellspacing=0 border=0 width="100%" bgcolor="$myBlue2">
         <tr><td align="center">
          <font face="arial" size="2" color="black">
           $u_dayOfWeek<br>
          <font face="verdana,arial" size="6"><b><i>
           $u_mday
          </i></b></font>
            <br>
           <b>$u_month</b>
            <br>
           $u_year
          </font>
         </td></tr>
        </table>
       </td></tr>
      </table>
    );

    show_event ($r_yyyymmdd, 1, "50%", "center");

    # Write Stuff Today links
    print qq(
    <br>
    <table cellpadding="1" cellspacing="1" border="0" align="left" width="120" bgcolor="$myBlue3">
     <tr><td align="left">
      <table cellpadding="5" cellspacing="0" border="0" width="100%" bgcolor="$myBlue1">
       <tr><td align="left">
         <div class="stufflogo" align="center">
          <a class="stufflogo" href="$STUFF_CGI?$date_args&p=stuff">Stuff&nbsp;Today!</a>
         </div>
         <div class="stufflinks">
          <a href="$STUFF_CGI?$date_args&p=stuff">Home</a> |
          <a href="$STUFF_CGI?$date_args&p=prospects">Prospects</a> |
          <a href="$STUFF_CGI?$date_args&p=kday">K-days</a> |
          <a href="$STUFF_CGI?$date_args&p=events">Events</a> |
          <a href="$STUFF_CGI?$date_args&p=help&a=welcome">Welcome</a>
         </div>
     </td></tr></table>
    </td></tr></table>
    );
}

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

sub add_pooclub_menu  # a cut down version of pooclub_menus (shows only poopages menu)
{
    my $menuFile = "$POO_MENUS_FILE";

    unless (open (MENUFILE, "$menuFile"))
    {
        return;
    }

    print <<EOT;
    <table border="0" width="120" align="left" cellspacing="0" cellpadding="0">
     <tr>
      <td align="left" valign="top" width="120">
<!---------
        <center>
         <font face="times,arial" size="3"><i>
          or if you really want to waste your life, join...</i></font>
        </center>
----------->
        <font face="verdana,arial,times" size="6" color="brown">
         pooclub
        </font>

EOT
    require "pooclub_html.pl";

    pooclub_small_slogan();

    print <<EOT;
        <br clear="all">
        <font face="verdana,arial,times" size="4" color="brown">
         poopages
        </font>
        <table cellpadding="1" cellspacing="1" border="0" width="100%" bgcolor="#cc6600" >
         <tr align="center"><td align="left">
          <table class="poomenu" cellpadding="1" cellspacing="0" border="0" width="100%" bgcolor="#e8e8e8" >
EOT

    while (<MENUFILE>)
    {
        chop;
        next if (!/^A;/);
        next if (/^#/);
        next if (/^\s*$/);
        ($recType, $link, $title, $format) = split /;/, $_;

        $endlink = "";
        $asterisk = "";
        $indentation = "";
        $link = "$POO_CGI?" . $link;
        $link = "<a class=\"poomenu\" href=\"" . $link . "\">";
        $endlink = "</a>";

        print <<EOT;
           <tr>
            <td>&nbsp;</td> <td class="poomenu" nowrap valign="middle" align="left">
              $indentation$link$title$endlink
            </td>
            <td>&nbsp;</td>
           </tr>
EOT
    }

    close (MENUFILE);


    print <<EOT;
          </table>
         </td></tr>
        </table>
        <br clear="all">

      </td>
     </tr>
    </table>
    <br clear="all">
EOT
}

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

sub crappalots_page
{
    my ($pageId, $title) = @_;

    my $pageHash = {};
    my @pageList = ();

    get_pages(\$pageHash, \@pageList, "c");  # get "Crappalot's Page" list

    my $listSize = scalar(@pageList);
    my $pageNo = -1;
    my $prev = 3;
    my $next = 3;

    for ($i = 0; $i < $listSize; $i++)
    {
        if ($pageList[$i] eq $pageId)
        {
            $pageNo = $i;
            $i = $listSize;
        }
    }

    if ($pageNo >= 0)
    {
        $prev = $pageNo - 1;
        $next = $pageNo + 1;
        $prev = $listSize - 1 if ($prev < 0);
        $next = 0 if ($next >= $listSize);
    }

    $prevPageId = $pageList[$prev];
    $nextPageId = $pageList[$next];

    $prevTitle = $pageHash->{$prevPageId}->{title};
    $nextTitle = $pageHash->{$nextPageId}->{title};

    shite_title ("Crappalot's Page", "$title");

    print <<EOT;
<table align="left" width="90%" cellspacing="0" cellpadding="5" bgcolor="brown" border="0">
 <tr><td align="center" valign="center">

  <table width="100%" cellpadding="0" cellspacing="0" bgcolor="white" border="0">
  <tr>
  <td align="left" valign="top" width="30%">
    <a href="${THIS_CGI}?$date_args&p=$nextPageId">
    <img src="${IMGDIR1}/horse.gif" alt="$nextPageId" border="0">
    </a>
    <br clear="all">
    <font face="arial" size="-1">

    <ul>
EOT

    for ($i = 0; $i < $listSize; $i++)
    {
        print qq(
            <li><a href="${THIS_CGI}?$date_args&p=$pageList[$i]">$pageHash->{$pageList[$i]}->{title}</a>);
    }

    print <<EOT;
    </ul>

    <center><br><br>
    <a href="mailto:crappalot\@shite.org"><b>Email Crappalot</b></a>
    </center>
  </td>

  <td align="left" valign="top" width="60%">
    <br>
    <font face="verdana,arial" size="+1" color="brown"><b>
    Crappalot's Page</b>
    </font>
    <p>
    <font face="verdana,arial"><b>
    $title</b>
    </font>
    <font face="arial" size="-1">
    <p>
EOT

    # Add specific page text

    open (CRAPPAGE, "$DATADIR/text/${pageId}.html");
    while (<CRAPPAGE>)
    {
        substitute_vars(\$_);
        print $_;
    }
    close (CRAPPAGE);

    print <<EOT;
  <tr><td align="center" valign="bottom">
    <font face="arial" size="-1">
    <-- Previous Page<br>
    <a href="${THIS_CGI}?$date_args&p=$prevPageId">
    $prevTitle
    </a><br><br>
    </font>
  </td>
  <td align="center" valign="bottom">
    <font face="arial" size="-1">
    Next Page --><br>
    <a href="${THIS_CGI}?$date_args&p=$nextPageId">
    $nextTitle
    </a><br><br>
    </font>
  </td>
  <td align="center" valign="bottom"><br>
    <font face="arial" size="1">
     Crappalot appears&nbsp;<br> courtesy of<br>
    </font>
    <a href="${THIS_CGI}?$date_args">
    <font size="3" color="black"><b>Shite</b><i>Space</i></font>
    </a><br><br>
    </font>
  </td>
 </tr>
</table>
</td></tr></table>
EOT
}

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

sub index_page
{
    my $i;
    my $shiteHash = {};
    my $shiteList = ();
    my $pageHash = {};
    my $pageList = ();
    get_pages(\$pageHash, \@pageList, "a");  # get all pages
    get_shitems(\$shiteHash, \@shiteList, "a");  # get all shitems
    my $shiteListSize = scalar(@shiteList);
    my $pageListSize = scalar(@pageList);
    my $shiteCount = 0;

    for $shiteId (@shiteList)
    {
        $shiteId->{title} = $shiteHash->{$shiteId}->{title};
#        if ($shiteId->{title} =~ /^A /) {$shiteId->{title} = substr($shiteId->{title}, 2) . ", A";}
    }

    shite_title("Index", "Index of Shite Titles");

    print <<EOT;
    <table width="820" border="0" cellspacing="0" cellpadding="10">
     <tr>
      <td align="left" valign="top" bgcolor="#ffffc0" width="150">
EOT

    add_home_link (yellow);

    print <<EOT;
      </td>
      <td align="left" valign="top" width="20">
       &nbsp; 
      </td>
      <td align="left" valign="top" width="650">
        <font face="verdana,arial" size="4" color="brown">
         <b>Index Of Shite</b>
        </font>
       <p>
       <font face="verdana,arial" size="2">

       <!----- Index table ------>
       <table align="left" border="0">
        <tr>
          <td width="250" align="left" valign="top"><font face="times,verdana,arial" size="5"><i>Title</i></font></td>
          <td width="100" align="left" valign="top"><font face="times,verdana,arial" size="5"><i>Author</i></td>
          <td width="300" align="left" valign="top"><font face="times,verdana,arial" size="5"><i>Page</i></td>
        </tr>
EOT
    
    for $shiteId (sort sortbytitle @shiteList)
    {
        $shiteTitle = $shiteId->{title};
        $author     = $shiteHash->{$shiteId}->{author};
        $pageId     = $shiteHash->{$shiteId}->{pageId};
        $pageTitle  = $pageHash->{$pageId}->{title};
        $pageCategory = $pageHash->{$pageId}->{category};
        $initial    = substr($shiteTitle, 0, 1);

        next if (($pageHash->{$pageId}->{category} eq "n")
              || ($pageHash->{$pageId}->{category} eq ""));  # Don't include hidden pages
        next if ($shiteId eq "washing_up_nude_s");   # Ignore duplicate of this

        if ($pageId =~ /^shiterati/) {$pageTitle = "Shiterati: ". $pageTitle;}
        if ($shiteHash->{$shiteId}->{type} eq "B") {$pageTitle = "The Bible";}
        if ($shiteHash->{$shiteId}->{type} eq "H") {$pageTitle = "Tales From Beyond The Enchanted Prong Hills";}

#        print qq(shiteId=$shiteId shiteTitle=$shiteTitle author=$author pageId=$pageId pageTitle=$pageTitle
#        );

        if ($initial ne $prevInitial)   # Blank line on initial letter change
        {
            print qq(<tr><td>&nbsp;</td><td></td><td></td></tr>);
        }

        print qq(<tr>
          <td width="250" align="left" valign="top"><font face="verdana,arial" size="2"><a href="$THIS_CGI?$date_args&p=$pageId#$shiteId">$shiteTitle</a></font></td>
          <td width="100" align="left" valign="top"><font face="verdana,arial" size="2">$author</td>
          <td width="300" align="left" valign="top"><font face="verdana,arial" size="2">$pageTitle</td>
         <tr>);

        $prevInitial = $initial;
        $shiteCount++;
    }
    
    print <<EOT;
       </table>
       <br clear="all"><br>
       <nobr>Shite Count: $shiteCount</nobr>
       </font>
      </td>
     </tr>
    </table>
    <br clear="all">
EOT

    shite_menubar();
}

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

sub pages_page   # site map
{
    my $i;
    my $pageHash = {};
    my $pageList = ();
    get_pages(\$pageHash, \@pageList, "a");  # get all pages
    my $pageListSize = scalar(@pageList);
    my $shiteCount = 0;

    my $pageType = {
        X => 'Miscellaneous Pages',
        A => "Anthologies",
        E => "Epic Poetry",
        S => "Short Stories",
        H => "Tales From Beyond The Enchanted Prong Hills",
        B => "The Bible",
        R => "The Shiterati",
        L => "Parochial Plops",
        C => "Crappalot's Page",
        Y => "Splashback - Behind The Scenes",
        N => "Hidden Pages",
        W => "War Poetry",
        U => "Unfinished Shite"
    };

    shite_title("Site Map", "List Of Shitespace Pages");

    print <<EOT;
    <table width="820" border="0" cellspacing="0" cellpadding="10">
     <tr>
      <td align="left" valign="top" bgcolor="#ffffc0" width="150">
EOT

    add_home_link (yellow);

    print <<EOT;
      </td>
      <td align="left" valign="top" width="20">
       &nbsp; 
      </td>
      <td align="left" valign="top" width="660">
        <font face="verdana,arial" size="4" color="brown">
         <b>Shite Map</b>
        </font>
       <br>
        <font face="verdana,arial" size="2" color="black">
         - Shitespace Pages by Category
        </font>
       <p>
       <font face="verdana,arial" size="2">

       <!----- Index table ------>
       <table align="left" border="0">
EOT
    
    for $pageId (@pageList)
    {
        $pageTitle    = $pageHash->{$pageId}->{title};
        $pageCategory = uc($pageHash->{$pageId}->{category});
        $pageFormat   = uc($pageHash->{$pageId}->{pageFormat});
        ($formatCode, $pageNum, $numPages) = split /,/, $pageFormat;

        next if (($pageCategory eq "N")
              || ($pageCategory eq ""));  # Don't include hidden pages

        if ($pageId =~ /^shiterati_/) {$pageTitle = "Shiterati: ". $pageTitle;}

        if ($pageCategory ne $prevPageCategory)   # Blank line on change of category
        {
            print qq(<tr><td><br><font face="times,verdana,arial" size="5"><i>$pageType->{$pageCategory}</i></font></td><td></td><td></td></tr>);
        }

        print qq(<tr>
          <td width="500" align="left" valign="top"><font face="verdana,arial" size="2"><a href="$THIS_CGI?$date_args&p=$pageId">$pageTitle $pageNum</a></font></td>
          <td width="100" align="left" valign="top"><font face="verdana,arial" size="2">&nbsp;</td>
         <tr>);

        $prevPageCategory = $pageCategory;
        $pageCount++;
    }
    
    print <<EOT;
       </table>
       <br clear="all"><br>
       <nobr>Page Count: $pageCount</nobr>
       </font>
      </td>
     </tr>
    </table>
    <br clear="all">
EOT

    shite_menubar();
}


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

sub drawing_board
{
    my $i;
    my $pageHash = {};
    my $pageList = ();
    get_pages(\$pageHash, \@pageList, "n");  # get hidden pages
    my $pageListSize = scalar(@pageList);
    my $shiteCount = 0;

    shite_title("The Drawing Board", "Pages awaiting completion");

    print <<EOT;
    <table width="820" border="0" cellspacing="0" cellpadding="10">
     <tr>
      <td align="left" valign="top" bgcolor="#ffffc0" width="150">
EOT

    add_home_link (yellow);

    print <<EOT;
      </td>
      <td align="left" valign="top" width="20">
       &nbsp; 
      </td>
      <td align="left" valign="top" width="660">
        <font face="verdana,arial" size="4" color="brown">
         <b>The Drawing Board</b>
        </font>
       <p>
       <font face="verdana,arial" size="2">
       Welcome to the Shitespace workshop.  
       Those of you who have made it to this page are immensely privileged
       as we have set up no links here and so you are either here by pure
       chance or you have been invited to take a look behind the scenes by
       the authors.  If you're not supposed to be here, please leave now.
       <p>
       This page lists all the pages which are still under construction
       or for some reason we've decided not to give our readers a link to.
       Apologies if it's a bit messy... hell, no, why should we apologise?
       It's supposed to be messy!  We'll give you an official link to these
       pages when they're not messy anymore...

       <!----- Index table ------>
       <table align="left" border="0">
EOT
    
    for $pageId (@pageList)
    {
        $pageTitle    = $pageHash->{$pageId}->{title};
        $pageAltTitle = $pageHash->{$pageId}->{alternativeTitle};
        $pageCategory = uc($pageHash->{$pageId}->{category});
        $pageFormat   = uc($pageHash->{$pageId}->{pageFormat});
        ($formatCode, $pageNum, $numPages) = split /,/, $pageFormat;

        if ($pageId =~ /^shiterati_/) {$pageTitle = "Shiterati: ". $pageTitle;}

        if ($pageCategory ne $prevPageCategory)   # Blank line on change of category
        {
            print qq(<tr><td><br><font face="times,verdana,arial" size="5"><i>$pageType->{$pageCategory}</i></font></td><td></td><td></td></tr>);
        }

        print qq(<tr>
          <td width="300" align="left" valign="top"><font face="verdana,arial" size="2"><a href="$THIS_CGI?$date_args&p=$pageId">$pageTitle $pageNum</a></font></td>
          <td width="300" align="left" valign="top"><font face="times,arial,verdana" size="2"><i>$pageAltTitle</i></td>
         <tr>);

        $prevPageCategory = $pageCategory;
        $pageCount++;
    }
    
    print <<EOT;
       </table>
       <br clear="all"><br>
       <nobr>Page Count: $pageCount</nobr>
       </font>
      </td>
     </tr>
    </table>
    <br clear="all">
EOT

    shite_menubar();
}

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

1;

############################################################
# END OF FILE
############################################################
