#!/usr/bin/perl
# 
# Calendar Admin Script
#
# Matt Kruse
# http://www.mattkruse.com/
#

$|=1;
print "Content-type: text/html\n\n";

$base_dir = "/homed/globalta/calendar/";

#####################################################################
#
# SPLASH()
#
# Splash Screen
#
#####################################################################
sub SPLASH {
	print <<"END";
<HTML>
<HEAD><TITLE>Calendar Administration</TITLE>
<style>
<!--
$ADMIN_STYLES
-->
</style></HEAD>
<BODY BGCOLOR=white onLoad="document.forms[0].username.focus();">
<BR><BR>
<CENTER>
<TABLE BORDER=1 BORDERCOLOR="#333333" CELLSPACING=0 WIDTH=400 CELLPADDING=3>
<TR>
	<TD ALIGN=CENTER BGCOLOR="#000080"><FONT COLOR="white" FACE="arial"><B>Calendar Administration</B></FONT></TD>
</TR>
<TR>
	<TD BGCOLOR="#CCCCCC">
	<B>Author</B>: <A HREF="mailto:mkruse\@netexpress.net">Matt Kruse</A><br>
	<B>Web Site</B>: <A HREF="http://www.mattkruse.com/scripts/calendar/">http://www.mattkruse.com/scripts/calendar/</A><br>
	<CENTER>
	<BR>
	<B><U>THIS PROGRAM IS FREE SOFTWARE</U></B>
	</CENTER>
	<UL>However...
		<LI>It may not be re-distributed
		<LI>It may not be sold
	</UL>
	<CENTER>
	<B><U>THE POSTCARD INITIATIVE</U></B><br>
	</CENTER>
	This program is free, but I would appreciate receiving a <B>postcard</B> from you as a <B>Thank-You</B> for my time. If used for company purposes, a <font size=+1 color=green><B>\$50</B></font> donation is appreciated. Actually, any donation at all is appreciated! :)<br><br>
	<CENTER>
	<TABLE BORDER=1 CELLSPACING=0>
	<TR><TD>Matt Kruse<br>5510 31st Ave Ct.<br>Moline, IL 61265</TD></TR>
	</TABLE>
	<BR>
	<form action="$vars{cgi}" method=post><input type="hidden" name="OK" value="OK"><tt>
		<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Login:&nbsp;</b><input name="username" value="" size=20><br>
		<b>&nbsp;&nbsp;&nbsp;Password:&nbsp;</b><input type="password" name="password" value="" size=20><br>
		<b>Config File:&nbsp;</b><input name="config" value="calendar.cfg" size=20><br><br>
		<input type="submit" CLASS="button" value="     OK     ">
	</tt></form>
	</CENTER>
	
	</TD>
</TR>
</TABLE>
</BODY>
</HTML>
END
	exit(0);
	}

	
	
#####################################################################
#
# ADMIN()
#
# Main Admin page
#
#####################################################################
sub ADMIN {

	if ($vars{html_heading} eq "yes") { $html_heading = " CHECKED "; }
	if ($vars{html_description} eq "yes") { $html_description= " CHECKED "; }
	$monsunweek{$vars{monsunweek}} = " CHECKED ";
	unless ($vars{calendarurl} =~ /http/) {
		$vars{calendarurl} = "http://" . $ENV{SERVER_NAME} . $vars{cgi};
		$vars{calendarurl} =~ s|_admin||;
		$vars{message} .= "\\n\\nYour calendar URL needs to be entered. A URL has been entered for you based on this admin utility.\\n\\nYou must Save Options before this takes effect.";
		}
	opendir(DIR,$vars{template_dir});
	$calendar_template_options = "";
	$viewday_template_options = "";
	while ($file = readdir(DIR)) {
		$selected = "";
		if ($file =~ /^calendar.*\.html/) { 
			$title = $file;
			$title =~ m|^calendar_?(.*)\.html|i;
			$title = $1;
			$title =~ s|_| |g;
			if ($vars{calendar_html} =~ /$file/) {
				$selected = " SELECTED ";
				}
			$calendar_template_options .= "<OPTION VALUE=\"[template_dir]/$file\" $selected>$title";
			}
		if ($file =~ /^viewday.*\.html/) { 
			$title = $file;
			$title =~ m|^viewday_?(.*)\.html|i;
			$title = $1;
			$title =~ s|_| |g;
			if ($vars{viewday_html} =~ /$file/) {
				$selected = " SELECTED ";
				}
			$viewday_template_options .= "<OPTION VALUE=\"[template_dir]/$file\" $selected>$title";
			}
		}
	closedir(DIR);

	print <<"END";
<HTML>
<HEAD><TITLE>Calendar Administration</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function showmessage(msg) {
	if (msg != "") {
		alert(msg);
		}
	}
function MonSunWeek(x,theform) {
	if (x == 'No') {
		temp=theform.dayname7.value;
		theform.dayname7.value=theform.dayname6.value;
		theform.dayname6.value=theform.dayname5.value;
		theform.dayname5.value=theform.dayname4.value;
		theform.dayname4.value=theform.dayname3.value;
		theform.dayname3.value=theform.dayname2.value;
		theform.dayname2.value=theform.dayname1.value;
		theform.dayname1.value=temp;
		}
	if (x == 'Yes') {
		temp=theform.dayname1.value;
		theform.dayname1.value=theform.dayname2.value;
		theform.dayname2.value=theform.dayname3.value;
		theform.dayname3.value=theform.dayname4.value;
		theform.dayname4.value=theform.dayname5.value;
		theform.dayname5.value=theform.dayname6.value;
		theform.dayname6.value=theform.dayname7.value;
		theform.dayname7.value=temp;
		}
	return true;
	}
	
</SCRIPT>
<style>
<!--
$ADMIN_STYLES
-->
</style>
</HEAD>
<BODY BGCOLOR=white onLoad='showmessage("$vars{message}")'>
$ADMIN_PAGE_TOP
	<!-- General Options -->	
	<FORM ACTION=$vars{cgi} METHOD=POST>
	<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
	<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
	<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
	<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="OPTIONS">
	<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">

	<B>General&nbsp;Options</B>
	<HR SIZE=1>

	URL of Calendar Program: <INPUT NAME="calendarurl" size=30 value="$vars{calendarurl}"><br>
	
	<br>

	<INPUT TYPE="checkbox" name="html_heading" VALUE="yes" $html_heading> Allow HTML tags in headings<br>
	<INPUT TYPE="checkbox" name="html_description" VALUE="yes" $html_description> Allow HTML tags in descriptions<br>

	<br>
	
	Highlight today using <INPUT NAME="bgcolor_today" VALUE="$vars{bgcolor_today}" SIZE=25><br>
	Highlight selected day using <INPUT NAME="bgcolor_current" VALUE="$vars{bgcolor_current}" SIZE=25><br>
	Highlight other days using <INPUT NAME="bgcolor_day" VALUE="$vars{bgcolor_day}" SIZE=25><br>

	<br>
	
	Calendar Template: <SELECT NAME="calendar_html">$calendar_template_options</SELECT>
	<br>
	Day View Template: <SELECT NAME="viewday_html">$viewday_template_options</SELECT>
	<br>
	<br>
	Adjust for server's time zone: <INPUT SIZE=3 NAME="time_offset" VALUE="$vars{time_offset}"> hours
	<br>
	<br>
	Weeks start on: <INPUT TYPE="radio" NAME="monsunweek" VALUE="No" $monsunweek{No} onClick="MonSunWeek('No',this.form)">Sunday&nbsp;&nbsp;<INPUT TYPE="radio" NAME="monsunweek" VALUE="Yes" $monsunweek{Yes} onClick="MonSunWeek('Yes',this.form)">Monday<br>
	Weekday Names:<br>
	<input size="6" name="dayname1" value="$vars{dayname1}"> <input size="6" name="dayname2" value="$vars{dayname2}"> <input size="6" name="dayname3" value="$vars{dayname3}"> <input size="6" name="dayname4" value="$vars{dayname4}"> <input size="6" name="dayname5" value="$vars{dayname5}"> <input size="6" name="dayname6" value="$vars{dayname6}"> <input size="6" name="dayname7" value="$vars{dayname7}"><br>
	Month Names:<br>
	<input size="6" name="month1" value="$vars{month1}"> <input size="6" name="month2" value="$vars{month2}"> <input size="6" name="month3" value="$vars{month3}"> <input size="6" name="month4" value="$vars{month4}"> <input size="6" name="month5" value="$vars{month5}"> <input size="6" name="month6" value="$vars{month6}"> <br>
	<input size="6" name="month7" value="$vars{month7}"> <input size="6" name="month8" value="$vars{month8}"> <input size="6" name="month9" value="$vars{month9}"> <input size="6" name="month10" value="$vars{month10}"> <input size="6" name="month11" value="$vars{month11}"> <input size="6" name="month12"  value="$vars{month12}"> <br>
	Month Abbreviations:<br>
	<input size="6" name="shortmonth1" value="$vars{shortmonth1}"> <input size="6" name="shortmonth2" value="$vars{shortmonth2}"> <input size="6" name="shortmonth3" value="$vars{shortmonth3}"> <input size="6" name="shortmonth4" value="$vars{shortmonth4}"> <input size="6" name="shortmonth5" value="$vars{shortmonth5}"> <input size="6" name="shortmonth6" value="$vars{shortmonth6}"> <br>
	<input size="6" name="shortmonth7" value="$vars{shortmonth7}"> <input size="6" name="shortmonth8" value="$vars{shortmonth8}"> <input size="6" name="shortmonth9" value="$vars{shortmonth9}"> <input size="6" name="shortmonth10" value="$vars{shortmonth10}"> <input size="6" name="shortmonth11" value="$vars{shortmonth11}"> <input size="6" name="shortmonth12" value="$vars{shortmonth12}"> <br>

	<br>

	<CENTER><INPUT TYPE="submit" CLASS="button" value="   Save Options   "></CENTER>
	</FORM>

	<HR SIZE=1>
$ADMIN_PAGE_BOTTOM
END
	exit(0);
	} #end of ADMIN

	
