############################################################
#
# shite_vote.pl
#
# Functions for handling the "Rate My Shite" page
#
############################################################

sub sortbyaverage { $b->{average} <=> $a->{average}; }
#sub sortbyrating { $b->{rating} <=> $a->{rating}; }
sub sortbyrating 
{
    if ($b->{rating} == $a->{rating})
    {
        $b->{numVotes} <=> $a->{numVotes};
    }
    else
    {
        $b->{rating} <=> $a->{rating}; 
    }
}
############################################################

sub write_file
{
    $fname = shift(@_);

    open (FD, ">$fname");

    if (FD)
    {
        print FD "Filename = $fname\n";
        print "Written to file: $fname<br>\n";
    }
    else
    {
        print "Failed to write to file: $fname<br>\n";
    }
    close(FD);
}

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

sub ming_table
{
    my @minger = @_;

    print qq(
      <a name="ming">
      <table width="140" border="0" align="right" cellpadding="4" cellspacing="0" bgcolor="#c0c0c0">
       <tr>
        <td align="left" valign="top" bgcolor="#c0c0c0" >
         <font face="arial" size="2" color="black">
          <b>$minger[0]</b>
         </font>
        </td>
       </tr>
       <tr>
        <td align="left" valign="top" bgcolor="#e0e0e0" >
         <font face="arial" size="2" color="black">
    );

    for ($i = 1; $i < scalar(@minger); $i++)
    {
        print qq(
         $minger[$i]<br>
        );
    }

    print qq(
         </font>
        </td>
       </tr>
      </table>
    );
}

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

