#!/usr/bin/perl
use strict 'refs';
use lib '..';
use CGI qw(:standard);
use CGI::Carp qw/fatalsToBrowser/;

$starttime = time;

%months = (0, "January", 1, "February", 2, "March", 3, "April", 4, "May", 5,
  "June", 6, "July", 7, "August", 8, "September", 9, "October", 10, "November", 11, "December");
%days = (0, "Sunday", 1, "Monday", 2, "Tuesday", 3, "Wednesday", 4, "Thursday", 5, "Friday", 6, "Saturday");

print stdout
"Content-type: text/html\n".
"Cache-Control: no-cache\n\n".
"<HTML>\n".
"<HEAD>\n".
"<Title>Splitreflection Web Calendar</Title>\n".
"</HEAD>\n";


sub getlastday{
  for ($lastday = 28; $lastday < 32; $lastday++) {
    if(
       (localtime ($_[0] + ($lastday * 86400)) )[4] != (localtime $_[0])[4] ) {
      return $lastday;
    }
  }
  return $lastday - 1;
}

$startdate = param("start");
$eventdate = param("event");
$action = param("function");
if($startdate != "") {

$startdate = &fixdate($startdate);

print stdout
"<body bgcolor=#000080 link=#FFFF00 vlink=#C0C000 alink=#FFFF88 text=#FFFFFF>\n".
"<table cellspacing=0 border=0 cellpadding=7>\n";
if($credentials{'username'}) {print stdout "<tr><td align='right' colspan=2><font face='Courier' size='2'><a href='?event=new' target='event'>New Event--></a></font></td></tr>\n"; }
print stdout
"<tr><td colspan=3>\n";

print stdout
"<font face='Courier' size=2><b><a href='calendar.pl?start=".($startdate-(4 * 2626201))."'><-- Previous months</a>".
"&nbsp;|&nbsp;";
print stdout
"	<a href='calendar.pl?start=".($startdate+(4*2626201))."'>Next months --></a>\n";

print stdout
"</b></font></th></tr>\n";

for($x = 0; $x < 4; $x++) {
  if($x == 0 || $x == 2) {
    print stdout "	<tr>";
  }
  print stdout "<td valign='top'><b><font face='Courier' size=2>\n";
  $dattoday = $startdate + ($x * 2626201);
  if($y) {$dattoday = $dattoday - ($ltime[3]  * 86400);}
  @ltime = localtime $dattoday;

  $intthisyear = $ltime[5] + 1900;
  $intthismonth = $ltime[4];
  if(time - $dattoday > 1316700) {
    $intthisday = 32;}
  else {
    if(time - $dattoday < -1316700) {
      $intthisday = 0;}
    else {
      $intthisday = (localtime time)[3];}
  }
  $strmonthname = $months{$intthismonth};
  $strweekdayname = $days{$ltime[6]};

#'find the first and last days of this month
  $datfirstday = $dattoday - (($ltime[3] -1)  * 86400) + 1;
  $intfirstweekday = (localtime $datfirstday)[6];
  $intlastday = getlastday($datfirstday);

  $intprintday = 01;

## set up the hash for events
  opendir DIR, "/home/websites/splitreflection.com/htdocs/calendar";
    @listing = readdir DIR;
  closedir DIR;

  %event = {};

  @listing = grep(/\.calendar$/, @listing);
  grep {
    my $done = 0;
    (my $smonth, my $sday, my $syear, my $emonth, my $eday, my $eyear, my $shortdesc) = split "-", $_;
    $shortdesc =~ s/\.calendar$//g;
    $shortdesc =~ s/__/-/g;
    $sday += 1; $sday -= 1;
    $eday += 1; $eday -= 1;

    while(!$done) {
      if($smonth == ($intthismonth+1) && $syear == $intthisyear){
        $event{$sday} = $event{$sday}.",  ".$shortdesc;}
      $sday += 1;
      if($sday > 32) {$sday = 1; $smonth += 1;
        if($smonth > 12) { $smonth = 1; $syear += 1;}
      }
      if(($syear*400)+($smonth*31)+$sday > ($eyear*400)+($emonth*31)+$eday) {$done = 1;}
    }
  } @listing;
  while((my $key, my $value) = each %event) {
    $value =~ s/^,  //g;
    $event{$key} = $value;
  }
##

  print stdout
  "<br>".$strmonthname."&nbsp;".$intthisyear."<br><br>\n".
  "SU MO TU WE TH FR SA<br>\n".
  "--------------------<br>\n";

  $firstday = $intfirstweekday;
  while($intprintday <= $intlastday) {
    $startday = $intprintday;
    for($intLoopDay = 1; $intLoopDay <= 7; $intLoopDay++) {
      if($intfirstweekday) {
        print stdout "&nbsp;&nbsp;";
        $intfirstweekday--;
      }
      else {
if($intprintday < 10) {print stdout "&nbsp;";}
        if($intprintday > $intlastday) {
          print stdout "&nbsp;&nbsp;";
        }
        else {
	  if($intprintday > $intthisday) {
            if($event{$intprintday}) {
              print stdout "<a href='calendar.pl?event=".($intthismonth+1)."-".$intprintday."-".$intthisyear."' title='$event{$intprintday}'target='event'>";
	      if($event{$intprintday} =~ /,  /)
	      {
		print "<font color='#ffcc00'>".$intprintday."</font>";
	      }
	      else
	      {
		print $intprintday;
	      }
	      print "</a>";
            }
            else {
              print stdout "<font color=#cccccc>".$intprintday."</font>";
            }
          }
          else {
            if($event{$intprintday}) {
              print stdout "<a href='calendar.pl?event=".($intthismonth+1)."-".$intprintday."-".$intthisyear."' title='$event{$intprintday}'target='event'>";
	      if($event{$intprintday} =~ /,  /)
	      {
		print "<font color='#ffcc00'>".$intprintday."</font>";
	      }
	      else
	      {
		print $intprintday;
	      }
	      print "</a>";
            }
            else {
              print stdout $intprintday;
            }
          }
        }
        $intprintday++;
      }

    if($intLoopDay < 7) {print " ";}

    }
      print stdout "<br>\n";
  }
  print stdout
  "</td>\n";
  if($x == 1 || $x == 3) {
    print stdout "	</TR>";
  }
}
print stdout
"</TABLE>\n".
"</BODY>\n".
"</HTML>\n";
}
else { if($eventdate =~ /.../) {
print stdout
"<body bgcolor=#000080 link=#FFFF00 vlink=#C0C000 alink=#FFFF88 text=#FFFFFF>\n";
  if ($eventdate =~ /.*-*.-..../ ) {
    (my $month, my $day, my $year) = split "-", $eventdate;
    opendir DIR,"/home/websites/splitreflection.com/htdocs/calendar";
    @listing = readdir DIR;
    close DIR;
    
    @listing = grep(/\.calendar$/, @listing);

    grep {
      (my $smonth, my $sday, my $syear, my $emonth, my $eday, my $eyear, my $shortdesc) = split "-", $_;
      $shortdesc =~ s/\.calendar$//;
      $shortdesc =~ s/__/-/g;
      if ((($syear*400)+($smonth*31)+$sday <= ($year*400)+($month*31)+$day) &&
          (($eyear*400)+($emonth*31)+$eday >= ($year*400)+($month*31)+$day)) {
        $event{$shortdesc} = $_; }
    } @listing;

    print stdout
"<table border=1><tr><td align='center'><font face='Courier' size=4><i><b>Events on $eventdate</b></i></font></td></tr>\n";

    while ((my $key, my $value) = each %event) {
      open EVNT, "/home/websites/splitreflection.com/htdocs/calendar/$value";
      @data = <EVNT>;
      close EVNT;
      $dta = join "<br>\n", @data;

      (my $smonth, my $sday, my $syear, my $emonth, my $eday, my $eyear, my $shortdesc) = split "-", $value;
      $shortdesc =~ s/__/-/g;
      print stdout
"<tr><td><font face='Courier'><b>--$key--</b><br>\n".
"From: &nbsp;$smonth-$sday-$syear<br>\n".
"To: &nbsp; &nbsp;$emonth-$eday-$eyear<br><br>\n".$dta."</font>";

if($credentials{'username'}) {
  print stdout
    "<br>\n<font face='Courier' size=2><a href='calendar.pl?event=new&file=$value'>Edit Entry</a>";
}

print stdout "</td></tr>\n";
    }
  } 
print stdout "</table>\n";

if($credentials{'username'} && $eventdate eq "new") {
  my $filename = param('file');
  $filename =~ s/\%20/ /g;
  (my $smonth, my $sday, my $syear, my $emonth, my $eday, my $eyear, my $shortdesc) = split "-", $filename;
  $shortdesc =~ s/\.calendar$//;
  $shortdesc =~ s/__/-/g;
  my $owner;
  my $dta;

  if($filename =~ /\.calendar$/) {
    open FILE, "/home/websites/splitreflection.com/htdocs/calendar/$filename";
    my @data = <FILE>;
    close FILE;
    $dta = join "", @data;
    $owner = $dta;
    $owner =~ s/^(Last edited on [^ ]* by [^ \r\n]*).*/$1/;
    $dta =~ s/^Last edited on [^ ]* by [^ \r\n]*//;
    $owner =~ s/.* ([^ ]*)/$1/;
  }
  else {
    my @ltime = localtime time;
    $smonth = $emonth = $ltime[4] + 1;
    $syear = $eyear = $ltime[5] + 1900;
    $sday = $eday = $ltime[3];
  }
    
  print stdout
"<script language='javascript'>\n".
"  function update(object, value) {\n".
"    object.value = value;\n".
"  }\n".
"</script>\n".
"<table><tr><td align='center'><font face='Courier' size=4>".
"Add/Edit Calendar Entry</font></td></tr>".
"<tr><td><font face='Courier'><form method='post' name='edit' action='calendar.pl'>".
"<input type='hidden' name='filename' value='$filename'>".
"<table><tr><td><font face='Courier'>Name:</font></td><td><input type='text' name='shortdesc' value='$shortdesc' size=25>".
"</td></tr><tr><td>".
"<font face='Courier'>Start:</font></td><td><select name='smonth' onChange='update(forms.edit.emonth, this.value)'>";

  my $count = 1;
  while($count < 13) {
    print stdout "<option value=$count";
    if($smonth == $count) { print stdout " selected";}
    print stdout ">$months{$count - 1}\n";
    $count += 1;
  }
  print stdout "</select>".
"<select name='sday' onChange='update(forms.edit.eday, this.value)'>";

  my $count = 1;
  while($count < 32) {
    print stdout "<option value=$count";
    if($sday == $count) { print stdout " selected";}
    print stdout ">$count\n";
    $count += 1;
  }
  print stdout "</select> ".
"<input type='text' name='syear' value='$syear' size=4 onChange='update(forms.edit.eyear, this.value)'><br>".
"</td></tr><tr><td><font face='Courier'>End:</font></td><td><select name='emonth'>";

  my $count = 1;
  while($count < 13) {
    print stdout "<option value=$count";
    if($emonth == $count) { print stdout " selected";}
    print stdout ">$months{$count - 1}\n";
    $count += 1;
  }
  print stdout "</select>".
"<select name='eday'>";

  my $count = 1;
  while($count < 32) {
    print stdout "<option value=$count";
    if($eday == $count) { print stdout " selected";}
    print stdout ">$count\n";
    $count += 1;
  }
  print stdout "</select> ".
"<input type='text' name='eyear' value='$eyear' size=4></td></tr>".
"<tr><td valign='top'></td><td>".
"<textarea name='description' cols=20 rows=8>$dta</textarea>".
"</td></tr><tr><td></td><td><input type='submit' name='function' value='submit'>".
" &nbsp; <input type='submit' name='function' value='delete entry'>".
"</td></tr></table></form></td></tr></table>";

}
print stdout "</body></html>";
}
else { if($action =~ /.../) {
print stdout
"<body bgcolor=#000080 link=#FFFF00 vlink=#C0C000 alink=#FFFF88 text=#FFFFFF>\n";
if($credentials{'username'}) {
  $filename = param('filename');
  $shortdesc = param('shortdesc');
  $shortdesc =~ s/-/__/g;
  $shortdesc =~ s/'//g;
  $shortdesc =~ s/\&/and/g;
  $smonth = param('smonth');
  if($smonth < 10){$smonth = "0".$smonth;}
  $sday = param('sday');
  if($sday < 10){$sday = "0".$sday;}
  $syear = param('syear');
  $emonth = param('emonth');
  if($emonth < 10){$emonth = "0".$emonth;}
  $eday = param('eday');
  if($eday < 10){$eday = "0".$eday;}
  $eyear = param('eyear');
  $description = param('description');

  if(($syear*400)+($smonth*31)+$sday > ($eyear*400)+($emonth*31)+$eday) {
    $eyear = $syear;
    $emonth = $smonth;
    $eday = $sday;
  }


  my @ltime = localtime time;
  my $month = $ltime[4] + 1;
  my $day = $ltime[3];
  my $year = $ltime[5] + 1900;

  unlink "/home/websites/splitreflection.com/htdocs/calendar/$filename";

  if($action eq "submit") {
    open FILE, ">/home/websites/splitreflection.com/htdocs/calendar/$smonth-$sday-$syear-$emonth-$eday-$eyear-$shortdesc.calendar";
    print FILE "Last edited on $month-$day-$year by $credentials{'username'}\n".
    $description;
    close FILE;
  }

print stdout
"<script language='javascript'>\n".
"parent.calendar.location = parent.calendar.location;\n".
"window.location = 'calendar.pl?event=$smonth-$sday-$syear';".
"</script>";
}
else { print stdout "Your session has timed out."; }

print stdout "</body></html>";
}
else {
$startdate = (time - (2626201));

print stdout
"<frameset cols='424,*' border=0 frameborder='no'>\n".
"<frame src='calendar.pl?start=".$startdate."' name='calendar'>\n".
"<frame src='calendar.pl?event=new' name='event'>\n".
"</frameset></html>";

}}}
#sub param {
#  $param = $ENV{QUERY_STRING};
#  $param =~ s/.*$_[0]=//g;
#  $param =~ s/&.*//g;
#  return $param;
#}

sub fixdate {
  my $date = $_[0];
  my @ltime = localtime $date;
  $date = $date - ($ltime[0] + ($ltime[1] * 60) + ($ltime[2] * 3600) + ($ltime[3] * 86400));
  $date = $date + (3 * 86400);
#  $date = $date + (15 * 86400);
  return $date;
}

sub timer {
	if(time > ($starttime + 60)){print stdout "Script Timeout in ".$_[0]; exit;}
	}