#####################################################################
#
# OPTIONS()
#
# Save Options
#
#####################################################################
sub OPTIONS {
	my $config_file = $vars{base_dir} . $in{config};
	open(IN,$config_file) || &Error("Can't open $config_file.");
	undef $/;
	my $cfg = <IN>;
	close(IN);
	
	$in{months} = join(',', ($in{month1},$in{month2},$in{month3},$in{month4},$in{month5},$in{month6},$in{month7},$in{month8},$in{month9},$in{month10},$in{month11},$in{month12}) );
	$in{shortmonths} = join(',', ($in{shortmonth1},$in{shortmonth2},$in{shortmonth3},$in{shortmonth4},$in{shortmonth5},$in{shortmonth6},$in{shortmonth7},$in{shortmonth8},$in{shortmonth9},$in{shortmonth10},$in{shortmonth11},$in{shortmonth12}) );
	$in{days} = join(',' , ($in{dayname1}, $in{dayname2}, $in{dayname3}, $in{dayname4}, $in{dayname5}, $in{dayname6}, $in{dayname7}) );
	foreach (	'months',
				'shortmonths',
				'days',
				'monsunweek',
				'calendarurl',
				'html_heading',
				'html_description',
				'bgcolor_today',
				'bgcolor_current',
				'bgcolor_day',
				'calendar_html',
				'viewday_html',
				'time_offset'
				) {
		$cfg =~ s|^$_=.*|$_=$in{$_}|mg;
		}

	open(OUT,"> $config_file") || &Error( "Can't open $config_file for writing.");
	eval "flock OUT,2";
	print OUT $cfg;
	close(OUT);
	
	$/ = "\n";
	&read_config;
	$vars{message} = "Options Saved";
	&ADMIN;
	
	} # end of OPTIONS

	
#####################################################################
#
# Change username/password
#
#####################################################################
sub PASSWORD {
	print <<"END";
<HTML>
<HEAD><TITLE>Calendar Administration</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function showmessage(msg) {
	if (msg != "") {
		alert(msg);
		}
	}
function validate(theform) {
	if (theform.new_username.value == "") {
		alert("You must specify a login name");
		return false;
		}
	if (theform.new_password.value != theform.new_password_confirm.value) {
		alert("Passwords do not match!");
		return false;
		}
	return true;
	}
</SCRIPT>
<style>
<!--
 A { text-decoration:none; }
$ADMIN_STYLES
-->
</style>
</HEAD>
<BODY BGCOLOR="#ffffff" LINK="#000080" ALINK="#000080" VLINK="#000080" onLoad='showmessage("$vars{message}");'>
$ADMIN_PAGE_TOP
		<BR><BR>
		<form action="$vars{cgi}" method=post onSubmit="return validate(this)">
		<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
		<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="SAVE_PASSWORD">
		<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
		<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
		<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
		<table border=0>
		<tr>
			<TD ALIGN=right><B>New Admin Username</B>: </TD>
			<TD><INPUT TYPE="text" NAME="new_username" SIZE=15 VALUE="$in{username}"></TD>
		<tr>
		<tr>
			<TD ALIGN=RIGHT><B>New Password</B>: </TD>
			<TD><INPUT TYPE="password" NAME="new_password" SIZE=20 VALUE="$in{password}"></TD>
		</tr>
		<tr>
			<TD ALIGN=RIGHT><B>Confirm Password</B>: </TD>
			<TD><INPUT TYPE="password" NAME="new_password_confirm" SIZE=20 VALUE="$in{password}"></TD>
		</tr>
		<tr>
			<TD></TD>
			<TD><br><INPUT TYPE="Submit" CLASS="button" VALUE="Save Changes"></TD>
		</tr>
		</table>

		</form>
		
$ADMIN_PAGE_BOTTOM
END
	exit(0);
	}

	
	
#####################################################################
#
# Save New Password
#
#####################################################################
sub SAVE_PASSWORD {
	my $config_file = $vars{base_dir} . $in{config};
	open(IN,$config_file) || &Error("Can't open $config_file.");
	undef $/;
	my $cfg = <IN>;
	close(IN);
	
	$new_username = crypt($in{new_username},time);
	$new_password = crypt($in{new_password},time);
	$cfg =~ s|^username=.*|username=$new_username|mg;
	$cfg =~ s|^password=.*|password=$new_password|mg;

	open(OUT,"> $config_file") || &Error( "Can't open $config_file for writing.");
	eval "flock OUT,2";
	print OUT $cfg;
	close(OUT);
	
	$/ = "\n";
	&read_config;
	print <<"END";
<HTML>
<HEAD><TITLE>Calendar Administration</TITLE>
<style>
<!--
 A { text-decoration:none; }
$ADMIN_STYLES
-->
</style>
</HEAD>
<BODY BGCOLOR="#ffffff" LINK="#000080" ALINK="#000080" VLINK="#000080">
$ADMIN_PAGE_TOP
	<CENTER>
	<B>Username/Password changed.</B><br><br>
	You will now need to re-login under the new settings.<BR><BR>

	<FORM ACTION=$vars{cgi} METHOD=POST>
	<INPUT TYPE="SUBMIT" STYLE="background-color:#eeeeee;font:arial;font-weight:bold;color:#000080;font-size:xx-small;width:130;" 
	       VALUE="Admin Login">
	</FORM>
	</CENTER>
$ADMIN_PAGE_BOTTOM
END
	exit(0);
	} # end of OPTIONS

	