sub voting_page
{
    my $i;
    my $points = 0;

#    my $poemNum = $cgi->param("num");
    my $poemPts = $cgi->param("pts");

    # Let's start off by getting a random selection of poems

    my $voteHash  = {};
    my $voteList  = ();
    my $shiteHash = {};
    my $shiteList = ();
    my $pageHash  = {};
    my $pageList  = ();
    get_pages(\$pageHash, \@pageList, "a");  # get all pages
    get_shitems(\$shiteHash, \@shiteList, "a");  # get selected shitems
                                                 # r = 'd' + '+' (recommended reading)
    my $shiteListSize = scalar(@shiteList);
    my $pageListSize  = scalar(@pageList);

    # Boundary check
    $poemNum = "" if ($poemNum < 0);
    $poemNum = "" if ($poemNum > $shiteListSize);
    $poemPts = "" if ($poemPts < 0);
    $poemPts = "" if ($poemPts > 10);

    my $shuffles = $r_yyyymmdd % 7 + 1;
    for ($i = 0; $i < $shuffles; $i++)
    {
        random_sort(\@shiteList, $r_yyyymmdd);
    }


    my $poem_record = todays_poem($r_yyyymmdd);  # Get Poem Of The Day
    my ($potdId, $potdTitle, $potdAuthor, $potdType, $potdImageCode) = split /;/, $poem_record;
    $shiteList[0] = $potdId;


    my $id         = $shiteList[$poemNum];
    my $title      = $shiteHash->{$id}->{title};
    my $author     = $shiteHash->{$id}->{author};
    my $imageCode  = $shiteHash->{$id}->{imageCode};

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

    my $prevId        = "";
    my $prevTitle     = "";
    my $prevAuthor    = "";
    my $prevImageCode = "";

    my $prevNumVotes = 0;
    my $prevAverage  = 0;

    my $highestAvg = 0;
    my $lowestAvg  = 1000000;
    my $foundPoem  = 0;

    my @animalList = ("Pig", "Cow", "Sheep", "Horse", "Cock");

    my $month = substr ($r_yyyymmdd, 0, 6);
    $LOG_FILE = "${WRITEDIR}/votes_${month}.log";
##    $TEMP_FILE = "${WRITEDIR}/votes_${r_yyyymmdd}.dat";


    shite_title("Rate Our Shite", "Shitespace voting page");

#write_file("../bing3.txt");

    if ($poemPts && $poemNum > 0)  # User has voted for previous poem
    {
        $prevId        = $shiteList[$poemNum - 1];
        $prevTitle     = $shiteHash->{$prevId}->{title};
        $prevAuthor    = $shiteHash->{$prevId}->{author};
        $prevImageCode = $shiteHash->{$prevId}->{imageCode};

        $remote_addr = $ENV{'REMOTE_ADDR'};
        $remote_host = $ENV{'REMOTE_HOST'};
        $remote_user = $ENV{'REMOTE_USER'};
        $http_from   = $ENV{'HTTP_FROM'};
        open (VOTELOG, ">>$LOG_FILE");  # Record vote in log file
        print VOTELOG "${r_yyyymmdd};${r_now};${prevId};${poemPts};${remote_addr};${poemNum};${remote_host};${remote_user};${http_from}\n";
        close (VOTELOG);

# data file format:
#id;votes,total,average,breakdown
#pooing;73;330;4.52;0=0,1=0,2=13,3=0,4=45,5=0,6=2,7=0,8=9,9=0,10=4;
#
# now changed to:
#id;breakdown;votes,total,average
#pooing;0=0,1=0,2=13,3=0,4=45,5=0,6=2,7=0,8=9,9=0,10=4;73;330;4.52;


        open (TMPFILE,  ">$WRITEDIR/votes_tmp.dat");

        # Read all votes from data file
        open (VOTEFILE, "$READDIR/votes.dat");

        while (<VOTEFILE>)
        {
            chop;
            ($poemId, $breakdown, $votes, $total, $avg) = split /;/;

            $highestAvg = $avg if ($avg > $highestAvg);
            $lowestAvg  = $avg if ($avg < $lowestAvg);

#print "poemId=$poemId prevId=$prevId<br>";
            if ($poemId eq $prevId)  # Update poem's score
            {
                $foundPoem++;

#print "breakdown=$breakdown<br>";
                $totalPts = 0;
                $totalVotes = 0;
                $sep = "";

                print TMPFILE "$prevId;";

                for $item (split /,/, $breakdown)
                {
                    ($points, $numVotes) = split /=/, $item;

                    $numVotes++ if ($points == $poemPts);

                    print TMPFILE "${sep}${points}=${numVotes}";
                    $sep = ",";
                    
                    $totalVotes += $numVotes;
                    $mult = $points * $numVotes;
                    $totalPts += $mult;  # Need to move breakdown to 2nd field so we can build data line up in one go
                }

                $average = 0;
                $average = ${totalPts} / ${totalVotes} if ($totalVotes > 0);
                printf TMPFILE ";${totalVotes};${totalPts};%.2f;\n", $average;

                $prevNumVotes = $totalVotes;
                $prevAverage  = $average;
            }
            else  # No change
            {
                print TMPFILE "$_\n";
            }
        }

        close (VOTEFILE);

        if ($foundPoem < 1)  # It's a new poem to the voting file
        {
            $sep = "";
            print TMPFILE "$prevId;";

            for ($i = 0; $i <= 10; $i++)
            {
                if ($poemPts == $i)
                {
                    print TMPFILE "${sep}${i}=1";
                }
                else
                {
                    print TMPFILE "${sep}${i}=0";
                }

                $sep = ",";
            }

            print TMPFILE ";1;$poemPts;$poemPts;\n";

            $prevNumVotes = 1;
            $prevAverage  = $poemPts;
        }

        close (TMPFILE);

        # Copy temp file on top of old voting file
        open (TMPFILE,  "$READDIR/votes_tmp.dat");
        open (VOTEFILE, ">$WRITEDIR/votes.dat");
        while (<TMPFILE>)
        {
            print VOTEFILE $_;
        }
        close (VOTEFILE);
        close (TMPFILE);
    }

    # Now to start writing the page...


    print qq(

     <!------- Slogan ----->
     <table width="100%"><tr><td align="right" class="smallText">
    );
    add_shitespace_slogan();
    print qq(
     </td></tr></table>
     <table width="720" border="0" cellspacing="0" cellpadding="0">
      <tr>
       <!------ Padding ----->
       <td align="left" valign="top" bgcolor="white" width="0">
        &nbsp;
       </td>

       <!------ Left hand column ------->
       <td align="left" valign="top" bgcolor="white" width="120">
        <a href="${THIS_CGI}?p=crappalot">
         <img src="${IMGSHITEDIR}/horse.gif" alt="Crappalot - your genial host" border="0"></a>

<!-------------
         <div align="center" class="pageTitle">
          Shite Poetry<br>1995-2005
         </div>
         <img src="${IMGSHITEDIR}/10_truly_horrible_years.jpg" alt="Shitespaces 10th Anniversary" border="0">
         <br>
----------------->

        <!---- Stuff Today ----->
    );

    add_stuff_today_links();

    print qq(
     <br clear="all"><br>

     <a href="http://www.poemfactory.com">
      <img src="${IMGSHITEDIR}/poemfactory120.jpg" border="0" width="120"
           alt="www.poemfactory.com" align="left"></a>
     <br clear="all"><br>
    );



    add_pooclub_menu();

    my $poemOfTheDay = "&nbsp;";
    $poemOfTheDay = "Poem Of The Day" if ($poemNum eq "" || $poemNum == 0);

    print qq(
       <a href="${THIS_CGI}?p=bowels&$date_args">
        <img src="${IMGSHITEDIR}/shite_inside.bmp" border="0" width="120"
             alt="Enter The Bowels Of Shitespace" align="left"></a>
    ) if ($poemNum eq "" || $poemNum == 0);

    print qq(
       </td>

       <!------ Main column ------->
       <td align="left" valign="top" bgcolor="white" width="600">



        <table border="0" width="600" align="left">
         <tr>

          <td align="left" valign="top" width="5">
          </td>
          <td align="left" valign="top" width="225">
           <div class="smallishText">
            You have strolled into Shitespace.<br>
            Do not be alarmed, it's quite nice here.
            Just kick off your shoes, put your feet up, and have a giggle
            in our cosy little haven where nothing matters, 
            and you're safe from the nasty outside world.
           </div><br>
           <div class="sectionTitle">Pick Of The Day</div><br>
           <div class="listLink">

    );

    add_pick_of_the_day();

    print qq(
           </div>
          </td>
          <td align="left" valign="top" width="320">
           <div align="right" class="smallText">
    );

    print qq(
           </div>
           <font face="verdana,times,arial,verdana" size="1">
            <a href="${THIS_CGI}?p=bowels&$date_args">
             <img src="${IMGSHITEDIR}/shitespace_logo.jpg" width="300" border="0"
                  alt="Enter The Bowels Of Shitespace"></a>
           </font>
          </td>
         </tr>
        </table>
        <br clear="all"><br>

        <!--------- POEM OF THE DAY ----------->
        <a name="poem">
        <table border="0" bgcolor="white" align="left" bordersize="0" width="600"
               cellspacing="0" cellpadding="10">
         <tr>
          <td align="left" valign="top">


          </td>
          <td align="right" valign="top">
           <font face="verdana,times,arial,verdana" size="1">
    );

    print qq(
           </font>
    );

    if ($poemNum eq "" || $poemNum == 0)
    {
        print qq(
                 <div class="sectionTitle" align="left">$poemOfTheDay</div>
       );
    }

    print qq(
          </td>
         </tr>
    );

    if ($prevId)   # show voting of previous poem
    {

        $animal = $animalList[$poemPts / 2 - 1];
        $prevAverage = sprintf "%.2f", $prevAverage;
        $fakeVotes = 100 * ($prevNumVotes - 1) + randy(1, 99, $r_sec);
        $plural = "";
        $plural = "s" if ($fakeVotes > 1);

        print qq(
          <tr><td colspan="2" align="left">
           <font face="verdana,arial,times" size="2">
            You gave "<b>$prevTitle</b>" a $animal. 
            &nbsp;&nbsp;&nbsp;&nbsp;
            <nobr>Rating = 
           </font>
           <font face="verdana,arial,times" size="5">
            <b>$prevAverage</b>
           </font>
           <font face="times,arial,verdana" size="2">
            <i>($fakeVotes vote${plural})</i>
           </font>
           </nobr>
           <br clear="all"><br>
          </td></tr>
        );
    }


    $type = "P";

    show_shitem ($type, $id, $title, $author, $imageCode, 195, 400, 5);

    print qq(
        </table>

        <br clear="all">

<!----
type=$type id=$id title=$title author=$author imageCode=$imageCode poemNum=$poemNum poemPts=$poemPts<br>
---->

        <!----------- Buttons ------->
        <table align="center" border="0">

         <tr>
          <td colspan="5" align="center">
           <table border="0" width="100%" align="center">
            <tr>
             <td align="left">
              <img src="${IMGDIR2}/left.gif">
              <font face="times,arial,verdana" size="5"><i>
               Hate it!
              </i></font>
             </td>
             <td align="center">
              <font face="arial,verdana,times" size="2" color="gray">
               RATE THIS POEM
              </font>
             </td>
             <td align="right">
              <font face="times,arial,verdana" size="5"><i>
               Love it!
              </i></font>
              <img src="${IMGDIR2}/right.gif">
             </td>
            </tr>
           </table>
          </td>
         </tr>

         <tr>
    );


    my $animal;

    $poemNum++;

    for ($i = 0; $i < 5; $i++)
    {
        $points = ($i + 1) * 2;
        $animal = lc($animalList[$i]);

        print qq(
         <td>
          <a href="${THIS_CGI}?p=vote&${today_args}&${dob_args}&pts=$points&poemNum=$poemNum#poem">
             <img src="$IMGDIR2/butt_$animal.jpg" border="0"></a>
          <div align="center">
           <font face="arial,verdana,times" size="1">
            <a href="${THIS_CGI}?p=vote&${today_args}&${dob_args}&pts=$points&poemNum=$poemNum#poem">
               $animalList[$i]</a>
           </font>
          </div>
         </td>
        );
    }

    print qq(
         </tr>
        </table>
        <br clear="all">

        <table border="0" width="100%">
         <tr>
          <td align="left" valign="top">
    );

    if (!$poemPts)
    {
        print qq(
            <font face="verdana,arial,times" size="2">
             We'd like you to judge our Shite by awarding it farm animals. 
             Please select the farm animal which best expresses your enjoyment
             of the poem you've just read.
             Note that we are not expecting you to judge our work on how good 
             or bad it is - we <i>know</i> it's all terrible - 
             we're only interested in how much satisfaction <i>you</i> derived 
             from our poetry.
            <p>
             So if you really enjoyed the poem give it a proud cock but if it 
             really didn't do it for you then give it a piddling pig. 
            </font>
        );
    }

    print qq(
           &nbsp;
          </td>
          <td align="right" valign="top">
    );

    if ($poemNum == 1)
    {
        ming_table("Places that ming",
                   "Birmingham",
                   "Godalming",
                   "Walmington-on-Sea",
                   "Wyoming");        
    }

    elsif ($poemNum == 2)
    {
        ming_table("People that ming",
                   "Ernest Hemingway",
                   "Placido Domingo",
                   "Ian Fleming",
                   "Ming The Merciless<nobr><font face=\"arial\" size=\"1\">(Out of \"Flash Gordon\")</font></nobr>");
    }
    elsif ($poemNum == 3)
    {
        ming_table("Creatures that ming",
                   "Flamingo",
                   "Hummingbird",
                   "Lemming",
                   "Homing Pigeon");
    }
    elsif ($poemNum == 4)
    {
        ming_table("Jobs that ming",
                   "Farming",
                   "Computer Programming",
                   "Embalming",
                   "Snake Charming");
    }
    elsif ($poemNum == 5)
    {
        ming_table("Things that ming",
                   "Mingling",
                   "Swimming",
                   "Bumming",
                   "Judaism in Grimsby");
    }
    elsif ($poemNum == 6)
    {
        ming_table("Chinese dynasties that ming",
                   "erm ... Ming?");
    }


    print qq(
           &nbsp;
          </td>
         </tr>
        </table>
        <br clear="all">

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

#    print qq(
#      shiteListSize=$shiteListSize <br>
#    );

#    for ($i = 0; $i < $shiteListSize; $i++)
#    {
#        print qq(
#            $i $shiteList[$i] <br>
#        );
#    }

#print qq(
# VOTING_LOG_FILE=$VOTING_LOG_FILE<br>
#);

    shite_menubar();
}


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

sub view_votes()  # League
{
    shite_title("Rate Our Shite", "Shitespace voting page");

    my $voteHash  = {};
    my @voteList  = ();
    my $shiteHash = {};
    my @shiteList = ();
    get_shitems(\$shiteHash, \@shiteList, "a");
    my $textsize = "1";
    my $textface = "arial,verdana,times";

    print qq(
     <font face="verdana,arial,times" size="4">
       Shitespace League Table
     </font>
     <p>

     <font face="arial,verdana,times" size="2">
      <a href="${THIS_CGI}?p=votes&$date_args#end">Votes</a>&nbsp;|
      <a href="${THIS_CGI}?p=hits&$date_args#end">Hits</a>
     </font>
     <br><br>

     <font face="arial,verdana,times" size="2">

     <table align="left" border="0">
           <tr>
            <td align="center">
              <font face="$textface" size="$textsize">
               <b>Posn</b>
             </div>
            </td>
            <td>
             <font face="$textface" size="$textsize">
              <b>Poem</b>
             </font>
            </td>
            <td>
             <font face="$textface" size="$textsize">
              <b>Rating</b>
             </font>
            </td>
            <td>
             <font face="$textface" size="$textsize">
              <b>Votes</b>
             </font>
            </td>
            <td>
             <font face="$textface" size="$textsize">
              &nbsp;&nbsp;<b>Pig</b>
             </font>
            </td>
            <td>
             <font face="$textface" size="$textsize">
              <b>Cow</b>
             </font>
            </td>
            <td>
             <font face="$textface" size="$textsize">
              <b>Sheep</b>
             </font>
            </td>
            <td>
             <font face="$textface" size="$textsize">
              <b>Horse</b>
             </font>
            </td>
            <td>
             <font face="$textface" size="$textsize">
              <b>Cock</b>
             </font>
            </td>
<!---------
            <td>$id->{totalPts}</td>
            <td>$id->{average}</td>
            <td>$id->{ratingPts}</td>
-------------->
           </tr>
    );

    @pointsList = (0, 3, 7, 12, 18);

    open (VOTEFILE, "$READDIR/votes.dat");

    while (<VOTEFILE>)
    {
        chop;

        ($id, $breakdown, $numVotes, $totalPts, $average) = split /;/, $_;
        ($zero, $one, $pig, $three, $cow, $five, $sheep, $seven, $horse, $nine, $cock)
            = split /,/, $breakdown;

        $pig =~ s/^.*=//;
        $cow =~ s/^.*=//;
        $sheep =~ s/^.*=//;
        $horse =~ s/^.*=//;
        $cock =~ s/^.*=//;
        $average = sprintf "%.2f", $average;

        $ratingPts = ($pointsList[0] * $pig) +
                     ($pointsList[1] * $cow) +
                     ($pointsList[2] * $sheep) +
                     ($pointsList[3] * $horse) +
                     ($pointsList[4] * $cock);
        $rating = $ratingPts / ($numVotes + 1);

        $id->{pig} = $pig;
        $id->{cow} = $cow;
        $id->{sheep} = $sheep;
        $id->{horse} = $horse;
        $id->{cock} = $cock;
        $id->{numVotes} = $numVotes;
        $id->{totalPts} = $totalPts;
        $id->{average} = $average;
        $id->{ratingPts} = $ratingPts;
        $id->{rating} = $rating;
        push @voteList, $id;
    }

    close (VOTEFILE);

    my $i = 0;
    my $posn = 1;
    my $textsize = "1";
    my $textface = "arial,verdana,times";

    for $id (sort sortbyrating @voteList)
    {
        $prevRating = $rating;
        $prevNumVotes = $numVotes;
        $rating = sprintf "%.2f", $id->{rating};
        $numVotes = $id->{numVotes};
        $i++;

        # Increment posn only if rating has changed, so that tied poems
        # are awarded the same posn
        if (($prevRating != $rating) || ($numVotes != $prevNumVotes))
        {
            $posn = $i;
        }

        print qq(
           <tr>
            <td align="center">
             <div align="right">
              <font face="$textface" size="$textsize">
               $posn&nbsp;&nbsp;
              </font>
             </div>
            </td>
            <td>
             <font face="$textface" size="$textsize">
              $shiteHash->{$id}->{title}
             </font>
            </td>
            <td align="right">
             <font face="$textface" size="$textsize">
              $rating&nbsp;&nbsp;
             </font>
            </td>
            <td align="right">
             <font face="$textface" size="$textsize">
              $numVotes&nbsp;&nbsp;
             </font>
            </td>
            <td align="right">
             <font face="$textface" size="$textsize">
              $id->{pig}
             </font>
            </td>
            <td align="right">
             <font face="$textface" size="$textsize">
              $id->{cow}
             </font>
            </td>
            <td align="right">
             <font face="$textface" size="$textsize">
              $id->{sheep}
             </font>
            </td>
            <td align="right">
             <font face="$textface" size="$textsize">
               $id->{horse}
             </font>
            </td>
            <td align="right">
             <font face="$textface" size="$textsize">
               $id->{cock}
             </font>
            </td>
<!---------
            <td>$id->{totalPts}</td>
            <td>$id->{average}</td>
            <td>$id->{ratingPts}</td>
-------------->
           </tr>
        );

        $prevId = $id;
    }



    print qq(
     </table>
     </font>
     <br clear="all"><br>

     <font face="arial,verdana,times" size="2">
      <a href="${THIS_CGI}?p=votes&$date_args#end">Votes</a>&nbsp;|
      <a href="${THIS_CGI}?p=hits&$date_args#end">Hits</a>
     </font>
     <br><br>   
    );

    shite_menubar();
}

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

sub view_logs()   # Votes
{
    shite_title("Voting Log File", "Voting Log File");

    my $voteHash  = {};
    my $voteList  = ();
    my $shiteHash = {};
    my $shiteList = ();
    my $logday   = $cgi->param("ld");
    my $logmonth = $cgi->param("lm");
    my $logyear  = $cgi->param("ly");

#print "logmonth=$logmonth logyear=$logyear";

    get_shitems(\$shiteHash, \@shiteList, "a");

    my @animalList = ("Pig", "Cow", "Sheep", "Horse", "Cock");
    my $lastYyyymmdd = "";
    my $month = substr ($r_yyyymmdd, 0, 6);

    # What log file?
    if ($logmonth && $logyear)
    {
        for ($i = 0; $i < 12; $i++)  # What month number?
        {
#print "i=$i logmonth=$logmonth monthList=$monthList[$i]<br>";
            if ($logmonth eq $monthList[$i])
            { 
                $mm = sprintf "%02d", $i + 1;
                last;
            }
        }
      
        $month = "$logyear" . "$mm";
    }
    else
    {
        $logmonth = $um;
        $logyear  = $uy;
    }

    print qq(
     <font face="verdana,arial,times" size="4">
       Shitespace Votes - $logmonth $logyear
     </font>
     <p>

     <font face="arial,verdana,times" size="2">
    );

    log_form();

    my $thisMonth = substr($r_yyyymmdd, 0, 6);
    $LOG_FILE = "${READDIR}/votes_${month}.log";

    if ($month < 200403)
    {
        print qq(
          Vote logs started in March 2004
        );
    }
    elsif ($month > $thisMonth)
    {
        print qq(
          You'll have to wait . . .
        );
    }

    print qq(
LOG_FILE=$LOG_FILE
     <table align="left" border="0">
    );



 
    open (LOGFILE, "$LOG_FILE");

    while (<LOGFILE>)
    {
        chop;

        # Depth is how far down the list of poems this user went while voting

        ($yyyymmdd, $hhmm, $id, $vote, $ipAddress, $depth, $others) = split /;/, $_;
        $points = $vote / 2 - 1;

        if ($lastYyyymmdd != $yyyymmdd)  # Next day
        {
            ($dow, $nday, $month, $year) = split /;/, parse_date ($yyyymmdd);
         
            print qq(
             <tr>
              <td colspan="5" align="left">
               <a name="$yyyymmdd">
               <font face="arial,verdana,times" size="1">
                <br>
               </font>
               <font face="arial,verdana,times" size="2">
                <b>$dow $nday $month $year</b>
               </font>
              </td>
             </tr>
            );

            $lastYyyymmdd = $yyyymmdd;
        }

        print qq(
           <tr>
            <td>
             <font face="arial,verdana,times" size="1">
              $hhmm
             </font>
            </td>
            <td>
             <font face="arial,verdana,times" size="1">
              $shiteHash->{$id}->{title}
             </font>
            </td>

            <td>
             <font face="arial,verdana,times" size="1">
              $animalList[$points]
             </td>
             </font>
            <td>
        );

        for ($i = 0; $i <= $points; $i++)
        {
            print qq(
              <img src="${IMGDIR2}/star.gif" alt="star" border="0">
            );
        }

        print qq(
            </td>
            <td>
             <font face="arial,verdana,times" size="1">
              $ipAddress
            </td>
            <td>
             <font face="arial,verdana,times" size="1">
              [${depth}]
            </td>
             </font>
           </tr>
        );
    }

    close (VOTEFILE);

    print qq(
     </table>
     </font>
     <br clear="all"><br>
    );

    log_form();
    shite_menubar();
}

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

sub view_pagelogs()    # Hits (Page Views)
{
    shite_title("Page Hits Log", "Page Hits Log");

    my $pageHash = {};
    my $pageList = ();
    my $logday   = $cgi->param("ld");
    my $logmonth = $cgi->param("lm");
    my $logyear  = $cgi->param("ly");
    my $dd;
    my $mm;
    my $yyyy;
    my $title;
    my $titleColour;
    my $shitespaceHits = {};
    my $poopagesHits = {};
    my $stufftodayHits = {};
    my $datesList = ();
    my $pageIdHits = {};
    my @pageIdList = ();

print "logmonth=$logmonth logyear=$logyear";

    get_pages(\$pageHash, \@pageList, "a");  # get all pages

    my $lastYyyymmdd = "";
#    my $month = substr ($r_yyyymmdd, 0, 6);

    # What log file?
    if ($logday && $logmonth && $logyear)
    {
        $dd   = sprintf "%02d", $logday;
        $yyyy = sprintf "%02d", $logyear;

        for ($i = 0; $i < 12; $i++)  # What month number?
        {
#print "i=$i logmonth=$logmonth monthList=$monthList[$i]<br>";
            if ($logmonth eq $monthList[$i])
            { 
                $mm = sprintf "%02d", $i + 1;
                last;
            }
        }
    }
    else
    {
        $dd   = sprintf "%02d", substr($r_yyyymmdd, 6, 2);
        $mm   = sprintf "%02d", substr($r_yyyymmdd, 4, 2);
        $yyyy = sprintf "%02d", substr($r_yyyymmdd, 0, 4);
    }

    my $month = $monthList[($mm - 1)%12];
    my $logfile = "$WRITEDIR/views_$yyyy" . "$mm" . "$dd" . ".log";
$logfile = "$READDIR/pages_$yyyy" . "$mm" . ".log"; # Old monthly version

    print qq(
     <font face="verdana,arial,times" size="2" color="black">
       Shite
     </font>
     <font face="verdana,arial,times" size="2" color="black">
       log <br>
     </font>
     <font face="verdana,arial,times" size="4">
       Page Views - $dd $month $yyyy
<br>logfile=$logfile
     </font>
     <p>

     <font face="arial,verdana,times" size="2">
    );

    log_form();

    my $thisMonth = substr($r_yyyymmdd, 0, 6);


    print qq(
     <table align="left" border="0">
    );

    open (LOGFILE, "$logfile") or print "No page views for $dd $month $yyyy";

    while (<LOGFILE>)
    {
        chop;

        # Depth is how far down the list of poems this user went while voting

        ($yyyymmdd, $hhmm, $id, $pageArg1, $ipAddress, $pageArg2, $dob, $sex, $site) = split /;/, $_;
        $id = convert_pageId($id);
        $title = $pageHash->{$id}->{title};
        $titleColour = "black";

        # Record daily hits counts in hash tables

        if ($site eq "P")       
        {
            $poopagesHits->{$yyyymmdd}++;
            $title = "Poopages";
            $titleColour = "brown";

            if ($id eq "chat")
            {
                $id = $pageArg1;
                $pageArg1 = $pageArg2;
                $pageArg2 = "";
            }
        }
        elsif ($site eq "T")
        {
            $stufftodayHits->{$yyyymmdd}++;
            $title = "Stuff Today";
            $titleColour = "blue";
        }
        else
        {
            $shitespaceHits->{$yyyymmdd}++;
        }

        # Record popular page hash
#        if ($pageIdHits->[$id] < 1)
#        {
#            push @pageIdList, $id;
#        }
#        $pageIdHits->{$id}++;

        if ($lastYyyymmdd != $yyyymmdd)  # Next day
        {
            ($dow, $nday, $month, $year) = split /;/, parse_date ($yyyymmdd);        
            push @datesList, $yyyymmdd;

            print qq(
             <tr>
              <td colspan="5" align="left">
               <a name="$yyyymmdd">
               <font face="arial,verdana,times" size="1">
                <br>
               </font>
               <font face="arial,verdana,times" size="2">
                <b>$dow $nday $month $year</b>
               </font>
              </td>
             </tr>
            );

            $lastYyyymmdd = $yyyymmdd;
        }

        print qq(
           <tr>
            <td>
             <font face="arial,verdana,times" size="1">
              $hhmm
             </font>
            </td>
            <td>
             <font face="arial,verdana,times" size="1" color="$titleColour">
              $site
             </font>
            </td>
            <td>
             <font face="arial,verdana,times" size="1" color="$titleColour">
              $title
             </font>
            </td>

            <td>
             <font face="arial,verdana,times" size="1">
              $id
             </font>
            </td>
            <td>
             <font face="arial,verdana,times" size="1">
              $pageArg1
             </font>
            </td>
            <td>
             <font face="arial,verdana,times" size="1">
              $pageArg2
            </td>
            <td>
             <font face="arial,verdana,times" size="1">
              $ipAddress
            </td>
            <td>
             <font face="arial,verdana,times" size="1">
              $dob
            </td>
            <td>
             <font face="arial,verdana,times" size="1">
              $sex
            </td>

             </font>
           </tr>
        );
    }

    close (VOTEFILE);

    print qq(
     </table>
     </font>
     <br clear="all"><br>
    );

    # Display daily hits summary

    print qq(
       <font face="arial,verdana,times" size="2">
       <b>Summary</b>
       </font>
        <table border="0" align="left">
         <tr>
          <td><font face="arial,verdana,times" size="1">Date</font></td>
          <td><font face="arial,verdana,times" size="1">Total</font></td>
          <td><font face="arial,verdana,times" size="1">Shite</font></td>
          <td><font face="arial,verdana,times" size="1">Poo</font></td>
          <td><font face="arial,verdana,times" size="1">Stuff</font></td>
         </tr>
    );

    my $totTotal = 0;
    my $totShite = 0;
    my $totPoo  = 0;
    my $totStuff = 0;

    for $yyyymmdd (@datesList)
    {
        $total = $shitespaceHits->{$yyyymmdd} 
               + $poopagesHits->{$yyyymmdd}
               + $stufftodayHits->{$yyyymmdd};
        $totTotal += $total;
        $totShite += $shitespaceHits->{$yyyymmdd};
        $totPoo   += $poopagesHits->{$yyyymmdd};;
        $totStuff += $stufftodayHits->{$yyyymmdd};
        ($dow, $nday, $month, $year) = split /;/, parse_date ($yyyymmdd); 
        $dow = substr ($dow, 0, 3);
        $month = substr ($month, 0, 3);

        print qq(
         <tr>
          <td><font face="arial,verdana,times" size="1">$dow $nday $month</font></td>
          <td><font face="arial,verdana,times" size="1">$total</font></td>
          <td><font face="arial,verdana,times" size="1">$shitespaceHits->{$yyyymmdd}</font></td>
          <td><font face="arial,verdana,times" size="1">$poopagesHits->{$yyyymmdd}</font></td>
          <td><font face="arial,verdana,times" size="1">$stufftodayHits->{$yyyymmdd}</font></td>
         </tr>
        );
    }

    print qq(
         <tr>
          <td><font face="arial,verdana,times" size="1"><b>Totals</b></font></td>
          <td><font face="arial,verdana,times" size="1">$totTotal</font></td>
          <td><font face="arial,verdana,times" size="1">$totShite</font></td>
          <td><font face="arial,verdana,times" size="1">$totPoo</font></td>
          <td><font face="arial,verdana,times" size="1">$totStuff</font></td>
         </tr>
        </table>
       <br clear="all"><br>
    );

    log_form();

    shite_menubar();
}

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

sub log_form()
{
    my ($dow, $mday, $month, $year, $mnum) = split /;/, parse_date($r_yyyymmdd);

    my $logday = $cgi->param("ld");
    $logday = $mday if (!$logday);

    my $logmonth = $cgi->param("lm");
    $logmonth = $month if (!$logmonth);

    my $logyear = $cgi->param("ly");
    $logyear = $year if (!$logyear);

    print qq(
     <a name="end">

     <form action = "$THIS_CGI" method = "GET">
      <table border="0">
       <tr>
        <td align="left"> 
         <font face="arial,verdana,times" size="2">
          <a href="${THIS_CGI}?p=league&$date_args">League</a>
         </font>
        </td>
        <td align="left"> 
         <font face="arial,verdana,times" size="2">|
          <a href="${THIS_CGI}?p=votes&$date_args">Votes</a>
         </font>
        </td>
        <td align="left"> 
         <font face="arial,verdana,times" size="2">|
          <a href="${THIS_CGI}?p=hits&$date_args">Hits</a>
         </font>
        </td>
        <td align="right">
         <font face="arial,verdana,times" size="2">
             &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         </font>
        </td>

        <td align="right">
         <font face="arial,verdana,times" size="2">
             Back logs:
         </font>
        </td>


        <td align="right">
         <select name="ld" value="$logday" size="1">
    );

    for ($i = 1; $i < 32; $i++)
    {
        if ($i == $logday)   { print "<option selected>$i\n"; }
        else { print "<option>$i\n"; }
    }

    print qq(
         </select>
        </td>

        <td align="right">
         <select name="lm" size="1">
    );

    for ($i = 0; $i < 12; $i++)   # what month?
    {
        if ($monthList[$i] eq $logmonth)
        {
            print qq(
              <option selected>$monthList[$i]\n
            );
        }
        else
        {
            print qq(
              <option> $monthList[$i]\n
            );
        }
    }

    print qq(
         </select>
        </td>

        <td align="right">
              <input type="TEXT" name="ly" value="$logyear" default="" size="4">
              <input type="submit" value = "Go">
              <input type="hidden" name="p" value="$page">
              <input type="hidden" name="a" value="$arg1">
              <input type="hidden" name="ud" value="$ud">
              <input type="hidden" name="um" value="$um">
              <input type="hidden" name="uy" value="$uy">
              <input type="hidden" name="bd" value="$bd">
              <input type="hidden" name="bm" value="$bm">
              <input type="hidden" name="by" value="$by">
              <input type="hidden" name="poemNum" value="$poemNum">
        </td>
       </tr>
      </table>
     </form>
    );
}

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

1;

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