#####################################################################
#
# Support Stuff
#
#####################################################################
sub SUPPORT {
	print <<"END";
<HTML>
<HEAD><TITLE>Calendar Administration</TITLE>
<style>
<!--
$ADMIN_STYLES
-->
</style>
</HEAD>
<BODY BGCOLOR="#ffffff" LINK="#000080" ALINK="#000080" VLINK="#000080">
$ADMIN_PAGE_TOP

<B>Support Information</B>
<HR NOSHADE SIZE=1>
<UL>
<LI>I try to support this application when I can, how I can. Because I offer it for free, support is <U>NOT GUARANTEED</U>.
<BR><BR>
<LI>Please use my <A HREF="http://www.mattkruse.com/scripts/support/wwwboard/">Script Support Forum</A> for posting questions about this script. It is much easier for me than email, and others may be able to help. Before asking for support, be sure to check the <A HREF="http://www.mattkruse.com/scripts/calendar/docs/">Documentation</A>!
<BR><BR>
<LI>If you have created a template that others may be interested in (such as a language-translation) please <A HREF="mailto:mkruse\@netexpress.net">Mail Me</A> and let me know!
<BR><BR>
<LI>If you have legal/license questions, see my	<A HREF="http://www.mattkruse.com/scripts/legal.html">Legal Information</A> page.
<BR><BR>
<LI>Subscribe to my Email Update list to be mailed about updates to this program.
	<FORM ACTION="http://www.mattkruse.com/scripts/support/subscribe/subscribe.pl" METHOD="POST">
	<INPUT TYPE="TEXT" SIZE="20" NAME="email" VALUE="your email address"><br>
	<INPUT TYPE="RADIO" NAME="subscribe" VALUE="subscribe" CHECKED="CHECKED" ALIGN="TOP"> subscribe <INPUT TYPE="RADIO" NAME="subscribe" VALUE="unsubscribe" ALIGN="TOP"> unsubscribe <INPUT TYPE="SUBMIT" CLASS="button" VALUE="Submit">
	</FORM>
<LI>Please rate this script on a scale of 1-10, 10 being the best. This rating is 
used at <A href="http://www.cgi-resources.com/">www.cgi-resources.com</A> in 
their list of rated resources and helps other people find this script and judge 
its quality. <BR>
<BLOCKQUOTE>
<FORM action=http://cgi-resources.com/rate/index.cgi method=post><INPUT 
name=referer type=hidden value=http://cgi-resources.com/> <INPUT name=link_code 
type=hidden value=01771> <INPUT name=category_name type=hidden 
value="Programs and Scripts/Perl/Calendars/"> <INPUT name=link_name type=hidden 
value="Matt Kruse's Calendar Script"> <FONT face=Verdana,Arial,Helvetica 
size=-1><B>Script Rating: </B></FONT><SELECT name=rating><OPTION 
selected>--<OPTION VALUE="10">10 (Best)<OPTION>9<OPTION>8<OPTION>7<OPTION>6<OPTION>5<OPTION>4<OPTION>3<OPTION>2<OPTION>1</OPTION></SELECT> 
<INPUT type=submit CLASS="button" value="Rate It!"> </FORM></BLOCKQUOTE>

<LI>Please use this form to give me general feedback about this script. It will help me improve it and make it a better program! You can submit your comments anonymously if you wish. 
	<TABLE border=1 cellPadding=3 cellspacing=0>
	<form method=post action="http://www.mattkruse.com/scripts/support/feedback.pl">
	<input type=hidden name="SCRIPT" value="Calendar 2.2 - REMOTE">
	<input type=hidden name="RETURN" value="http://www.mattkruse.com/scripts/calendar/">
	<tr>
		<td>Name</td>
		<td><input size="40" name="name"></td>
	</tr>
	<tr>
		<td>Email</td>
		<td><input size="40" name="email"></td>
	</tr>
	<tr>
		<td>Comments</td>
		<td><textarea name="comments" cols=40 wrap=hard rows=5></textarea></td>
	</tr>
	<tr>
		<td colspan=2 align=center><input type="submit" CLASS="button" value="Send Comments"></td>
	</tr>
	</table>
	</form>


</UL>
		
$ADMIN_PAGE_BOTTOM
END
	exit(0);
	}

	
	
#####################################################################
#
# ADD()
#
# Form to add an entry
#
#####################################################################
sub ADD {	
	print <<"END";
<HTML>
<HEAD><TITLE>Calendar Administration</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function verifyform(theform) {
	if (theform.month.value<1 || theform.month.value>12) {
		alert("Month is invalid");
		return false;
		}
	if (theform.date.value<1 || theform.date.value>31) {
		alert("Date is invalid");
		return false;
		}
	if (theform.year.value<0 || theform.year.value == "") {
		alert("Year is invalid");
		return false;
		}
	if (theform.heading.value == "") {
		alert("Heading is required");
		return false;
		}
	if (theform.description.value == "") { 
		alert("Description is required");
		return false;
		}
	return true;
	} // end of function
function showmessage(msg) {
	if (msg != "") {
		alert(msg);
		}
	}
</SCRIPT>
<style>
<!--
$ADMIN_STYLES
-->
</style>
</HEAD>
<BODY BGCOLOR=white onLoad='showmessage("$vars{message}")'>
$ADMIN_PAGE_TOP
		<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=3>
			<form action="$vars{cgi}" method=post onSubmit="return verifyform(this);">
			<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
			<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
			<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
			<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
			<input type="hidden" name="ACTION" value="DO_ADD">
			<TR>
				<TD ALIGN=RIGHT><B>Add&nbsp;Event</B></TD>
				<TD WIDTH=100%><HR SIZE=1></TD>
			</TR>			
			<TR>
				<TH BGCOLOR="#CCCCCC">Date</TH>
				<TD BGCOLOR="#CCCCCC">
					<input name="month" size=2 maxlength=2 value="$vars{month}"> / <input name="date" size=2 maxlength=2 value="$vars{date}"> / <input name="year" size=4 maxlength=4 value="$vars{year}">&nbsp;&nbsp;
					<input type="checkbox" name="annual" value="1" onClick="if(form.annual.checked == true){form.year.value='0000'}else{form.year.value=''}"> Every Year
				</TD>
			</TR>
			<TR>
				<TH BGCOLOR="#CCCCCC">Heading</TH>
				<TD BGCOLOR="#CCCCCC"><input name="heading" size=30></TD>
			</TR>
			<TR>
				<TH BGCOLOR="#CCCCCC">Description</TH>
				<TD BGCOLOR="#CCCCCC" COLSPAN=3><textarea name="description" cols=40 rows=3></textarea></TD>
			</TR>
			<TR>
				<TD COLSPAN=2 ALIGN=RIGHT BGCOLOR="#CCCCCC"><input type="reset" value="Clear" CLASS="button" >&nbsp;&nbsp;&nbsp;<input type="submit" value="Save" CLASS="button" >
				</form>
				</TD>
			</TR>
			<TR>
				<TD COLSPAN=2><HR SIZE=1></TD>
			</TR>
		</TABLE>
$ADMIN_PAGE_BOTTOM
END
	exit(0);
	} #end of ADD

	
#####################################################################
#
# DO_ADD()
#
# Add an entry
#
#####################################################################
sub DO_ADD
{ $in{description} =~ s|[\r\n]+|<BR>|gs;
  $in{month} =~ s|^(\d)$|0$1|;
  $in{date}  =~ s|^(\d)$|0$1|;
  my $datestamp = $in{year} . $in{month} . $in{date};

  if ($datestamp =~ /^\d\d\d\d\d\d\d\d$/)
  { open(OUT,">> $vars{calendar_file}") || &Error( "Can't open $calendar_file for writing!");
    eval "flock OUT,2";
# jxl event data
    print OUT "$vars{new_id}|$vars{loginid}|$vars{eventkey}|$vars{phonenum}|$datestamp|$in{heading}|$in{description}\n";

    close(OUT);
    $vars{'message'} = "Event Added";
  }
  else
  { $vars{'message'} = "ERROR: Event not added";
  }
  &ADD;
  exit(0);
} # end of DO_ADD

	
#####################################################################
#
# EDIT()
#
# Edit/Delete Entries
#
#####################################################################
sub EDIT {	
	my $x;

	$x = $vars{month};	
	$monthselected{$x} = " SELECTED ";
	$x = $vars{year};
	$yearselected{$x} = " SELECTED ";

	print <<"END";
<HTML>
<HEAD><TITLE>Calendar Administration</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function eventdetails(id) {
	window.open('$vars{cgi}?ACTION=EVENTDETAILS&id=' + id,'EVENTDETAILS','scrollbars,resizable,height=250,width=400');
	}
function verify() {
	return confirm("Are you sure?");
	}
function showmessage(msg) {
	if (msg != "") {
		alert(msg);
		}
	}
</SCRIPT>
<style>
<!--
$ADMIN_STYLES
-->
</style>
</HEAD>
<BODY BGCOLOR="#ffffff" LINK="#000080" ALINK="#000080" VLINK="#000080" onLoad='showmessage("$vars{message}");'>
$ADMIN_PAGE_TOP
		<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=3>
			<TR>
				<TD ALIGN=RIGHT><B>Edit&nbsp;Events</B></TD>
				<TD WIDTH=100%><HR SIZE=1></TD>
			</TR>	
		</TABLE>	
		<CENTER>
		<form action="$vars{cgi}" method=post>
		<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
		<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="EDIT">
		<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
		<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
		<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
		<INPUT TYPE="HIDDEN" NAME="month" VALUE="$vars{lastmonth}">
		<INPUT TYPE="HIDDEN" NAME="year" VALUE="$vars{lastyear}">
		<select name="Month" size=1>
			<option value="1" $monthselected{'1'}>January
			<option value="2" $monthselected{'2'}>February
			<option value="3" $monthselected{'3'}>March
			<option value="4" $monthselected{'4'}>April
			<option value="5" $monthselected{'5'}>May
			<option value="6" $monthselected{'6'}>June
			<option value="7" $monthselected{'7'}>July
			<option value="8" $monthselected{'8'}>August
			<option value="9" $monthselected{'9'}>September
			<option value="10" $monthselected{'10'}>October
			<option value="11" $monthselected{'11'}>November
			<option value="12" $monthselected{'12'}>December
		</select>
		<select name="Year" size=1>
			<option value="1997" $yearselected{1997}>1997
			<option value="1998" $yearselected{1998}>1998
			<option value="1999" $yearselected{1999}>1999
			<option value="2000" $yearselected{2000}>2000
			<option value="2001" $yearselected{2001}>2001
			<option value="2002" $yearselected{2002}>2002
			<option value="2003" $yearselected{2003}>2003
		</select>
		<input type="submit" value="Go" CLASS="button" ><br>
		</FORM>
		</CENTER>

		<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=3 WIDTH=100%> 
		<form action="$vars{cgi}" method=post onSubmit="return verify();">
		<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
		<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="DO_EDIT">
		<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
		<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
		<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
		<TR>
			<TD VALIGN=BOTTOM ALIGN=CENTER><B>Date</B></TD>
			<TD VALIGN=BOTTOM ALIGN=CENTER WIDTH=100%><B>Heading</B><br><FONT COLOR=red SIZE=+1>*</FONT> = Annual Event</TD>
			<TD VALIGN=BOTTOM ALIGN=CENTER><B>Action</B></TD>
		</TR>
END
	foreach $datestamp ( sort keys %events ) {
		($year,$month,$date) = ($datestamp =~ /(\d\d\d\d)(\d\d)(\d\d)/o);
		next unless ($month==$vars{month} && ($year==$vars{year}||$year eq "0000"));
		foreach $i ( sort keys %{$events{$datestamp}} ) {
			if ($year eq "0000") { $annual = "<FONT COLOR=red SIZE=+1>*</FONT>"; }
				else { $annual=""; }		
			print "<TR><TD ALIGN=CENTER>${month}/${date}</TD><TD>$annual <A HREF=\"javascript:eventdetails('${$events{$datestamp}}{$i}{id}');\">${$events{$datestamp}}{$i}{label}</A></TD>\n";
			print "    <TD><input CLASS=\"button\" type=\"submit\" name=\"ID${$events{$datestamp}}{$i}{id}\" VALUE=\"Edit\">&nbsp;&nbsp;<input type=\"submit\" CLASS=\"button\" name=\"ID${$events{$datestamp}}{$i}{id}\" VALUE=\"Delete\"></TD>\n";
			print "</TR>\n";
			}
		}
	print <<"END";
		</form>
		</TABLE>
$ADMIN_PAGE_BOTTOM
END
	exit(0);
	} #end of EDIT

	
#####################################################################
#
# EVENTDETAILS()
#
# Show details of an event in pop-up window
#
#####################################################################
sub EVENTDETAILS {	
        my $zjunk;
	open(IN,"$vars{calendar_file}") || &Error( "Can't open $vars{calendar_file}");
	my $header = <IN>;
	while (<IN>) {
		chomp;
# jxl event data
                ($id,$zloginid,$zeventkey,$zphonenum,$xdatestamp,$label,$description,$zjunk) = split(/\|/,$_,8);
		next unless ($id == $in{id});
		($year,$month,$date) = ($xdatestamp =~ /(\d\d\d\d)(\d\d)(\d\d)/);
		if ($year eq "0000") {
			$year = " (Annual)";
			}
		else {
			$year = ", $year";
			}
		last;
		}
	close(IN);
	print <<"END";	
<HTML>
<HEAD>
	<TITLE>$label</TITLE>
</HEAD>
<BODY BGCOLOR="#ffffff" LINK="#000080" ALINK="#000080" VLINK="#000080" LEFTMARGIN=3 RIGHTMARGIN=3 TOPMARGIN=3 MARGINWIDTH=3 MARGINHEIGHT=3>
<font size="+1" face="verdana,arial">$label</font><br>
<HR WIDTH=75% ALIGN=LEFT SIZE=1 NOSHADE>
<DL>
<DT><B>When</B>
	<DD>$month/$date$year
<DT><B>Description</B>
	<DD>$description
</DL>
<HR>
<CENTER><FORM><INPUT TYPE="button" VALUE="Close" onClick="window.close();"></FORM></CENTER>
</BODY>
</HTML>
END
	exit(0);
	} # end	

	
#####################################################################
#
# DO_EDIT()
#
# Edit/Delete Entries
#
#####################################################################
sub DO_EDIT {	
	# Get ID of button pressed
	foreach (keys %in) { if (/^ID(\d+)/) { $id = $1; } }
	if ($in{"ID$id"} eq "Edit") {
		&EDITFORM($id);
		}
	elsif ($in{"ID$id"} eq "Delete") {
		&DELETE($id);
		}
	else { &ADMIN; }
	exit(0);
	}

	
#####################################################################
#
# EDITFORM()
#
# Form to edit an entry
#
#####################################################################
sub EDITFORM {
	$vars{id} = shift;
	open(IN,"$vars{calendar_file}") || &Error( "Can't open $vars{calendar_file}");
	my $header = <IN>;
	while (<IN>) {
		chomp;
# jxl event data
                ($id,$zloginid,$zeventkey,$zphonenum,$xdatestamp,$label,$description,$zjunk) = split(/\|/,$_,8);
		next unless ($id == $vars{id});
		($year,$month,$date) = ($xdatestamp =~ /(\d\d\d\d)(\d\d)(\d\d)/);
		$description =~ s|<BR>|\n|gis;
		$description =~ s|"|&quot;|gs;
		$label =~ s|"|&quot;|gs;
		last;
		}
	close(IN);
	print <<"END";
<HTML>
<HEAD><TITLE>Calendar Administration</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function verifyform(theform) {
	if (theform.month.value<1 || theform.month.value>12) {
		alert("Month is invalid");
		return false;
		}
	if (theform.date.value<1 || theform.date.value>31) {
		alert("Date is invalid");
		return false;
		}
	if (theform.year.value<0 || theform.year.value == "") {
		alert("Year is invalid");
		return false;
		}
	if (theform.heading.value == "") {
		alert("Heading is required");
		return false;
		}
	if (theform.description.value == "") { 
		alert("Description is required");
		return false;
		}
	return true;
	} // end of function
</SCRIPT>
<style>
<!--
$ADMIN_STYLES
-->
</style>
</HEAD>
<BODY BGCOLOR=white>
$ADMIN_PAGE_TOP
		<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=3>
			<form action="$vars{cgi}" method=post onSubmit="return verifyform(this);">
			<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
			<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
			<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
			<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
			<INPUT TYPE="HIDDEN" NAME="id" VALUE="$id">
			<input type="hidden" name="ACTION" value="SAVE_EDIT">
			<TR>
				<TD ALIGN=RIGHT><B>Edit&nbsp;Event</B></TD>
				<TD WIDTH=100%><HR SIZE=1></TD>
			</TR>			
			<TR>
				<TH BGCOLOR="#CCCCCC">Date</TH>
				<TD BGCOLOR="#CCCCCC">
					<input name="month" size=2 maxlength=2 value="$month"> / <input name="date" size=2 maxlength=2 value="$date"> / <input name="year" size=4 maxlength=4 value="$year">&nbsp;&nbsp;
					<input type="checkbox" name="annual" value="1" onClick="if(form.annual.checked == true){form.year.value='0000'}else{form.year.value=''}"> Every Year
				</TD>
			</TR>
			<TR>
				<TH BGCOLOR="#CCCCCC">Heading</TH>
				<TD BGCOLOR="#CCCCCC"><input name="heading" size=30 value="$label"></TD>
			</TR>
			<TR>
				<TH BGCOLOR="#CCCCCC">Description</TH>
				<TD BGCOLOR="#CCCCCC" COLSPAN=3><textarea name="description" cols=50 rows=3>$description</textarea></TD>
			</TR>
			<TR>
				<TD COLSPAN=2 ALIGN=RIGHT BGCOLOR="#CCCCCC"><input type="reset" CLASS="button" value="Clear">&nbsp;&nbsp;&nbsp;<input type="submit" CLASS="button" value="Save">
				</form>
				</TD>
			</TR>
			<TR>
				<TD COLSPAN=2><HR SIZE=1></TD>
			</TR>
		</TABLE>
$ADMIN_PAGE_BOTTOM
END
	exit(0);
	}

	
#####################################################################
#
# SAVE_EDIT()
#
# Save edits
#
#####################################################################
sub SAVE_EDIT {
	my %events;
	
	$in{description} =~ s|[\r\n]+|<BR>|gs;
	$in{month} =~ s|^(\d)$|0$1|;
	$in{date}  =~ s|^(\d)$|0$1|;
	my $datestamp = $in{year} . $in{month} . $in{date};

	open(IN,"$vars{calendar_file}") || &Error( "Can't open $vars{calendar_file}");
	my $header = <IN>;
	while (<IN>) {
		chomp;
# jxl event data
                ($id,$zloginid,$zeventkey,$zphonenum,$xdatestamp,$label,$description,$zjunk) = split(/\|/,$_,8);
		$events{$id}{loginid} = $zloginid;
		$events{$id}{eventkey} = $zeventkey;
		$events{$id}{phonenum} = $zphonenum;
		$events{$id}{datestamp} = $xdatestamp;
		$events{$id}{label} = $label;
		$events{$id}{description} = $description;
		}
	close(IN);

	$events{$in{id}}{loginid} = $in{loginid};
	$events{$in{id}}{eventkey} = $in{eventkey};
	$events{$in{id}}{phonenum} = $in{phonenum};
	$events{$in{id}}{datestamp} = $datestamp;
	$events{$in{id}}{label} = $in{heading};
	$events{$in{id}}{description} = $in{description};
	
	open(OUT,"> $vars{calendar_file}") || &Error( "Can't open $calendar_file for writing!");
	eval "flock OUT,2";
# jxl event data
	print OUT "#id|loginid|eventkey|phonenum|datestamp|label|description\n";
	foreach $id ( sort {$a <=> $b} keys %events ) {
# jxl event data
 		print OUT "$id|$events{$id}{loginid}|$events{$id}{eventkey}|$events{$id}{phonenum}|$events{$id}{datestamp}|$events{$id}{label}|$events{$id}{description}\n";
		}
	close(OUT);
	$vars{'message'} = "Changes Saved";
	undef %events;
	
	&read_cal_data;
	$vars{month} = $in{month}; $vars{month} =~ s|^0||;
	$vars{year} = $in{year};
	&EDIT;	
	exit(0);
	}

	
#####################################################################
#
# DELETE()
#
# Delete an entry
#
#####################################################################
sub DELETE {
	$in{id} = shift;
	my %events;
	open(IN,"$vars{calendar_file}") || &Error( "Can't open $vars{calendar_file}");
	my $header = <IN>;
	while (<IN>) {
		chomp;
# jxl event data
                ($id,$zloginid,$zeventkey,$zphonenum,$xdatestamp,$label,$description,$zjunk) = split(/\|/,$_,8);
		next if ($id == $in{id});
		$events{$id}{loginid} = $zloginid;
		$events{$id}{eventkey} = $zeventkey;
		$events{$id}{phonenum} = $zphonenum;
		$events{$id}{datestamp} = $xdatestamp;
		$events{$id}{label} = $label;
		$events{$id}{description} = $description;
		}
	close(IN);

	open(OUT,"> $vars{calendar_file}") || &Error( "Can't open $calendar_file for writing!");
	eval "flock OUT,2";
	print OUT "#id|loginid|eventkey|phonenum|datestamp|label|description\n";
	foreach $id ( sort {$a <=> $b} keys %events ) {
# jxl event data
 		print OUT "$id|$events{$id}{loginid}|$events{$id}{eventkey}|$events{$id}{phonenum}|$events{$id}{datestamp}|$events{$id}{label}|$events{$id}{description}\n";
		}
	close(OUT);
	$vars{'message'} = "Event Deleted";
	undef %events;
	
	&read_cal_data;
	&EDIT;	
	exit(0);
	}

	
#####################################################################
#
# Initialize variables
#
#####################################################################
sub INITIALIZE {
	my $x,$i,$neg_pos,$hours;

	# Current date and stuff

	$time = time;
	($neg_pos,$hours) = ($vars{time_offset} =~ /([+-])(\d+)/);
	if ($neg_pos eq '+') {
		$time += (60*60 * $hours);
		}
	else {
		$time -= (60*60 * $hours);
		}
	($mday,$month,$year) = (localtime($time))[3,4,5];
	$month = $month+1;
	$year = $year+1900;
	$datestamp = sprintf("%4.4d%2.2d%2.2d",$year,$month,$mday);
	
	}


#####################################################################
#
# Read in calendar data file
#
#####################################################################
sub read_cal_data {
	undef %events;
	my $id,$xdatestamp, $xmonth;
	$vars{new_id} = 0;
	open(IN,"$vars{calendar_file}") || &Error( "Can't open $vars{calendar_file}");
	my $header = <IN>;

	# If file isnt in right format, prompt to update it.
# jxl event data
	unless ($header =~ m/^#id\|loginid\|eventkey\|phonenum\|datestamp\|label\|description/) {
		close(IN);
		&UPDATE_FORMAT;
		}

	while (<IN>) {
		chomp;
		next unless /^\d/;
# jxl event data
#		($id,$xdatestamp,$label,$desc) = split(/\|/,$_,4);
                ($id,$zloginid,$zeventkey,$zphonenum,$xdatestamp,$label,$desc,$zjunk) = split(/\|/,$_,8);
		if ($id > $vars{new_id}) { $vars{new_id} = $id; }
				
		$total_events{$xdatestamp}++;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{description} = $desc;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{label} = $label;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{phonenum} = $zphonenum;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{eventkey} = $zeventkey;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{loginid} = $zloginid;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{id} = $id;
		
		}
	close(IN);
	$vars{new_id}++;
	}

	
#####################################################################
#
# Read in config file
#
#####################################################################
sub read_config {
	my $config_file;
	if ($in{config}) {
		$vars{config} = $in{config};
		unless ($vars{config} =~ m|^/|) {
			$config_file = $vars{base_dir} . $vars{config};
			}
		else {
			$config_file = $vars{config};
			}
		}
	else {
		$vars{config} = "calendar.cfg";
		$config_file = $vars{base_dir} . $vars{config};
		}
	my $key,$val;
	open(IN,$config_file) || &Error("Can't open config file $config_file.");
	while(<IN>) {
		next if /^#/;
		chomp;
		($key,$val) = ( /([^=]+)=(.*)/ );
		$key = lc($key);
		$val =~ s|\[(\S+)\]|$vars{$1}|g;
		$val =~ s|\s*$||;
		$vars{$key} = $val;
		}
	close(IN);

	@months = split(',',$vars{months});
	($vars{month1},$vars{month2},$vars{month3},$vars{month4},$vars{month5},$vars{month6},$vars{month7},$vars{month8},$vars{month9},$vars{month10},$vars{month11},$vars{month12} ) = @months;

	@shortmonths = split(',',$vars{shortmonths});
	($vars{shortmonth1},$vars{shortmonth2},$vars{shortmonth3},$vars{shortmonth4},$vars{shortmonth5},$vars{shortmonth6},$vars{shortmonth7},$vars{shortmonth8},$vars{shortmonth9},$vars{shortmonth10},$vars{shortmonth11},$vars{shortmonth12} ) = @shortmonths;

	@days = split(',',$vars{days});
	($vars{dayname1},$vars{dayname2},$vars{dayname3},$vars{dayname4},$vars{dayname5},$vars{dayname6},$vars{dayname7} ) = @days;

	}

	
	
#####################################################################
#
# Return an error screen
#
#####################################################################
sub Error {
	$message = shift;
	print <<"END";
<HTML>
<HEAD><TITLE>Error</TITLE>
</HEAD>
<BODY BGCOLOR=white>
<BR><BR>
<CENTER>
<TABLE BORDER=1 BORDERCOLOR="#333333" CELLSPACING=0 CELLPADDING=3 WIDTH=500>
<TR>
	<TD ALIGN=CENTER BGCOLOR="#000080"><FONT COLOR="white" SIZE="+1"><B>ERROR</B></FONT></TD>
</TR>
<TR>
	<TD BGCOLOR="#CCCCCC">
	<br><B>Error Message:</B><br>
	$message
	<br><br>
	<U>Debugging Info</U><br>
	File and Directory Locations:<br>
	<ul>
		<li>Base Directory (\$base_dir): $base_dir
		<li>Template Directory (\$template_dir): $template_dir
		<li>Calendar Events File (\$calendar_file): $calendar_file
		<li>Current Calendar Template (\$calendar_html): $calendar_html
		<li>Current View Day Template (\$viewday_html): $viewday_html
	</ul>
	<br>
	<U>File Permissions</U><br>
	Any potential problems caused by file permissions or locations will be listed here.
	<FONT COLOR="red">
	<ul>
END
	unless (-d $base_dir) { print "<li>The base directory does not exist\n"; }
	unless (-e $calendar_file) { print "<li>The calendar events file does not exist\n"; }
	unless (-w $calendar_file) { print "<li>The calendar events file is not world-writeable (chmod 777)\n"; }
	unless (-d $template_dir) { print "<li>The Template directory does not exist\n"; }
	unless (-e $calendar_html) { print "<li>The calendar template file does not exist\n"; }
	unless (-w $calendar_html) { print "<li>The calendar template file is not world-writeable (chmod 777)\n"; }
	unless (-e $viewday_html) { print "<li>The view day template file does not exist\n"; }
	unless (-w $viewday_html) { print "<li>The view day template file is not world-writeable (chmod 777)\n"; }
	
print <<"END";
	</ul>
	</FONT>

	<br><br>
	<CENTER>
	<B><A HREF="http://www.mattkruse.com/scripts/calendar/docs/">Online Documentation</A></B>
	</CENTER>

	</TD>
</TR>
</TABLE>
</BODY>
</HTML>
END
	exit(0);
	}


#####################################################################
#
# TEMPLATES()
#
# HTML Template Options
#
#####################################################################
sub TEMPLATES {
	opendir(DIR,$vars{template_dir});
	$calendar_template_options = "";
	$viewday_template_options = "";
	while ($file = readdir(DIR)) {
		$selected = "";
		if ($file =~ /^calendar.*\.html/) { 
			$title = $file;
			$title =~ m|^calendar_?(.*)\.html|i;
			$title = $1;
			$title =~ s|_| |g;
			$calendar_templates{$file}{title} = $title;
			$filename = $vars{template_dir} . "/" . $file;
			$calendar_templates{$file}{lastmod} = int(-M $filename);
			}
		if ($file =~ /^viewday.*\.html/) { 
			$title = $file;
			$title =~ m|^viewday_?(.*)\.html|i;
			$title = $1;
			$title =~ s|_| |g;
			$viewday_templates{$file}{title} = $title;
			$filename = $vars{template_dir} . "/" . $file;
			$viewday_templates{$file}{lastmod} = int(-M $filename);
			}
		}
	closedir(DIR);

	print <<"END";
<HTML>
<HEAD><TITLE>Calendar Administration</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function showmessage(msg) {
	if (msg != "") {
		alert(msg);
		}
	}
</SCRIPT>
<style>
<!--
$ADMIN_STYLES
-->
</style>
</HEAD>
<BODY BGCOLOR=white onLoad='showmessage("$vars{message}")'>
$ADMIN_PAGE_TOP
END

print "<TABLE BORDER=1 BORDERWIDTH=1 CELLSPACING=0 CELLPADDING=3 WIDTH=100%>\n";
print "<TR><TH COLSPAN=2>Main Calendar Templates</TH></TR>\n";
foreach $file (sort keys %calendar_templates) {
	print <<"END";
	<TR>
		<FORM ACTION="$vars{cgi}" METHOD=POST TARGET="_new">
		<TD ALIGN=CENTER VALIGN=MIDDLE>
			<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
			<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
			<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
			<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="EDIT_TEMPLATE">
			<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
			<INPUT TYPE="HIDDEN" NAME="file" VALUE="$file">
			<INPUT TYPE="Submit" VALUE=" Edit " CLASS="BUTTON">
		</TD>
		</FORM>
		<TD BGCOLOR=#EEEEEE>$calendar_templates{$file}{title}<br>
			<FONT SIZE="-1">(Last modified $calendar_templates{$file}{lastmod} days ago)</FONT>
		</TD>
	</TR>
END
	}
print "	</TABLE>\n";

print "<TABLE BORDER=1 BORDERWIDTH=1 CELLSPACING=0 CELLPADDING=3 WIDTH=100%>\n";
print "<TR><TH COLSPAN=2>View Day Templates</TH></TR>\n";
foreach $file (sort keys %viewday_templates) {
	print <<"END";
	<TR>
		<FORM ACTION="$vars{cgi}" METHOD=POST TARGET="_new">
		<TD ALIGN=CENTER VALIGN=MIDDLE>
			<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
			<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
			<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
			<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="EDIT_TEMPLATE">
			<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
			<INPUT TYPE="HIDDEN" NAME="file" VALUE="$file">
			<INPUT TYPE="Submit" VALUE=" Edit " CLASS="BUTTON">
		</TD>
		</FORM>
		<TD BGCOLOR=#EEEEEE>$viewday_templates{$file}{title}<br>
			<FONT SIZE="-1">(Last modified $viewday_templates{$file}{lastmod} days ago)</FONT>
		</TD>
	</TR>
END
	}
print "	</TABLE>\n";


print <<"END";
	<HR SIZE=1>
$ADMIN_PAGE_BOTTOM
END
	exit(0);
	} #end of TEMPLATES

	
#####################################################################
#
# EDIT_TEMPLATE()
#
# Actually edit an HTML template
#
#####################################################################
sub EDIT_TEMPLATE {
	$filename = $vars{template_dir} . "/" . $in{file};
	open(IN,$filename);
	undef $/;
	$contents = <IN>;
	$/="=n";
	close(IN);
	$contents =~ s|<|\&lt\;|gs;
	$contents =~ s|>|\&gt\;|gs;
	$contents =~ s|\r\n|\n|gs;
	
	print <<"END";
<HTML>
<HEAD><TITLE>Calendar Administration</TITLE>
<style>
<!--
$ADMIN_STYLES
-->
</style>
</HEAD>
<BODY BGCOLOR=white>
<CENTER>
<TABLE BORDER=1 BORDERCOLOR="#333333" CELLSPACING=0 CELLPADDING=3>
<TR>
	<TD ALIGN=CENTER BGCOLOR="#000080"><FONT COLOR="white" FACE="arial"><B>Calendar Administration</B></FONT></TD>
</TR>
<TR>
	<TD BGCOLOR=#CCCCCC>
	<B>Editing File:</B> $in{file}
	</TD>
</TR>
END

# Filename doesn't exist
unless (-e $filename) {
	print <<"END";
<TR>
	<TD BGCOLOR=#CCCCCC>
	<FONT COLOR=red SIZE=+1>ERROR:</FONT> This filename does not exist. Pleaes check the full path manually:<br><br>
	$filename
	</TD>
</TR>
END
	}
	
# Filename isn't writeable
unless (-w $filename) {
	print <<"END";
<TR>
	<TD BGCOLOR=#CCCCCC>
	<FONT COLOR=red SIZE=+1>ERROR:</FONT> Cannot write to this template file. Please check to make sure the file is world-writeable (chmod 777) to allow editing from the admin menu.<br><br>
	$filename
	</TD>
</TR>
END
	}

if (-e $filename) {
	print <<"END";
<TR>
	<TD ALIGN=CENTER BGCOLOR=#CCCCCC>
		<FORM ACTION="$vars{cgi}" METHOD=POST>
		<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
		<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
		<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
		<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="SAVE_TEMPLATE">
		<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
		<INPUT TYPE="HIDDEN" NAME="filename" VALUE="$filename">
		<TEXTAREA NAME="contents" COLS=80 ROWS=25 WRAP=off>$contents</TEXTAREA>
		<br><br>
		<INPUT TYPE="Submit" VALUE=" Save Changes " CLASS="BUTTON">
		<INPUT TYPE="button" VALUE=" Cancel " CLASS="BUTTON" onClick="window.close()">
		</FORM>
	</TD>
</TR>
END
	}

print <<"END";
</TABLE>
</BODY>
</HTML>
END
	exit(0);
	} #end of EDIT_TEMPLATE

	
#####################################################################
#
# SAVE_TEMPLATE()
#
# Save an HTML template
#
#####################################################################
sub SAVE_TEMPLATE {
	$filename = $in{filename};
	open(OUT,"> $filename") || &Error("Couldn't write to file $filename");
	$contents =~ s|\r\n|\n|gs;
#	$contents =~ s|<|\&lt\;|gs;
#	$contents =~ s|>|\&gt\;|gs;
	print OUT "$in{contents}";
	close(OUT);
	print <<"END";
<HTML>
<HEAD><TITLE>Calendar Administration</TITLE>
<style>
<!--
$ADMIN_STYLES
-->
</style>
</HEAD>
<BODY BGCOLOR=white>
<CENTER>
<TABLE BORDER=1 BORDERCOLOR="#333333" CELLSPACING=0 CELLPADDING=3>
<TR>
	<TD ALIGN=CENTER BGCOLOR="#000080"><FONT COLOR="white" FACE="arial"><B>Calendar Administration</B></FONT></TD>
</TR>
<TR>
	<TD BGCOLOR=#CCCCCC ALIGN="center">
	<B>Changes Saved</B>
	<BR><BR><BR>
	<FORM>
	<INPUT TYPE="button" VALUE="Close" CLASS="BUTTON" onClick="window.close()">
	</FORM>
	</TD>
</TR>
</TABLE>
</BODY>
</HTML>
END
	exit(0);
	} #end of SAVE_TEMPLATE

	
#####################################################################
#
# Parse input
#
#####################################################################
sub ReadParse {
 local (*in) = @_ if @_;  local ($i, $loc, $key, $val);
 if ($ENV{'REQUEST_METHOD'} eq "GET") { $in = $ENV{'QUERY_STRING'};} 
 elsif ($ENV{'REQUEST_METHOD'} eq "POST")
      {read(STDIN,$in,$ENV{'CONTENT_LENGTH'});}
 @in = split(/&/,$in);
 foreach $i (0 .. $#in) {
  $in[$i] =~ s/\+/ /g;    ($key, $val) = split(/=/,$in[$i],2);
  $key =~ s/%(..)/pack("c",hex($1))/ge;
  $val =~ s/%(..)/pack("c",hex($1))/ge;
  $val =~ s/^\s+//g;               # remove leading spaces
  $val =~ s/\s+$//g;               # remove trailing spaces
  $in{$key} .= "\0" if (defined($in{$key})); 
  $in{$key} .= $val;  
  }  
 return 1; 
 }


#####################################################################
#
# Calendar logic
#
#####################################################################
sub PerpetualCalendar {
	# This perpetual calendar routine provides accurate day/date
	# correspondences for dates from 1601 to 2899 A.D.  It is based on
	# the Gregorian calendar, so be aware that early correspondences
	# may not always be historically accurate.  The Gregorian calendar
	# was adopted by the Italian states, Portugal and Spain in 1582,
	# and by the Catholic German states in 1583.  However, it was not
	# adopted by the Protestant German states until 1699, by England
	# and its colonies until 1752, by Sweden until 1753, by Japan
	# until 1873, by China until 1912, by the Soviet Union until 1918,
	# and by Greece until 1923.
	($perp_mon,$perp_day,$perp_year) = @_;
	%day_counts =
	  (1,0,2,31,3,59,4,90,5,120,6,151,7,181,
	  8,212,9,243,10,273,11,304,12,334);
	$perp_days = (($perp_year-1601)*365)+(int(($perp_year-1601)/4));
	$perp_days += $day_counts{$perp_mon};
	$perp_days += $perp_day;
	$perp_sofar = $day_counts{$perp_mon};
	$perp_sofar += $perp_day;
	$perp_togo = 365-$perp_sofar;
	if (int(($perp_year-1600)/4) eq (($perp_year-1600)/4)) {
		$perp_togo++;
		if ($perp_mon > 2) {
			$perp_days++;
			$perp_sofar++;
			$perp_togo -= 1;
		}
	}
	foreach $key (1700,1800,1900,2100,2200,2300,2500,2600,2700) {
		if ((($perp_year == $key) && ($perp_mon > 2))
		  || ($perp_year > $key)) {
			$perp_days -= 1;
		}
	}
	$perp_dow = $perp_days - (int($perp_days/7)*7);
	if ($perp_dow == 7) { $perp_dow = 0; }
	if ($vars{monsunweek} eq "Yes") {
		$perp_dow -= 1;
		if ($perp_dow == -1) { $perp_dow = 6; }
	}
	$perp_eom = 31;
	if (($perp_mon == 4) || ($perp_mon == 6)
	  || ($perp_mon == 9) || ($perp_mon == 11)) {
		$perp_eom = 30;
	}
	if (($perp_mon == 2)) {
		$perp_eom = 28;
	}
	if ((int(($perp_year-1600)/4) eq (($perp_year-1600)/4))
	  && ($perp_mon == 2)) {
		$perp_eom = 29;
	}
	foreach $key (1700,1800,1900,2100,2200,2300,2500,2600,2700) {
		if ($perp_year == $key) {
			if ($perp_mon == 1) {
				$perp_togo -= 1;
			}
			elsif ($perp_mon == 2) {
				$perp_togo -= 1;
				$perp_eom = 28;
			}
			else {
				$perp_sofar -= 1;
			}
		}
	}
}


#####################################################################
# load_template
# 
# load_template( "filename" )
#
# load a file and return it
#
#####################################################################
sub load_template {
	my($filename) = shift;
	undef $/;
	open(IN,"$filename") || &Error("Couldn't open file $filename in load_template: $!\n");
	my($template) = <IN>;
	close(IN);
	$/="\n";
	return $template;
	}

#####################################################################
# parse_template
# 
# parse_template( $template_string , \%value_array )
#
# Replace <%=TAGS%> in template with values
#
#####################################################################
sub parse_template {
	my ($template) = shift;
	my ($data) = shift;

	# Bring in #include files
	$template =~ s|
					<!--\#include\s*file="([^"]+)"-->
                  |
				  	package temp;
					my $tmp;
					my $file = $1;
					if (!open(IN,$file)) {
						$tmp = "[ INCLUDE ERROR: Couldn't find file '$file' to include ]";
						}
					else {
						undef $/;
						$tmp = <IN>;
						$/ = "\n";
						close(IN);
						$tmp;
						}
                  |sgeix;

	# Replace <%TAG%> <%/TAG%>
	foreach (keys %$data) {
		if (defined ${$data}{$_}) {
			$template =~ s|<%$_%>(.+?)<%/$_%>|
							my($tmp2) = $1; 
							$tmp2 =~ s!<%=VALUE%>!${$data}{$_}!s;
							"$tmp2";
						 |esgx;
			}
		else {
			$template =~ s|<%$_%>(.*?)<%/$_%>||sg;
			}
		}

	# Replace <%=TAG%>
	foreach (keys %$data) {
		$template =~ s|<%=$_%>|${$data}{$_}|sg;
		}

	# Replace <%=ENCODE TAG%>
	foreach (keys %$data) {
		$temp = ${$data}{$_};
		$temp =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
		$template =~ s|<%=ENCODE $_%>|$temp|sg;
		}

	# Replace <% code %> with output from code
	$template =~ s|
					<%(.*?)%>
                  |
				  	package temp;
					my $tmp;
					my $code = $1;
					$code =~ s/\bprint\b/\$tmp .= /sg;
					eval($code);
					$tmp;
                  |sgex;


	# Pass back parsed template
	return $template;
	
	}

#####################################################################
# parse_output
# 
# parse_output( $tag , $template_string , \%value_array )
#
# Loop through values array and replace <%OUTPUT $tag%> </%OUTPUT%>
# 
#####################################################################
sub parse_output {
	my ($tag) = shift;
	my ($template) = shift;
	my ($data) = shift;

	# Parse the <%OUTPUT%> <%/OUTPUT%> tags for record format
	my ($format) = ($template =~ m|<%OUTPUT $tag%>(.+?)<%/OUTPUT%>|si);
	my($output) = "";
	my($key,$tmp,$tmp2);
	# Loop through data and create output data
	foreach $key ( sort keys %$data ) {
		$tmp = $format;
		foreach (keys %{$$data{$key}}) {
			if ($$data{$key}{$_} =~ /\S/) {
				$tmp =~ s|<%$_%>(.+?)<%/$_%>|
							$tmp2 = $1; 
							$tmp2 =~ s!<%=VALUE%>!$$data{$key}{$_}!s;
							"$tmp2";
						 |esgx;
				}
			else {
				$tmp =~ s|<%$_%>(.+?)<%/$_%>||sg;
				}
			}
		foreach (keys %{$$data{$key}}) {
			$tmp =~ s|<%=($_)%>|$$data{$key}{$1}|sg;
			}
		$output .= $tmp;
		}

	# Replace OUTPUT in template with generated output
	$template =~ s|<%OUTPUT $tag%>.+?<%/OUTPUT%>|$output|s;

	return $template;
	}

#####################################################################
# html_escape
# 
# html_escape ( $string )
#
# Escape a string for display in HTML forms, etc.
# 
#####################################################################
sub html_escape {
	my ($string) = shift;
	$string =~ s|"|&quot;|sg;
	$string =~ s|<|&lt;|sg;
	$string =~ s|>|&gt;|sg;
	
	return $string;
	}




&GetCwd;
&ReadParse;
&read_config;
$vars{"cgi"} = $ENV{'SCRIPT_NAME'};
&INITIALIZE;

#####################################################################
#
# Top of Admin Page
#
#####################################################################
$ADMIN_PAGE_TOP = <<"END";
<BR><BR>
<CENTER>
<TABLE BORDER=1 BORDERCOLOR="#333333" CELLSPACING=0 CELLPADDING=3 WIDTH=600>
<TR>
	<TD COLSPAN=2 ALIGN=CENTER BGCOLOR="#000080"><FONT COLOR="white" FACE="arial"><B>Calendar Administration</B></FONT></TD>
</TR>
<TR>
	<TD BGCOLOR="#CCCCCC" VALIGN=TOP ALIGN=CENTER WIDTH=150>
		<FONT SIZE="+1"><B><U>Menu Screens</U></B></FONT>
		<br>
		<FORM ACTION=$vars{cgi} METHOD=POST>
		<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
		<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
		<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
		<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="ADMIN">
		<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
		<INPUT TYPE="SUBMIT" STYLE="background-color:#eeeeee;font:arial;font-weight:bold;color:#000080;font-size:xx-small;width:130;" 
		       VALUE="General Options">
		</FORM>

		<FORM ACTION=$vars{cgi} METHOD=POST>
		<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
		<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
		<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
		<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="ADD">
		<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
		<INPUT TYPE="SUBMIT" STYLE="background-color:#eeeeee;font:arial;font-weight:bold;color:#000080;font-size:xx-small;width:130;" 
		       VALUE="Add Event">
		</FORM>

		<FORM ACTION=$vars{cgi} METHOD=POST>
		<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
		<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
		<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
		<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="EDIT">
		<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
		<INPUT TYPE="SUBMIT" STYLE="background-color:#eeeeee;font:arial;font-weight:bold;color:#000080;font-size:xx-small;width:130;" 
		       VALUE="Edit Events">
		</FORM>

		<FORM ACTION=$vars{cgi} METHOD=POST>
		<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
		<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
		<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
		<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="PASSWORD">
		<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
		<INPUT TYPE="SUBMIT" STYLE="background-color:#eeeeee;font:arial;font-weight:bold;color:#000080;font-size:xx-small;width:130;" 
		       VALUE="Change Password">
		</FORM>

		<FORM ACTION=$vars{cgi} METHOD=POST>
		<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
		<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
		<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
		<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="TEMPLATES">
		<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
		<INPUT TYPE="SUBMIT" STYLE="background-color:#eeeeee;font:arial;font-weight:bold;color:#000080;font-size:xx-small;width:130;" 
		       VALUE="Template Editor">
		</FORM>

		<FORM ACTION=$vars{calendarurl} METHOD=GET>
		<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
		<INPUT TYPE="SUBMIT" STYLE="background-color:#eeeeee;font:arial;font-weight:bold;color:#000080;font-size:xx-small;width:130;" 
		       VALUE="View Calendar">
		</FORM>		

		<FORM ACTION=$vars{cgi} METHOD=POST>
		<INPUT TYPE="SUBMIT" STYLE="background-color:#eeeeee;font:arial;font-weight:bold;color:#000080;font-size:xx-small;width:130;" 
		       VALUE="Admin Login">
		</FORM>

		<FORM ACTION=$vars{cgi} METHOD=POST>
		<INPUT TYPE="HIDDEN" NAME="OK" VALUE="OK">
		<INPUT TYPE="HIDDEN" NAME="username" VALUE="$in{username}">
		<INPUT TYPE="HIDDEN" NAME="password" VALUE="$in{password}">
		<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="SUPPORT">
		<INPUT TYPE="HIDDEN" NAME="config" VALUE="$in{config}">
		<INPUT TYPE="SUBMIT" STYLE="background-color:#eeeeee;font:arial;font-weight:bold;color:#000080;font-size:xx-small;width:130;" 
		       VALUE="Support/Feedback">
		</FORM>

		Calendar Program<br>
		&copy; Copyright 1999<br>
		Matt Kruse<br>
		
	</TD>
	<TD BGCOLOR="#CCCCCC" VALIGN=TOP>
END

#####################################################################
#
# Bottom of Admin Page
#
#####################################################################
$ADMIN_PAGE_BOTTOM = <<"END";
	</TD>
</TR>
</TABLE>
</BODY>
</HTML>
END

#####################################################################
#
# Style Sheet for Admin Pages
#
#####################################################################
$ADMIN_STYLES = <<"END";
 INPUT.button { background-color:#eeeeee;font:arial;font-weight:bold;color:#000080;font-size:xx-small; }
END
		


# Routine to get working directory
# --------------------------------
sub GetCwd {
	if ($base_dir) { $vars{base_dir} = $base_dir; }
	return if $vars{base_dir};
	my $path =  $ENV{'PATH_TRANSLATED'} || $ENV{'SCRIPT_FILENAME'};
	unless ($path) {
		&Error("Your server does not provide the PATH_TRANSLATED or SCRIPT_FILENAME environment variables.<br><br>Please see the installation documentation for how to set the \$base_dir variable manually.");
		exit(0);
		}
	$path =~ s|[^/\\]*$||;
	$vars{base_dir} = $path;
	}

# Generate general variables
# --------------------------
$vars{'month'} = $in{'Month'} || $month;
$vars{'year'} = $in{'Year'} || $year;
$vars{'date'} = $in{'Date'};
if (!$vars{date} && $vars{month}==$month && $vars{year}==$year) {
	$vars{date} = $mday;
	}
$vars{'type'} = $DefaultType; 
$vars{'monthname'} = @months[int($vars{'month'})-1];
$vars{'datestamp'} = sprintf("%4.4d%2.2d%2.2d",$vars{year},$vars{month},$vars{date});

$vars{lastyear}  = $vars{year};
$vars{nextyear}  = $vars{year};
$vars{lastmonth} = $vars{month}-1;
$vars{nextmonth} = $vars{month}+1;
if ($vars{lastmonth} < 1) { $vars{lastmonth}=12; $vars{lastyear}--; }
if ($vars{nextmonth} > 12){ $vars{nextmonth}=1;  $vars{nextyear}++; }
$vars{lastmonthname} = @months[int($vars{lastmonth})-1];
$vars{nextmonthname} = @months[int($vars{nextmonth})-1];

#####################################################################
#
# Decide what to do based on the ACTION parameter
#
#####################################################################
if ($in{"ACTION"} eq "EVENTDETAILS") {
	&EVENTDETAILS;
	}
unless ($in{"OK"} eq "OK") { 
	&SPLASH;
	}

# If encrypted password is blank, go to passwd change screen
if (($in{"ACTION"} eq "SAVE_PASSWORD") && ($vars{username} !~ /\w/)) {
	&SAVE_PASSWORD;
	}
unless ( ($vars{username} =~ /\w/) && ($vars{username} =~ /\w/) ) {
	$vars{message} = "You must create and save an administrator username and password before using the admin utility.<br><br>The username and password you just entered have been put as the defaults above.";
	&PASSWORD;
	exit(0);
	}
# Check the password
unless (  
		(crypt($in{"username"},$vars{username}) eq $vars{username}) 
		&& 
		(crypt($in{"password"},$vars{password}) eq $vars{password})  
		) {
	print "Username and/or password invalid";
	exit(0);
	}

if ($in{"ACTION"} eq "DO_UPDATE_FORMAT") {
	&DO_UPDATE_FORMAT;
	}

# Check file format before doing anything else
&read_cal_data;
	
if ($in{"ACTION"} eq "EDIT") {
	&EDIT;
	}
if ($in{"ACTION"} eq "DO_EDIT") {
	&DO_EDIT;
	}
if ($in{"ACTION"} eq "SAVE_EDIT") {
	&SAVE_EDIT;
	}
elsif ($in{"ACTION"} eq "ADD") {
	&ADD;
	}
elsif ($in{"ACTION"} eq "DO_ADD") {
	&DO_ADD;
	}
elsif ($in{"ACTION"} eq "OPTIONS") {
	&OPTIONS;
	}
elsif ($in{"ACTION"} eq "PASSWORD") {
	&PASSWORD;
	}
elsif ($in{"ACTION"} eq "SAVE_PASSWORD") {
	&SAVE_PASSWORD;
	}
elsif ($in{"ACTION"} eq "SUPPORT") {
	&SUPPORT;
	}
elsif ($in{"ACTION"} eq "TEMPLATES") {
	&TEMPLATES;
	}
elsif ($in{"ACTION"} eq "EDIT_TEMPLATE") {
	&EDIT_TEMPLATE;
	}
elsif ($in{"ACTION"} eq "SAVE_TEMPLATE") {
	&SAVE_TEMPLATE;
	}
else {
	&ADMIN;
	}
exit(0);

