#!/usr/bin/perl
use CGI::Carp qw(fatalsToBrowser);
#
# csCalendar - v3.1 - 101106
#
$basepath = './';
#####################################################################
#                                                                   #
#    Copyright © 1999-2001 CGISCRIPT.NET - All Rights Reserved     #
#                                                                   #
#####################################################################
#                                                                   #
#          THIS COPYRIGHT INFORMATION MUST REMAIN INTACT            #
#                AND MAY NOT BE MODIFIED IN ANY WAY                 #
#                                                                   #
#####################################################################
#
# When you downloaded this script you agreed to accept the terms 
# of this Agreement. This Agreement is a legal contract, which 
# specifies the terms of the license and warranty limitation between 
# you and CGISCRIPT.NET. You should carefully read the following 
# terms and conditions before installing or using this software.  
# Unless you have a different license agreement obtained from 
# CGISCRIPT.NET, installation or use of this software indicates 
# your acceptance of the license and warranty limitation terms
# contained in this Agreement. If you do not agree to the terms of this
# Agreement, promptly delete and destroy all copies of the Software.
#
# Versions of the Software 
# Only one copy of the registered version of CGISCRIPT.NET 
# may used on one web site.
# 
# License to Redistribute
# Distributing the software and/or documentation with other products
# (commercial or otherwise) or by other than electronic means without
# CGISCRIPT.NET's prior written permission is forbidden.
# All rights to the CGISCRIPT.NET software and documentation not expressly
# granted under this Agreement are reserved to CGISCRIPT.NET.
#
# Disclaimer of Warranty
# THIS SOFTWARE AND ACCOMPANYING DOCUMENTATION ARE PROVIDED "AS IS" AND
# WITHOUT WARRANTIES AS TO PERFORMANCE OF MERCHANTABILITY OR ANY OTHER
# WARRANTIES WHETHER EXPRESSED OR IMPLIED.   BECAUSE OF THE VARIOUS HARDWARE
# AND SOFTWARE ENVIRONMENTS INTO WHICH CGISCRIPT.NET MAY BE USED, NO WARRANTY 
# OF FITNESS FOR A PARTICULAR PURPOSE IS OFFERED.  THE USER MUST ASSUME THE
# ENTIRE RISK OF USING THIS PROGRAM.  ANY LIABILITY OF CGISCRIPT.NET WILL BE
# LIMITED EXCLUSIVELY TO PRODUCT REPLACEMENT OR REFUND OF PURCHASE PRICE.
# IN NO CASE SHALL CGISCRIPT.NET BE LIABLE FOR ANY INCIDENTAL, SPECIAL OR
# CONSEQUENTIAL DAMAGES OR LOSS, INCLUDING, WITHOUT LIMITATION, LOST PROFITS
# OR THE INABILITY TO USE EQUIPMENT OR ACCESS DATA, WHETHER SUCH DAMAGES ARE
# BASED UPON A BREACH OF EXPRESS OR IMPLIED WARRANTIES, BREACH OF CONTRACT,
# NEGLIGENCE, STRICT TORT, OR ANY OTHER LEGAL THEORY. THIS IS TRUE EVEN IF
# CGISCRIPT.NET IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN NO CASE WILL
# CGISCRIPT.NET' LIABILITY EXCEED THE AMOUNT OF THE LICENSE FEE ACTUALLY PAID
# BY LICENSEE TO CGISCRIPT.NET.
#
# Credits:
# Andy Angrick - Programmer - angrick@cgiscript.net
# Mike Barone - Design - mbarone@cgiscript.net
#
# For information about this script or other scripts see 
# http://www.cgiscript.net
#
# Thank you for trying out our script.
# If you have any suggestions or ideas for a new innovative script
# please direct them to suggest@cgiscript.net.  Thanks.
#
########################################################################
#                       Config Variables                               #
########################################################################
##set today's color
$todaycolor = 'aqua';
$eventcolor = 'silver';
$eventtodaycolor = 'orange';
$vdefault = 'month';
$timeoffset = -1;

@bad = ('badword1','badword2','badword3','badword3');
#word to replace the bad words with
$rw = '&^#$%';
$flock=1;
$in{'cinfo'} = '<center><font size=1 face=tahoma>Powered by: <a href="http://www.cgiscript.net" target=_blank>CGIScript.net</a></font></center';
@DoW = ('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
@MoY = ('January','February','March','April','May','June','July','August','September','October','November','December');
$scriptname = 'csCalendar.cgi';
########################################################################
#                       End Config Variables                           #
########################################################################

$isUser=0;

(! -e "$basepath/setup.cgi")?($nosetup=1):(require("$basepath/setup.cgi"));
require("$basepath/libs.cgi");

if($cgiurl =~ /\/mod\//){
	$module=1;
	&GetCookies;
	$in{'UserName'} = $cookie{'UserName'};
	}
else{
	$module=0;
	}

$| = 1;	
&main;

sub main{
use Time::Local;
&getdata;
print "Content-type: text/html\n";
#print "C: $ENV{'HTTP_COOKIE'}\n";

($in{'command'} eq 'savesetup')&&(print "\n")&&(($nosetup)?(&SaveSetup):(&PError("Error. Permission denied.")));
$in{'cgiurl'} = $cgiurl."/$scriptname";
$in{'imageurl'} = $imageurl;
$in{'calid'} =~ s/z/\\0/g;
my(@c) = split(/\\0/,$in{'calid'});
$in{'rcalid'} = $c[0];

if(($in{'command'} eq 'viewsmall')||($in{'command'} eq 'viewlarge')){
&GetCookies;

	if(!$cookie{$in{'rcalid'}.'-m'}){
	$in{'mymonth'} = $in{'mmon'};
	$in{'myyear'} = $in{'myear'};
	}
	else{	
	$in{'mymonth'} = $cookie{$in{'rcalid'}.'-m'};
	$in{'myyear'} = $cookie{$in{'rcalid'}.'-y'};
	$in{'mday'} = $cookie{$in{'rcalid'}.'-d'};
	$in{'viewby'} = $cookie{$in{'rcalid'}.'-v'};
	$in{'fcalid'} = $cookie{$in{'rcalid'}.'-f'};
	my $np = $cookie{$in{'rcalid'}.'-p'};
	if($np eq 'p'){
		$in{'mymonth'} = $in{'mymonth'}-1;
		if($in{'mymonth'} == 0){
			$in{'mymonth'} = '12';
			$in{'myyear'} += -1;
			}
	}
	if($np eq 'n'){
		$in{'mymonth'} = $in{'mymonth'}+1;
		if($in{'mymonth'} == 13){
			$in{'mymonth'} = '1';
			$in{'myyear'} += 1;
			}
	}
	#print "$in{'mymonth'} - $in{'myyear'}<br>";
	if($cookie{$in{'rcalid'}.'-de'} == 1){
		$in{'eventscall'} = "DisplayEvents$in{'rcalid'}();";
		}
	}
}

print "Set-Cookie: $in{'rcalid'}-m= ;path=/\n";
print "Set-Cookie: $in{'rcalid'}-y= ;path=/\n";
print "Set-Cookie: $in{'rcalid'}-v= ;path=/\n";
print "Set-Cookie: $in{'rcalid'}-d= ;path=/\n";
print "Set-Cookie: $in{'rcalid'}-p= ;path=/\n";
print "Set-Cookie: $in{'rcalid'}-f= ;path=/\n";
($in{'command'} eq "evcs")&&(&ExportVCS);
print "\n";

#print "C: $ENV{'HTTP_COOKIE'}\n";

($in{'command'} eq '')&&($nosetup)&&(&Setup);
($in{'command'} eq 'view')&&(&View);
($in{'command'} eq '')&&(!$in{'vt'})&&(&Login);
($in{'command'} eq 'login')&&(&Login);
($in{'command'} eq 'viewinit')&&(&ViewInit);
($in{'command'} eq 'viewsmall')&&(&ViewSmall);
($in{'command'} eq 'viewlarge')&&(&ViewLarge);
($in{'command'} eq 'showsubmit')&&(&ShowSubmit);
($in{'command'} eq 'submitforapproval')&&(&SubmitForApproval);
($in{'command'} eq "mc")&&(&MoreComments);
($in{'command'} eq "savecomment")&&(&SaveComment);
($in{'command'} eq "pc")&&(&PopCal);

($module)?(&GetLoginMod):(&GetLogin);
($in{'command'} eq "sac")&&(&ShowAddCategory);
($in{'command'} eq "sacal")&&(&ShowAddCalendar);
($in{'command'} eq "ac")&&(&AddCategory);
($in{'command'} eq "dc")&&(&DeleteCategory);
($in{'command'} eq 'manage')&&(&Manage);
($in{'command'} eq "modify")&&(&ShowModifyCal);
($in{'command'} eq 'delete')&&(&DeleteCal2);
($in{'command'} eq 'savecal')&&(&SaveCalendar);
($in{'command'} eq 'savesettings')&&(&SaveSettings);
($in{'command'} eq 'showpending')&&(&ShowPending);
($in{'command'} eq 'approve')&&(&Approve);
($in{'command'} eq "sc")&&(&ShowConfig);
($in{'command'} eq "saveoptions")&&(&SaveConfig);
($in{'command'} eq "showadde")&&(&ShowAddEvent);
($in{'command'} eq "adde")&&(&AddEvent);
($in{'command'} eq "sce")&&(&SaveEventChanges);
($in{'command'} eq "de")&&(&DeleteEvent);
($in{'command'} eq 'showedit')&&(&ShowEditEvent);
($in{'command'} eq 'slw')&&(&ShowLinksWizard);
($in{'command'} eq "cp")&&(&ChangePassword);
}

sub ChangePassword{
my($buff,$encpass);
($in{'musername'} lt '0')&&(&PError("Error. Please enter a username"));
($in{'mpassword'} lt '0')&&(&PError("Error. Please enter a password"));
($in{'mpassword'} ne $in{'mpassword2'})&&(&PError("Error. Please retype passwords"));
open(DB,"<$basepath/setup.cgi");
while(<DB>){
	$buff .= $_;
	}
close DB;

if($^O !~ /win/i){
    	$encpass = crypt($in{'mpassword'},'CS');
    	}
else{
	$encpass = $in{'mpassword'};
	}
    	
$buff =~ s/\$username\s*=\s*'.*'/\$username='$in{'musername'}'/;
$buff =~ s/\$password\s*=\s*'.*'/\$password='$encpass'/;

open(DB,">$basepath/setup.cgi");
print DB $buff;
close DB;

print <<"EOF";
<script language=javascript>
var rndURL = (1000*Math.random());
document.cookie="UserName=$in{'musername'}";
document.cookie="PassWord=$in{'mpassword'}";
alert("Username/Password changed");
window.location="$in{'cgiurl'}?command=manage&rnd="+rndURL;
</script>
EOF
exit;
}

sub SaveComment{

&GetConfig($in{'rcalid'});
if(!$in{'acomments'}){
	&PError("Error. Comments are not allowed on this calendar");
	exit;
	}

(!$in{'comment'})&&(&PError("Please enter a comment"));
(!$in{'name'})&&(&PError("Please enter a your name"));

foreach my $i (@bad){
	$in{'comments'} =~ s/$i/$rw/gi;
	$in{'name'} =~ s/$i/$rw/gi;
	}

my(@e) = localtime(time);
$e[4] = $e[4]+1;
$e[5] = $e[5]+1900;
my($date);
if($in{'DateFormat'} eq 'English'){
	$date = sprintf("%.2d%s%.2d%s%.4d %.2d:%.2d:%.2d",$e[4],$in{'Separator'},$e[3],$in{'Separator'},$e[5],$e[3],$e[2],$e[1]);
	}
else{
	$date = sprintf("%.2d%s%.2d%s%.4d %.2d:%.2d:%.2d",$e[3],$in{'Separator'},$e[4],$in{'Separator'},$e[5],$e[3],$e[2],$e[1]);
	}

if(-e "$datapath/$in{'id'}-comments.cgi"){
	$in{'comment'} =~ s/&#(\d+);/pack("c",$1)/ge;
	$in{'name'} =~ s/&#(\d+);/pack("c",$1)/ge;
	
	my($file) = &CheckSafe("$datapath/$in{'id'}-comments.cgi");
	open(CMT,"+<$file");
	($flock)&&(flock(CMT,2));
	my(@l);
	while(<CMT>){
		push(@l,$_);
		}
	seek(CMT,0,0);
	print CMT "$date-$in{'name'}: $in{'comment'}\n\n";
	foreach my $i (@l){
		print CMT $i;
		}
	truncate(CMT, tell(CMT));
	($flock)&&(flock(CMT,8));
	close CMT;
	}
	
if(! -e "$datapath/$in{'id'}-comments.cgi"){
	$in{'comment'} =~ s/&#(\d+);/pack("c",$1)/ge;
	$in{'name'} =~ s/&#(\d+);/pack("c",$1)/ge;
	my($file) = &CheckSafe("$datapath/$in{'id'}-comments.cgi");
	open(CMT,">$file");
	($flock)&&(flock(CMT,2));
	print CMT "$date-$in{'name'}: $in{'comment'}\n\n";
	($flock)&&(flock(CMT,8));
	close CMT;
	}

&Redirect($in{'cgiurl'} . "?command=view&id=$in{'id'}&calid=$in{'calid'}&m=$in{'m'}&y=$in{'y'}&d=$in{'d'}","Comment Added");
exit;
}

sub MoreComments{
$/="\n\n";
open(CMT,"<$datapath/$in{'id'}-comments.cgi")||print "$!: $$datapath/$in{'id'}-comments.cgi";
	($flock)&&(flock(CMT,2));
	my($c);
	while(<CMT>){
		$c++;
		$_ =~ s/([^\w\s\:\-])/'&#'.ord($1).';'/ge;
		$_ =~ s/^(.*?): /<b>$1: <\/b>/g;
		$_ =~ s/\r*\n/<br>\n/g;
		$in{'comments'} .= $_;
		}
	close CMT;
	undef $/;
	$in{'comments'} =~ s/\n\n/\n<hr>\n/g;
(!$in{'comments'})&&($in{'comments'} ='No comments');
&PageOut("$cgipath/t_comments.htm");
exit;
}

sub AddEvent{
	&CheckVars;
	&GetConfig($in{'calid'});

if(!$isUser){
	if(($in{'atype'} ne 'admin')&&($in{'puid'} ne $in{'UserName'})){
		&PError("Error. Permission denied");
		}
	}
else{
	if((!$uadd{$in{'calid'}})&&(!$uconf{'addthiscatall'})){
		&PError("Error. Permission denied");
		}
	}
		
	my($id) = &GetID;
	&GetOutVars(1,$id,$in{'calid'});
	my($file) = &CheckSafe("$datapath/$in{'calid'}.cgi");
	open(DB,">>$file");
	($flock)&&(flock(DB,2));
	print DB "$newentry\n";
	close DB;
	($flock)&&(flock(DB,8));
	print DB 
	&Redirect($in{'cgiurl'} . "?command=modify&cid=$in{'cid'}&calid=$in{'calid'}","Event Added");
	exit;
	}

sub SaveEventChanges{
&CheckVars;
&GetConfig($in{'calid'});

if(!$isUser){
	if(($in{'atype'} ne 'admin')&&($in{'puid'} ne $in{'UserName'})){
		&PError("Error. Permission denied");
		}
	}
else{
	if((!$umod{$in{'calid'}})&&(!$uconf{'modifythiscatall'})){
		&PError("Error. Permission denied");
		}
	}

&GetOutVars($in{'approve'},$in{'id'},$in{'calid'});

my $sfile = &CheckSafe("$datapath/$in{'calid'}.cgi");
open(DB,"+<$sfile");
while(<DB>){
  @f = split("\t",$_);
  ($f[0] ne $in{'id'})?(push(@l,$_)):(push(@l,"$newentry\n"));
  }
seek(DB,0,0);
foreach $i (@l){
  print DB $i;
  }
truncate(DB, tell(DB));

if($in{'acomments'}){
	$in{'comments'} =~ s/&#(\d+);/pack("c",$1)/ge;
	my($file) = &CheckSafe("$datapath/$in{'id'}-comments.cgi");
	open(CMT,">$file");
	print CMT $in{'comments'};
	close CMT;
	}

&Redirect($in{'cgiurl'} . "?command=modify&cid=$in{'cid'}&calid=$in{'calid'}","Event Changed");
}

sub DeleteEvent{

&GetConfig($in{'calid'});
if(!$isUser){
	if(($in{'atype'} ne 'admin')&&($in{'puid'} ne $in{'UserName'})){
		&PError("Error. Permission denied");
		}
	}
else{
	if((!$udel{$in{'calid'}})&&(!$uconf{'deletethiscatall'})){
		&PError("Error. Permission denied");
		}
}

my $sfile = &CheckSafe("$datapath/$in{'calid'}.cgi");
open(DB,"+<$sfile");
while(<DB>){
  @f = split("\t",$_);
  ($f[0] ne $in{'id'})&&(push(@l,$_));
  }
seek(DB,0,0);
foreach $i (@l){
  print DB $i;
  }
truncate(DB, tell(DB));

&Redirect($in{'cgiurl'} . "?command=modify&cid=$in{'cid'}&calid=$in{'calid'}","Event Removed");
}

sub PopCal{
	&GetConfig($in{'calid'});
	&ViewCalendarSub;
	&PageOut("$cgipath/t_popcal.htm");
	exit;
}

sub ShowAddEvent{
$in{'command'} = 'adde';
if(!$isUser){
	(!$in{'CalName'})&&(&PError("Error. Please enter a name for your calendar before adding events"));
	}
(!$in{'calid'})&&(&SaveNewCalendar);
&GetConfig($in{'calid'});

#get today
my(@t,$tm,$td,$ty);
(@t) = localtime(time);
$t[3] = sprintf("%.2d",$t[3]);
$t[4] = sprintf("%.2d",$t[4]+1);
$t[5] = sprintf("%.4d",$t[5]+1900);

$in{'df'} = 'MM-DD-YYYY';
$in{'sedate'} = $in{'srdate'} = $in{'sdate'} ="$t[4]-$t[3]-$t[5]";
	
foreach my $i (1..10){
	next if ($in{'c'.$i} lt '0');
	$in{'cfields'} .= qq|<tr>
                        <td align="right"><b><font size="2">$in{'c'.$i}:</font></b></td>
                        <td vAlign="top">
                        <input maxLength="512" size="35" name="cv$i"></td>
                      	</tr>|;
	}
$in{'approve1'} = 'selected';
$in{'etypesingle'} = 'checked';
$in{'cancelbutton'} = qq|<input type="reset" class="button" onMouseOver="className='buttonOver';" onMouseOut="className='button';" value="Cancel" onclick="if (confirm('Return to the Management Screen?\\n\\nAny changes that have not yet been saved will be lost.')) {self.location='$in{'cgiurl'}?command=modify&cid=$in{'cid'}&calid=$in{'calid'}';}; return false;">|;
&PageOut("$cgipath/t_add_event.htm");
exit;
}


sub SaveConfig{
($in{'cpp'} =~ /[^\d]/)&&(&PError("Error. Comments per page has to be a number"));
($in{'pd'} eq '1')&&($in{'pw'} =~ /[^\d]/)&&(&PError("Error. Popup width has to be a number"));
($in{'ph'} eq '1')&&($in{'ph'} =~ /[^\d]/)&&(&PError("Error. Popup height has to be a number"));
	if(!$in{'calid'}){
		&PError("Error. Please save the calendar before changing the configuration");
	}
	else{
		my(@p);
		my($file) = &CheckSafe("$datapath/calendars.cgi");
		open(DB,"+<$file");
		($flock)&&(flock(DB,2));
		while(<DB>){
		chomp;
		   	my(@f) = split("\t",$_);
		   	if($f[0] eq $in{'calid'}){
		   
				$f[5] = $in{'dateformat'};
				$f[6] = $in{'separator'};
				$f[7] = $in{'allowpub'};
				$f[8] = $in{'requireapproval'};
				$f[9] = $in{'emailnotify'};
				($in{'emailnotify'})&&(!$in{'approveremail'})&&(&PError("Please enter an email address to send the approvals to"));
				($in{'approveremail'})&&($in{'approveremail'} !~ /\S+\@\S+/)&&(&PError("Error. Invalid approval email address"));
				$in{'approveremail'} =~ s/&#(\d+);/pack("c",$1)/ge;
				$in{'approveremail'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
				$f[10] = $in{'approveremail'};
				$f[11] = $in{'allowreminders'};
				($in{'allowreminders'})&&(!$in{'senderemail'})&&(&PError("Please enter an email address for where the reminders are being sent from"));
				($in{'senderemail'})&&($in{'senderemail'} !~ /\S+\@\S+/)&&(&PError("Error. Invalid sender email address"));
				$in{'senderemail'} =~ s/&#(\d+);/pack("c",$1)/ge;
				$in{'senderemail'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
				
				$f[12] = $in{'senderemail'};
				$f[13] = $in{'acomments'};
				$f[14] = $in{'cpp'};
		
		   		$f[14] = $in{'cpp'};
		   		$f[15] = $in{'sdefault'};
		   		
				for my $c (1..10){
					$in{'c'.$c} =~ s/&#(\d+);/pack("c",$1)/ge;
					$in{'c'.$c} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
					$f[15+$c] = $in{'c'.$c}
					}
				$f[26] = $in{'wstart'};
				
				$f[27] = $in{'pd'};
				$f[28] = $in{'pw'};
		   		$f[29] = $in{'ph'};
		   		
		   		$f[30] = $in{'cs1'};
		   		$f[31] = $in{'cs2'};
		   		$f[32] = $in{'cs3'};
		   		$f[33] = $in{'cs4'};
		   		$f[34] = $in{'cs5'};
		   		$f[35] = $in{'cs6'};
		   		$f[36] = $in{'cs7'};
		   		$f[37] = $in{'cs8'};
		   		$f[38] = $in{'cs9'};
		   		$f[39] = $in{'cs10'};
		   		$f[40] = $in{'showexport'};
		   		my($nv) = join("\t",@f);
		   		push(@p,$nv);
		   		}
		   	else{
		   		push(@p,$_);
		   		}
		  	}
		seek(DB,0,0);
		foreach my $i (@p){
		   	print DB "$i\n";
		   	}
		truncate(DB, tell(DB));
		($flock)&&(flock(DB,8));
		close DB;
	}
	&Redirect($in{'cgiurl'} . "?command=manage&cid=$in{'cid'}","Configuration Updated");
	exit;
	}
	
sub GetConfig{
my($id) = @_;
my($file) = &CheckSafe("$datapath/calendars.cgi");
open(DB,"<$file");
while(<DB>){
	chomp;
	my(@f) = split("\t",$_);
	if ($id == $f[0]){
	$in{'puid'} = $f[1];
			$in{'CalName'} = $f[3];
			$in{'CalName'} =~ s/&#(\d+);/pack("c",$1)/ge;
			$in{'CalName'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
			$in{'CalDesc'} = $f[4];
			$in{'CalDesc'} =~ s/&#(\d+);/pack("c",$1)/ge;
			$in{'CalDesc'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
			$in{'dateformat'.$f[5]} = 'checked';
			$in{'DateFormat'} = $f[5];
			$in{'separator'.$f[6]} = 'checked';
			($f[6] eq 'Slash')&&($in{'Separator'} = '/');
			($f[6] eq 'Hyphen')&&($in{'Separator'} = '-');
			($f[6] eq 'Period')&&($in{'Separator'} = '.');
			$in{'allowpub'} = $f[7];
			$in{'requireapproval'} = $f[8];
			$in{'emailnotify'} = $f[9];
			$in{'approveremail'} = $f[10];
			$in{'approveremail'} =~ s/&#(\d+);/pack("c",$1)/ge;
			$in{'approveremail'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
			$in{'allowreminders'} = $f[11];
			$in{'senderemail'} = $f[12];
			$in{'senderemail'} =~ s/&#(\d+);/pack("c",$1)/ge;
			$in{'senderemail'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
			$in{'acomments'} = $f[13];
			$in{'cpp'} = $f[14];
			$in{'sdefault'} = $f[15];
			$in{'wstart'} = $f[26];
			$in{'wstart'.$f[26]} = 'selected';
			
			$in{'pd'} = $f[27];
			$in{'pd'.$f[27]} = 'checked';
			$in{'pw'} = $f[28];
			$in{'ph'} = $f[29];
					   		
			$in{'cs1'} = $f[30];
			$in{'cs2'} = $f[31];
			$in{'cs3'} = $f[32];
			$in{'cs4'} = $f[33];
			$in{'cs5'} = $f[34];
			$in{'cs6'} = $f[35];
			$in{'cs7'} = $f[36];
			$in{'cs8'} = $f[37];
			$in{'cs9'} = $f[38];
		   	$in{'cs10'} = $f[39];
		   	$in{'showexport'} = $f[40];	
			for my $c (1..10){
				$in{'c'.$c} = $f[15+$c];
				$in{'c'.$c} =~ s/&#(\d+);/pack("c",$1)/ge;
				$in{'c'.$c} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
				}
						
			}
		}
close DB;

$in{'mdescription'} = '';
if($in{'calid'} =~ /\\0/){
	my($sel);
	my(@mcid) = split(/\\0/,$in{'calid'});
		foreach my $i (@mcid){
		open(DB,"<$datapath/calendars.cgi");
		while(<DB>){
		my(@c) = split("\t",$_);
		if($c[0] == $i){
			($in{'fcalid'} == $i)?($sel='selected'):($sel='');
			$in{'mdescription'} .= qq|<option value="$i" $sel>$c[4]</option>\n| unless (!$c[4]);
			}
		}
		close DB;
		}
	
	$in{'mdescription'} = qq|<hr size=1><select onChange="ChangeCal$in{'rcalid'}(this.options[this.selectedIndex].value);" class="calendarForm" name=fcalid size=1><option value="">-= All Calendars =-</option>\n$in{'mdescription'}</select>|;
	}
}

sub ShowConfig{
	if(!$in{'calid'}){
		&PError("Error. Please save the calendar before changing the configuration");
	}
	$in{'categoryname'} = &GetCatName($in{'cid'});
	&GetConfig($in{'calid'});
	&PageOut("$cgipath/t_config.htm");
	exit;
}


sub ShowModifyCal{

if($isUser==1){
		$in{'command'} = 'modify';
		&DoUserManage;
		exit;
		}
$in{'categoryname'} = &GetCatName($in{'cid'});
&GetConfig($in{'calid'});
my($file) = &CheckSafe("$datapath/calendars.cgi");
open(DB,"<$file");
while(<DB>){
	my($id,$uid,$cid,$calName,$calDesc,@rest) = split("\t",$_);
	($module)&&($in{'atype'} ne 'admin')&&($uid ne $in{'UserName'})&&(next);
	if ($id == $in{'calid'}){
		$in{'CalName'} = $calName;
		$in{'CalDesc'} = $calDesc;
		$in{'CalDesc'} =~ s/&#(\d+);/pack("c",$1)/ge;$in{'CalDesc'} =~ s/\\n/\n/g;
		$in{'calid'} = $id;
		}
	}
close DB;

&ManageView($in{'calid'});

&PageOut("$cgipath/t_add_edit_calendar.htm");
exit;
}

sub GetCatName{
	my($cid) =@_;
	my($id,$uid,$name,@rest,$name);
	my($file) = &CheckSafe("$datapath/categories.cgi");
	open(DB,"<$file");
	while(<DB>){
		chomp;
		($id,$uid,$name,@rest) = split("\t",$_);
		last if ($id == $cid);
		}
	close DB;
	return $name;
	}
	
sub ShowAddCalendar{
	if($isUser==1){
		&DoUserManage;
		}
(!$in{'cid'})&&(&PError("Error. Please create a category first."));
$in{'categoryname'} = &GetCatName($in{'cid'});
&ManageView;
$in{'command'} = 'savcal';
&PageOut("$cgipath/t_add_edit_calendar.htm");
exit;
}

sub ShowLinksWizard{
my($catId) = $in{'cid'};
my($selected,%calendars);
my($file) = &CheckSafe("$datapath/categories.cgi");
my(%calcat,%selcat,@qs,$hasid);

if(($in{'ff'})&&(!$in{'calid'})){
	&PError("Please select at least one calendar");
	}

open(DB,"<$file");
while(<DB>){
	chomp;
	my($id,$uid,$catname) = split("\t",$_);
	($module)&&($in{'atype'} ne 'admin')&&($uid ne $in{'UserName'})&&(next);
	$calcat{$id} = $catname;	
	}
close DB;

my(@cids) = split(/\\0/,$in{'calid'});
foreach my $i (@cids){
$selcat{$i} = 1;
push(@qs,"calid=$i");
$hasid=1;
}

my $query = join("\&",@qs);

my($file) = &CheckSafe("$datapath/calendars.cgi");
open(DB,"<$file");
	while(<DB>){
	chomp;
	my($id,$uid,$cid,$calName,@rest) = split("\t",$_);
	next if (!$calName);
	(!$in{'calid'})&&($in{'calid'} = $id);
	($module)&&($in{'atype'} ne 'admin')&&($uid ne $in{'UserName'})&&(next);
	if ($selcat{$id}) {
			$selected = 'selected';
			}
		else{
			$selected = '';
		}
	$calendars{$calcat{$cid}.'-'.$calName.'-'.$id} = qq~
	<option value="$id" $selected>$calcat{$cid} - $calName</option>
	~;
	}
	close DB;
	
	foreach my $i (sort keys %calendars){
		$in{'calendars'} .= $calendars{$i};
		}
	
	(!$in{'calendars'})&&($in{'calendars'} = qq|<option value="">No calendars in this category</option>|);
	

if($in{'filter'}){
	$in{'filter'} =~ s/([^\w])/'%'.sprintf("%.2x",ord($1))/ge;
	$filter = "\&filter=$in{'filter'}";
	}

if($hasid){
	$in{'smalljs'} = qq|<script language=javascript src="$in{'cgiurl'}?command=viewsmall&o=j&$query$filter"></script>|;
	$in{'largejs'} = qq|<script language=javascript src="$in{'cgiurl'}?command=viewlarge&o=j&$query$filter"></script>|;
	$in{'initjs'} = qq|<script language=javascript src="$in{'cgiurl'}?command=viewinit&o=j&$query$filter"></script>|;
	($myurl) = $in{'cgiurl'} =~ /http:\/\/.*?(\/.*)/i;
	$in{'small'} = qq|<!--#include virtual="$myurl?command=viewsmall&$query$filter" -->|;
	$in{'large'} = qq|<!--#include virtual="$myurl?command=viewlarge&$query$filter" -->|;
	$in{'init'} = qq|<!--#include virtual="$myurl?command=viewinit&$query$filter" -->|;
	$in{'eventonly'} = qq|<script language=javascript src="$in{'cgiurl'}?command=viewsmall&o=j&$query$filter&e=$in{'e'}&n=$in{'n'}&l=$in{'l'}"></script>|;
	$in{'e'.$in{'e'}} = 'checked';
	}

if($in{'smalljs'}){
	$in{'preview1'} = qq|<input type=button value="Preview" onClick="window.open('$in{'cgiurl'}?command=viewsmall&o=&$query$filter');">|;
	$in{'preview5'} = $in{'preview1'};
	}
	
if($in{'largejs'}){
	$in{'preview2'} = qq|<input type=button value="Preview" onClick="window.open('$in{'cgiurl'}?command=viewlarge&o=&$query$filter');">|;
	$in{'preview6'} = $in{'preview2'};
	}
	
if($in{'initjs'}){
	$in{'preview3'} = qq|<input type=button value="Preview" onClick="window.open('$in{'cgiurl'}?command=viewinit&o=&$query$filter');">|;
	$in{'preview7'} = $in{'preview3'};
	}
	
if($in{'e'}){
	$in{'preview4'} = qq|<input type=button value="Preview" onClick="window.open('$in{'cgiurl'}?command=viewsmall&$query$filter&e=$in{'e'}&n=$in{'n'}&l=$in{'l'}');">|;
	}
else{
	$in{'eventonly'}='';
	}


if($module){
	$in{'tcalid'} = $in{'calid'};
	$in{'tcalid'} =~ s/\\0/z/g;
	my(@mids) = split(/\\0/,$in{'calid'});
	foreach my $i (@mids){
		$in{'xcalid'} .= "&calid=$i";
		}
	&PageOut("$cgipath/t_show_links_mod.htm");
	}
else{
	&PageOut("$cgipath/t_show_links.htm");
	}
exit;
}

sub ViewInit{

if(!$in{'mday'}){
  &ctime(time);
  $in{'mday'} = $in{'myday'};
  }
&GetConfig($in{'rcalid'});
&ViewCalendarSub;
$in{'calid'} = $in{'rcalid'};
if($in{'CalDesc'}){
	if(!$in{'mdescription'}){
		$in{'description'} = "<br>$in{'CalDesc'}";
		}
	else{
		$in{'description'} = $in{'mdescription'};
		}
	}
($in{'o'} eq 'j')?(&PageOutJS("$cgipath/t_view_init.htm")):(&PageOut("$cgipath/t_view_init.htm"));
exit;
}

sub SubmitForApproval{

&GetConfig($in{'rcalid'});
&CheckVars;

$id = &GetID;
my($havetoapprove);
($in{'requireapproval'})?($havetoapprove=0):($havetoapprove=1);

&GetOutVars($havetoapprove,$id,$in{'calid'});

if($in{'emailnotify'}){
	&SendEmailNotify;
	}
	
my $sfile = &CheckSafe("$datapath/$in{'calid'}.cgi");
open(DB,">>$sfile");
($flock)&&(flock(DB,2));
print DB "$newentry\n";
close DB;
($flock)&&(flock(DB,8));

print <<"EOF";
<script language=javascript>
var rndURL = (1000*Math.random());
alert("Event successfully submitted.");
window.opener.location.reload();
window.close();
</script>
EOF
exit;
}

sub SendEmailNotify{

($in{'c1'})&&($in{'cf'} .= "$in{'c1'}: $in{'cv1'}\r\n");
($in{'c2'})&&($in{'cf'} .= "$in{'c2'}: $in{'cv2'}\r\n");
($in{'c3'})&&($in{'cf'} .= "$in{'c3'}: $in{'cv3'}\r\n");
($in{'c4'})&&($in{'cf'} .= "$in{'c4'}: $in{'cv4'}\r\n");
($in{'c5'})&&($in{'cf'} .= "$in{'c5'}: $in{'cv5'}\r\n");
($in{'c6'})&&($in{'cf'} .= "$in{'c6'}: $in{'cv6'}\r\n");
($in{'c7'})&&($in{'cf'} .= "$in{'c7'}: $in{'cv7'}\r\n");
($in{'c8'})&&($in{'cf'} .= "$in{'c8'}: $in{'cv8'}\r\n");
($in{'c9'})&&($in{'cf'} .= "$in{'c9'}: $in{'cv9'}\r\n");
($in{'c10'})&&($in{'cf'} .= "$in{'c10'}: $in{'cv10'}\r\n");

my(@f) = split("\t",$newentry);

if($f[22] eq 'single'){
		$when = "$f[23]";
		if($f[15] eq 'checked'){
			if($f[19]){
				$when .= " from $f[16]:$f[17] $f[18] to $f[19]:$f[20] $f[21]";
				}
			else{
				$when .= " at $f[16]:$f[17] $f[18]";			
				}
			}
		}
	elsif($f[22] eq "multiple"){
		$when = "$f[24] to $f[25]";
		if($f[15] eq 'checked'){
			if($f[19]){
				$when .= " from $f[16]:$f[17] $f[18] to $f[19]:$f[20] $f[21]";
				}
			else{
				$when .= " at $f[16]:$f[17] $f[18]";			
				}
			}
		}
	else{
		$when = "starting on $f[26]";
		if($f[28] == 2){
			$when .= " ending after $f[29] occurences";
			}
		if($f[28] == 3){
			$when .= " ending on $f[27]";
			}
		
		
	
	
	if($f[30] == 1){
			 $when .= " repeating every $f[31] day(s)";
			}
			
	if($f[30] == 2){
		undef(@d);
		($f[33])&&(push(@d,"Sunday"));
		($f[34])&&(push(@d,"Monday"));
		($f[35])&&(push(@d,"Tuesday"));
		($f[36])&&(push(@d,"Wednesday"));
		($f[37])&&(push(@d,"Thursday"));
		($f[38])&&(push(@d,"Friday"));
		($f[39])&&(push(@d,"Saturday"));
		$dw = join(", ",@d);
			$when .= " repeating every $f[32] week(s) on $dw";
		}
		
	if($f[30] == 3){
		if($f[40] == 1){
			$when = " repeating day $f[41] of every $f[42] month(s)";
			}
		else{
			$when = " repeating the $f[43] $f[44] of every $f[45] month(s)";
			}
	}
	
	if($f[30] == 4){
		if($f[46] == 1){
			$when = " repeating every $f[47] $f[48]";
			}
		else{
			$when = " repeating the $f[49] $f[50] of $f[51]";
			}
	}
	
	}

my($mess);
if($in{'requireapproval'}){
	$mess = 'The follow event has been submitted for your approval';
}
else{
	$mess = 'The follow event has been submitted';
}

(!$in{'email'})&&($in{'approveremail'});
$in{'approveremail'}=~ s/&#(\d+);/pack("c",$1)/ge;
$in{'title'} =~ s/&#(\d+);/pack("c",$1)/ge;
$in{'body'} =~ s/&#(\d+);/pack("c",$1)/ge;
$in{'cf'} =~ s/&#(\d+);/pack("c",$1)/ge;

$message = qq|
$mess

Calendar
----------------
$in{'CalName'}


Event Date
----------------
$when

Event Name: $in{'title'}
$in{'cf'}


Event Description
-----------------
$in{'body'}


$in{'cgiurl'}?command=modify&calid=$in{'calid'}
|;

if($sendmail){
my $sfile = &CheckSafe("$sendmail");
open(MAIL,"|$sfile -t");
print MAIL<<"EOF";
To: $in{'approveremail'}
From: $in{'email'}
Subject: Calendar Submission

$message

EOF
close MAIL;
}

if($mailserver){
  require("$basepath/sendmail.cgi");
  &SendMail($in{'approveremail'},$in{'email'},"Calendar Submission",$message,$mailserver);
  }

}

sub ShowSubmit{

&GetConfig($in{'rcalid'});

if($in{'requireapproval'}){
	$in{'em'} = qq|<tr>
                        <td align="right"><b><font size="2">Your Email:</font></b></td>
                        <td vAlign="top">
                        <input maxLength="512" size="35" name="email" value=""></td>
                      </tr>|;
	}
$in{'command'} = 'submitforapproval';

foreach my $i (1..10){
	next if ($in{'c'.$i} lt '0');
	$in{'cfields'} .= qq|<tr>
                        <td align="right"><b><font size="2">$in{'c'.$i}:</font></b></td>
                        <td vAlign="top">
                        <input maxLength="512" size="35" name="cv$i"></td>
                      	</tr>|;
	}

$in{'etypesingle'} = 'checked';
$in{'cancelbutton'} = qq|<input type="reset" class="button" onMouseOver="className='buttonOver';" onMouseOut="className='button';" value="Cancel" onclick="if (confirm('Are you sure you want to cancel?\\n\\nAny changes that have not yet been saved will be lost.')) {window.close();} return false;">|;
&PageOut("$cgipath/t_add_event.htm");
exit;
}

sub ViewSmall{

&GetConfig($in{'rcalid'});
($in{'e'} == 1)&&($in{'viewby'} = 'all');
($in{'n'} > 0)&&($in{'viewby'} = 'all');

&ViewCalendarSub;

$in{'calid'} = $in{'rcalid'};
(!$in{'fcalid'})&&($in{'fcalid'}=$in{'calid'});

if($in{'allowpub'}){
$in{'submitentry'} = qq|<input type=button value="Submit Entry" onClick="SubmitEntry$in{'calid'}();" class="calendarform">|;
}


if($in{'CalDesc'}){
		if(!$in{'mdescription'}){
			$in{'description'} = "<br>$in{'CalDesc'}";
			}
		else{
			$in{'description'} = $in{'mdescription'};
		}
	}



if($in{'e'} eq '1'){
	($in{'o'} eq 'j')?(&PageOutJS("$cgipath/t_events.htm")):(&PageOut("$cgipath/t_events.htm"));
	}
elsif($in{'n'} > 0){
	($in{'o'} eq 'j')?(&PageOutJS("$cgipath/t_events.htm")):(&PageOut("$cgipath/t_events.htm"));
	}
else{
	($in{'o'} eq 'j')?(&PageOutJS("$cgipath/t_view_small.htm")):(&PageOut("$cgipath/t_view_small.htm"));
	}
exit;
}

sub ViewLarge{

&GetConfig($in{'rcalid'});
&ViewCalendarSub;
if($in{'allowpub'}){
$in{'submitentry'} = qq|<input type=button value="Submit Entry" onClick="SubmitEntry$in{'calid'}();" class="calendarform">|;
}
$in{'ydate'} = $MoY[$in{'mymonth'}-1] . ' ' . $in{'myyear'};
if($in{'CalDesc'}){
		if(!$in{'mdescription'}){
			$in{'description'} = "<br>$in{'CalDesc'}";
			}
		else{
			$in{'description'} = $in{'mdescription'};
		}
	}
	
$in{'calid'} = $in{'rcalid'};
(!$in{'fcalid'})&&($in{'fcalid'}=$in{'calid'});
($in{'o'} eq 'j')?(&PageOutJS("$cgipath/t_view_large.htm")):(&PageOut("$cgipath/t_view_large.htm"));
exit;
}

sub ExportVCS{
#print "Content-type: text/html\n\n";
my $vcs='';
if($in{'id'} =~ /\-/){
	($in{'id'},$in{'calid'}) = split("-",$in{'id'});
	}

&GetConfig($in{'rcalid'});
my $sfile = &CheckSafe("$datapath/$in{'calid'}.cgi");
open(DB,"$sfile");
while(<DB>){
chomp;
@f = split("\t",$_);
if($f[0] eq $in{'id'}){
  $in{'id'} = $f[0];
  $in{'calid'} = $f[1];
  $in{'cid'} = $f[2];	
  $in{'title'} = $f[3];
  $in{'cv1'} = $f[4];
  $in{'cv2'} = $f[5];
  $in{'cv3'} = $f[6];
  $in{'cv4'} = $f[7];
  $in{'cv5'} = $f[8];
  $in{'cv6'} = $f[9];
  $in{'cv7'} = $f[10];
  $in{'cv8'} = $f[11];
  $in{'cv9'} = $f[12];
  $in{'cv10'} = $f[13];
  $in{'body'} = $f[14];
  $in{'body'} =~ s/&#(\d+);/pack("c",$1)/ge;
  $in{'body'} =~ s/\\n/=0D=0A/g;
  $in{'showtimes'} = $f[15];
  $in{'sthour'.$f[16]} = 'selected';
  $in{'stmin'.$f[17]} = 'selected';
  $in{'stsuf'.$f[18]} = 'selected';
  $in{'ethour'.$f[19]} = 'selected';
  $in{'etmin'.$f[20]} = 'selected';
  $in{'etsuf'.$f[21]} = 'selected';
  $in{'etype'.$f[22]} = 'checked';
  $in{'sedate'} = $f[23];
  $in{'sdate'} = $f[24];
  $in{'edate'} = $f[25];
  $in{'srdate'} = $f[26];
  $in{'erdate'} = $f[27];
  $in{'ed'.$f[28]} = 'checked';
  $in{'oc'} = $f[29];
  $in{'pattern'.$f[30]} = 'checked';
  $in{'pdaily'} = $f[31];
  $in{'pweekly'} = $f[32];
  $in{'wd0'} = $f[33];
  $in{'wd1'} = $f[34];
  $in{'wd2'} = $f[35];
  $in{'wd3'} = $f[36];
  $in{'wd4'} = $f[37];
  $in{'wd5'} = $f[38];
  $in{'wd6'} = $f[39];
  $in{'monthlytype'.$f[40]} = 'checked';
  $in{'m1'} = $f[41];
  $in{'m2'} = $f[42];
  $in{'m3'.$f[43]} = 'selected';
  $in{'m4'.$f[44]} = 'selected';
  $in{'m5'} = $f[45];
  $in{'yearlytype'.$f[46]} = 'checked';
  $in{'y1'.$f[47]} = 'selected';
  $in{'y2'} = $f[48];
  $in{'y3'.$f[49]} = 'selected';
  $in{'y4'.$f[50]} = 'selected';
  $in{'y5'.$f[51]} = 'selected';
  $in{'approve'} = $f[52];
  last;
  }
}
close DB;

foreach my $i (1..10){
	next if ($in{'c'.$i} lt '0');
	$in{'cfields'} .= qq|$in{'c'.$i}: $in{'cv'.$i}\n|;
	}

$f[17] = sprintf("%.2d",$f[17]);
$f[20] = sprintf("%.2d",$f[20]);


my $startdate;
my $enddate;

my $DTSTART;
my $DTEND;
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst);

if($f[15] eq 'checked'){
(!$f[16])&&($f[16]='12');
(!$f[17])&&($f[17]='00');
(!$f[19])&&($f[19]='12');
(!$f[20])&&($f[20]='00');

		if(($f[18] eq 'PM')&&($f[16] != 12)){
			$f[16] += 12;
			}
		if(($f[21] eq 'PM')&&($f[19] != 12)){
			$f[19] += 12;
			}
		if(($f[18] eq 'AM')&&($f[16] == 12)){
			$f[16] = '00';
			}
		if(($f[21] eq 'AM')&&($f[19] == 12)){
			$f[19] = '00';
			}			
	$startdate = timelocal(0,$f[17],$f[16],$in{'d'},$in{'m'}-1,$in{'y'});
	
	if(($f[20] eq '00')&&($f[19] eq '00')){
		$enddate = $startdate + 900;
		}
	else{
		$enddate = timelocal(0,$f[20],$f[19],$in{'d'},$in{'m'}-1,$in{'y'});
		}
	
	}
else{
	$startdate = timelocal(0,0,0,$in{'d'},$in{'m'}-1,$in{'y'});
	#$enddate = timelocal(0,59,23,$in{'d'},$in{'m'}-1,$in{'y'});
	$enddate = $startdate + 86400;
	}

($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = gmtime($startdate+(3600*$timeoffset));
$min = sprintf("%02s",$min);
$hour = sprintf("%02s",$hour);
$mon = sprintf("%02s",$mon+1);
$mday = sprintf("%02s",$mday);
$year = sprintf("%04s",$year+1900);
$DTSTART = "$year$mon${mday}T$hour${min}00Z";
($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = gmtime($enddate+(3600*$timeoffset));
$min = sprintf("%02s",$min);
$hour = sprintf("%02s",$hour);
$mon = sprintf("%02s",$mon+1);
$mday = sprintf("%02s",$mday);
$year = sprintf("%04s",$year+1900);
$DTEND = "$year$mon${mday}T$hour${min}00Z";

if($f[15] ne 'checked'){
	$DTEND .= "\nTRANSP:1";
	}

$in{'cfields'}=~ s/\r*\n/=0D=0A/g;

if($in{'cfields'}){
	$in{'cfields'} = '=0D=0A=0D=0A'.$in{'cfields'};
	}

my $siteurl = $ENV{'HTTP_HOST'}; 
$vcs = qq|BEGIN:VCALENDAR
VERSION:1.0
BEGIN:VEVENT
URL:$siteurl
DTSTART:$DTSTART
DTEND:$DTEND
SUMMARY:$in{'title'}
DESCRIPTION;ENCODING=QUOTED-PRINTABLE:$in{'body'}$in{'cfields'}
END:VEVENT
END:VCALENDAR|;

my $size = length($vcs);
print "Content-Type: text/x-vcalendar\n";
print "Content-disposition: inline; filename=\"export.vcs\"\n";
print "Content-length: $size\n\n";
print $vcs;
exit;
}

sub View{

my $evcslink = "$in{'cgiurl'}?command=evcs&calid=$in{'calid'}&id=$in{'id'}&m=$in{'m'}&d=$in{'d'}&y=$in{'y'}";
if($in{'id'} =~ /\-/){
	($in{'id'},$in{'calid'}) = split("-",$in{'id'});
	}

&GetConfig($in{'rcalid'});
my $sfile = &CheckSafe("$datapath/$in{'calid'}.cgi");
open(DB,"$sfile");
while(<DB>){
chomp;
@f = split("\t",$_);
if($f[0] eq $in{'id'}){
  $in{'id'} = $f[0];
  $in{'calid'} = $f[1];
  $in{'cid'} = $f[2];	
  $in{'title'} = $f[3];
  $in{'cv1'} = $f[4];
  $in{'cv2'} = $f[5];
  $in{'cv3'} = $f[6];
  $in{'cv4'} = $f[7];
  $in{'cv5'} = $f[8];
  $in{'cv6'} = $f[9];
  $in{'cv7'} = $f[10];
  $in{'cv8'} = $f[11];
  $in{'cv9'} = $f[12];
  $in{'cv10'} = $f[13];
  $in{'body'} = $f[14];
  $in{'body'} =~ s/&#(\d+);/pack("c",$1)/ge;
  $in{'body'} =~ s/\\n/<br>\n/g;
  $in{'showtimes'} = $f[15];
  $in{'sthour'.$f[16]} = 'selected';
  $in{'stmin'.$f[17]} = 'selected';
  $in{'stsuf'.$f[18]} = 'selected';
  $in{'ethour'.$f[19]} = 'selected';
  $in{'etmin'.$f[20]} = 'selected';
  $in{'etsuf'.$f[21]} = 'selected';
  $in{'etype'.$f[22]} = 'checked';
  $in{'sedate'} = $f[23];
  $in{'sdate'} = $f[24];
  $in{'edate'} = $f[25];
  $in{'srdate'} = $f[26];
  $in{'erdate'} = $f[27];
  $in{'ed'.$f[28]} = 'checked';
  $in{'oc'} = $f[29];
  $in{'pattern'.$f[30]} = 'checked';
  $in{'pdaily'} = $f[31];
  $in{'pweekly'} = $f[32];
  $in{'wd0'} = $f[33];
  $in{'wd1'} = $f[34];
  $in{'wd2'} = $f[35];
  $in{'wd3'} = $f[36];
  $in{'wd4'} = $f[37];
  $in{'wd5'} = $f[38];
  $in{'wd6'} = $f[39];
  $in{'monthlytype'.$f[40]} = 'checked';
  $in{'m1'} = $f[41];
  $in{'m2'} = $f[42];
  $in{'m3'.$f[43]} = 'selected';
  $in{'m4'.$f[44]} = 'selected';
  $in{'m5'} = $f[45];
  $in{'yearlytype'.$f[46]} = 'checked';
  $in{'y1'.$f[47]} = 'selected';
  $in{'y2'} = $f[48];
  $in{'y3'.$f[49]} = 'selected';
  $in{'y4'.$f[50]} = 'selected';
  $in{'y5'.$f[51]} = 'selected';
  $in{'approve'} = $f[52];
  last;
  }
}
close DB;

foreach my $i (1..10){
	next if ($in{'c'.$i} lt '0');
	$in{'cfields'} .= qq|
	<tr>
		<td class="calendarday"><b>$in{'c'.$i}:</b></td>
	</tr>
	<tr>
		<td class="calendarday">$in{'cv'.$i}</td>
	</tr>
	|;
	}

$f[17] = sprintf("%.2d",$f[17]);
$f[20] = sprintf("%.2d",$f[20]);

if(($f[22] eq 'multiple')&&(!$set{$f[0]})&&($f[25])){
		my($sm,$sd,$sy) = $f[24] =~ /(\d*)[^\d](\d*)[^\d](\d*)/;
		my($em,$ed,$ey) = $f[25] =~ /(\d*)[^\d](\d*)[^\d](\d*)/;

			if($f[15] eq 'checked'){
				if(($f[16])&&($f[17])&&($f[18])){
					$timestart= "$f[16]:$f[17] $f[18]";
					}
				if(($f[19])&&($f[20])&&($f[21])){
					$timeend = "$f[19]:$f[20] $f[21]";
					}
				}

		$in{'fulldate'} = "$sm$in{'Separator'}$sd$in{'Separator'}$sy $timestart to $em$in{'Separator'}$ed$in{'Separator'}$ey $timeend";
		}
else{
	$in{'fulldate'} = &ctime(timelocal(0,0,0,$in{'d'},$in{'m'}-1,$in{'y'}));
	chomp $in{'fulldate'};
	}
if(($f[15] eq 'checked')&&($f[22] ne 'multiple')){
			$in{'fulltime'} .= "<br>$f[16]:$f[17] $f[18] - $f[19]:$f[20] $f[21]";
			}
			
if($in{'acomments'}){

(!$in{'cpp'})&&($in{'cpp'} = 5);
$/="\n\n";
open(CMT,"<$datapath/$in{'id'}-comments.cgi");
	($flock)&&(flock(CMT,2));
	my($c);
	while(<CMT>){
		chomp;
		$_ =~ s/\r//g;
		$c++;
		last if ($c > $in{'cpp'});
		$_ =~ s/([^\w\s\:\-])/'&#'.ord($1).';'/ge;
		$_ =~ s/^(.*?): /<b>$1: <\/b>/g;
		$_ =~ s/\n/<br>\n/g;
		$in{'comments'} .= $_."\n<hr size=1>\n";
		}
	close CMT;
undef $/;
if($in{'comments'}){
	$in{'comments'} = qq|<br><hr><div align=center><font size=3><b>Comments</b></font></div><hr><br>$in{'comments'}<div align=right><a href="javascript:ShowMore();">more »</a></div>|;
	}
else{
	$in{'comments'} = qq|<br><hr><div align=center><b>No comments submitted</b></div><hr>|;
	}


$in{'cform'} = qq|
<hr><div align=center><font size=3><b>Add Comment</b></font></div><hr>
<form method="POST" action="$in{'cgiurl'}">
                    <input type=hidden name=command value=savecomment>
                    <input type=hidden name=id value=$in{'id'}>
                    <input type=hidden name=calid value=$in{'calid'}>
                    <input type=hidden name=d value=$in{'d'}>
                    <input type=hidden name=y value=$in{'y'}>
                    <input type=hidden name=m value=$in{'m'}>
                    
                      <div align="center">
                        <table border="0" cellpadding="3" cellspacing="0">
                          <tr>
                            <td class="calendarday" align="right">Name:</td>
                            <td align="left"><input type="text" class="calendarform" name="name" size="20"></td>
                          </tr>
                          <tr>
                            <td colspan="2" class="calendarday" align="left">Comment:<br>
                              <textarea rows="4" class="calendarform" name="comment" cols="32"></textarea></td>
                          </tr>
                        </table>
                      </div>
                      <p align="center"><input class="calendarform" type="submit" value="Submit Comment"></p>
                    </form>
                    <hr>
|;
}


if($in{'t'} eq '1'){
	$in{'viewbutton'} = qq|<input type="button" value="Back" onClick="history.back();" class="calendarform">|;
	}
else{
	$in{'viewbutton'} = qq|<input type="button" value="Close" onClick="window.close();" class="calendarform">|;
	}
	
if($in{'showexport'}){	
	$in{'viewbutton'} .= qq| <input type="button" value="Export Event" onClick="window.location='$evcslink'" class="calendarform">|;	
	}
&PageOut("$cgipath/t_view.htm");
exit;
}

sub Approve{
my $sfile = &CheckSafe("$datapath/calendardata.cgi");
open(DB,"+<$sfile");
while(<DB>){
  @f = split("~",$_);
  ($f[0] ne $in{'id'})?(push(@l,$_)):(push(@l,"$f[0]~$f[1]~$f[2]~$f[3]~$f[4]~$f[5]~1\n"));
  }
seek(DB,0,0);
foreach $i (@l){
  print DB $i;
  }
truncate(DB, tell(DB));
print <<"EOF";
<script language=javascript>
var rndURL = (1000*Math.random());
alert("Event Approved.");
window.location = "$in{'cgiurl'}?command=showpending&mday=$in{'mday'}&mymonth=$in{'mymonth'}&myyear=$in{'myyear'}&viewby=$in{'viewby'}&mode=0&rnd="+rndURL;
</script>
EOF
exit;
}

sub ShowEditEvent{
&GetConfig($in{'calid'});
my $sfile = &CheckSafe("$datapath/$in{'calid'}.cgi");
open(DB,"$sfile");
while(<DB>){
chomp;
@f = split("\t",$_);
if($f[0] eq $in{'id'}){

  $in{'id'} = $f[0];
  $in{'calid'} = $f[1];
  $in{'cid'} = $f[2];	
  $in{'title'} = $f[3];
  
  $in{'cv1'} = $f[4];
  $in{'cv2'} = $f[5];
  $in{'cv3'} = $f[6];
  $in{'cv4'} = $f[7];
  $in{'cv5'} = $f[8];
  $in{'cv6'} = $f[9];
  $in{'cv7'} = $f[10];
  $in{'cv8'} = $f[11];
  $in{'cv9'} = $f[12];
  $in{'cv10'} = $f[13];
  
  $in{'cv1'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
  $in{'cv2'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
  $in{'cv3'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
  $in{'cv4'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
  $in{'cv5'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
  $in{'cv6'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
  $in{'cv7'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
  $in{'cv8'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
  $in{'cv9'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
  $in{'cv10'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
  
  $in{'body'} = $f[14];

  $in{'body'} =~ s/\\n/\n/g;
  
  $in{'showtimes'} = $f[15];
  $in{'sthour'.$f[16]} = 'selected';
  $in{'stmin'.$f[17]} = 'selected';
  $in{'stsuf'.$f[18]} = 'selected';
  $in{'ethour'.$f[19]} = 'selected';
  $in{'etmin'.$f[20]} = 'selected';
  $in{'etsuf'.$f[21]} = 'selected';
  $in{'etype'.$f[22]} = 'checked';
  $in{'sedate'} = $f[23];
  $in{'sdate'} = $f[24];
  $in{'edate'} = $f[25];
  $in{'srdate'} = $f[26];
  $in{'erdate'} = $f[27];
  $in{'ed'.$f[28]} = 'checked';
  $in{'oc'} = $f[29];
  $in{'pattern'.$f[30]} = 'checked';
  $in{'pdaily'} = $f[31];
  $in{'pweekly'} = $f[32];
  $in{'wd0'} = $f[33];
  $in{'wd1'} = $f[34];
  $in{'wd2'} = $f[35];
  $in{'wd3'} = $f[36];
  $in{'wd4'} = $f[37];
  $in{'wd5'} = $f[38];
  $in{'wd6'} = $f[39];
  $in{'monthlytype'.$f[40]} = 'checked';
  $in{'m1'} = $f[41];
  $in{'m2'} = $f[42];
  $in{'m3'.$f[43]} = 'selected';
  $in{'m4'.$f[44]} = 'selected';
  $in{'m5'} = $f[45];
  $in{'yearlytype'.$f[46]} = 'checked';
  $in{'y1'.$f[47]} = 'selected';
  $in{'y2'} = $f[48];
  $in{'y3'.$f[49]} = 'selected';
  $in{'y4'.$f[50]} = 'selected';
  $in{'y5'.$f[51]} = 'selected';
  $in{'approve'} = $f[52];
  $in{'approve'.$f[52]} = 'selected';
  $in{'color'} = $f[53];
  $in{'lurl'} = $f[54];
  $in{'ltarget'} = $f[55];
  $in{'othertarget'} = $f[56];
  ($in{'ltarget'} eq '_self')&&($in{'lself'} = 'checked');
  ($in{'ltarget'} eq '_blank')&&($in{'lblank'} = 'checked');
  ($in{'ltarget'} eq 'other')&&($in{'lother'} = 'checked');
  last;
  }
}
close DB;


foreach my $i (1..10){
	next if ($in{'c'.$i} lt '0');
	
	$in{'cfields'} .= qq|<tr>
                        <td align="right"><b><font size="2">$in{'c'.$i}:</font></b></td>
                        <td vAlign="top">
                        <input maxLength="512" size="35" name="cv$i" value="$in{'cv'.$i}"></td>
                      	</tr>|;
	}
	
$in{'command'} = 'sce';
my($comments) = '';

if($in{'acomments'}){
my($file) = &CheckSafe("$datapath/$in{'id'}-comments.cgi");
open(CMT,"<$file");
while(<CMT>){
	$comments .= $_;
	}
close CMT;

if($comments){

$comments =~ s/&#(\d+);/pack("c",$1)/ge;
$comments =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;

$comments = qq|
<tr>
	<td vAlign="top" align="left">
		<b>Comments:</b><br>
		<textarea name=comments rows=10 cols=80>$comments</textarea>
	</td>
</tr>
|;
}

}

$in{'appr'} = qq|
<tr>
    <td vAlign="top" align="center">
      <div align="left">
        <table border="0" cellpadding="3" cellspacing="0">
          <tr>
             <td><b>Status:</b></td>
             <td><select size="1" name="approve">
               <option value=1 $in{'approve1'}>Enabled</option>
               <option value=0 $in{'approve0'}>Disabled</option>
               </select>
             </td>
          </tr>
        </table>
      </div>
    </td>
</tr>
$comments
|;

if($f[53]){
	$in{'color'} = qq|<option style="color: $in{'color'}">$in{'color'}</option>\n|;
	}
&PageOut("$cgipath/t_add_event.htm");
}

sub SaveCalendar{
	$in{'CalDesc'} =~ s/<\/(.*)>/$1/gi;
	$in{'CalName'} =~ s/<\/(.*)>/$1/gi;
	(length($in{'CalName'}) > 50)&&(&PError("Error. Calendar name has to be 50 characters or less"));
	if(!$in{'calid'}){
		&SaveNewCalendar;
	}
	else{
		my(@p);
		my($file) = &CheckSafe("$datapath/calendars.cgi");
		open(DB,"+<$file");
		($flock)&&(flock(DB,2));
		while(<DB>){
		   	my(@f) = split("\t",$_);
		   	if($f[0] eq $in{'calid'}){
		   		$in{'CalDesc'} =~ s/\r*\n/\\n/g;$in{'CalDesc'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
		   		$f[3] = $in{'CalName'};
		   		$f[4] = $in{'CalDesc'};
		   		my($nv) = join("\t",@f);
		   		push(@p,$nv);
		   	}
		   	else{
		   		push(@p,$_);
		   		}
		  	}
		seek(DB,0,0);
		foreach my $i (@p){
		   	print DB $i;
		   	}
		truncate(DB, tell(DB));
		($flock)&&(flock(DB,8));
		close DB;
	}
	&Redirect($in{'cgiurl'} . "?command=manage&cid=$in{'cid'}","Calendar Saved");
	exit;
	}
	
sub SaveNewCalendar{
	my($id) = &GetID;
	my($file) = &CheckSafe("$datapath/calendars.cgi");
	open(DB,">>$file");
	($flock)&&(flock(DB,2));
	$in{'CalDesc'} =~ s/\r*\n/\\n/g;$in{'CalDesc'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
	print DB "$id\t$in{'UserName'}\t$in{'cid'}\t$in{'CalName'}\t$in{'CalDesc'}\tEnglish\tHyphen\t\t\t\t\t\t\t\t10\t\t\t\t\t\t\t\t\t\t\t\t0\t1\t500\t600\t\t\t\t\t\t\t\t\t\t\n";
	($flock)&&(flock(DB,8));
	close DB;
	$in{'calid'} = $id;
	}
	
sub GetOutVars{
	my ($approve,$id,$calid) = @_;	
	($in{'sedate'})&&($in{'sedate'} !~ /\d+\-\d+-\d\d\d\d/)&&(&PError("Error. Invalid event date"));
	($in{'sdate'})&&($in{'sdate'} !~ /\d+\-\d+\-\d\d\d\d/)&&(&PError("Error. Invalid start date"));
	($in{'edate'})&&($in{'edate'} !~ /\d+\-\d+\-\d\d\d\d/)&&(&PError("Error. Invalid start date"));
	($in{'srdate'})&&($in{'srdate'} !~ /\d+\-\d+\-\d\d\d\d/)&&(&PError("Error. Invalid start date"));
	($in{'erdate'})&&($in{'erdate'} !~ /\d+\-\d+\-\d\d\d\d/)&&(&PError("Error. Invalid start date"));
	#id	calid	cid	title	c1	c2	c3	c4	c5	c6	c7	c8	c9	c10	body	showtimes	sthour	stmin	stsuf	ethour	etmid	suf	etype	sedate	sdate	edate	srdate	erdate	ed	oc	pattern	pdaily	pweekly	wd0	wd1	wd2	wd3	wd4	wd5	wd5	monthlytype	m1	m2	m3	m4	m5	yearlytype	y1	y2	y3	y4	y5	approve color lurl
	#0	1	2	3	4	5	6	7	8	9	10	11	12	13	14	15		16	17	18	19	20	21	22	23	24	25	26	27	28	29	30	31	32	33	34	35	36	37	38	39	40		41	42	42	44	45	46		47	48	49	50	51	52       53	54
	$newentry = "$id\t$calid\t$in{'cid'}\t$in{'title'}\t$in{'cv1'}\t$in{'cv2'}\t$in{'cv3'}\t$in{'cv4'}\t$in{'cv5'}\t$in{'cv6'}\t$in{'cv7'}\t$in{'cv8'}\t$in{'cv9'}\t$in{'cv10'}\t$in{'body'}\t$in{'showtimes'}\t$in{'sthour'}\t$in{'stmin'}\t$in{'stsuf'}\t$in{'ethour'}\t$in{'etmin'}\t$in{'etsuf'}\t$in{'etype'}\t$in{'sedate'}\t$in{'sdate'}\t$in{'edate'}\t$in{'srdate'}\t$in{'erdate'}\t$in{'ed'}\t$in{'oc'}\t$in{'pattern'}\t$in{'pdaily'}\t$in{'pweekly'}\t$in{'wd0'}\t$in{'wd1'}\t$in{'wd2'}\t$in{'wd3'}\t$in{'wd4'}\t$in{'wd5'}\t$in{'wd6'}\t$in{'monthlytype'}\t$in{'m1'}\t$in{'m2'}\t$in{'m3'}\t$in{'m4'}\t$in{'m5'}\t$in{'yearlytype'}\t$in{'y1'}\t$in{'y2'}\t$in{'y3'}\t$in{'y4'}\t$in{'y5'}\t$approve\t$in{'color'}\t$in{'lurl'}\t$in{'ltarget'}\t$in{'othertarget'}\t";
	}

sub ViewCalendarSub{
(!$in{'viewby'})&&($in{'viewby'} = $vdefault);

my($tm) = (localtime(time))[4]+1;
my($ty) = (localtime(time))[5]+1900;

if(($in{'mymonth'})&&(!$in{'mday'})&&(!$in{'e'})){
if($in{'mymonth'} == $tm){
	$in{'mday'} = (localtime(time + (3600 * $timeoffset ) ))[3];
	}
else{
	$in{'mday'} = 1;
	}
}

if((!$in{'mymonth'})||($in{'e'})){
  &GetDateInfo(time);
  }

else{
  #($in{'myyear'} != $ty)&&($in{'mday'}=1);
  &GetDateInfo(timelocal(0,0,12,$in{'mday'},$in{'mymonth'}-1,$in{'myyear'}));
  }


(!$in{'myday'})&&($in{'myday'}='01');
(!$in{'mday'})&&($in{'mday'}=$in{'myday'});

&GetEvents;

&CreateCalendar;
$in{'mymonth'} = sprintf("%.2d",$in{'mymonth'});
$in{'m'.$in{'mymonth'}} = 'selected';
$in{'y'.$in{'myyear'}} = 'selected';



$in{'fulldate'} = &ctime(timelocal(0,0,0,$in{'mday'},$in{'mymonth'}-1,$in{'myyear'}));

($in{'viewby'} eq 'month')&&($msg = 'month');
($in{'viewby'} eq 'day')&&($msg = 'day');
($in{'viewby'} eq 'all')&&($msg = 'calendar');
($in{'mode'} eq '0')&&($msg = 'queue');
(!$in{'eventline'})&&($in{'eventline'} = qq|<tr><td colspan="$in{'cols'}" class="calendarday">No entries for this $msg.</td></tr>|);
($in{'viewby'} eq 'month')&&($in{'vmonth'} = 'selected');
($in{'viewby'} eq 'day')&&($in{'vday'} = 'selected');
($in{'viewby'} eq 'all')&&($in{'vall'} = 'selected');
}

sub DoUserManage{

open(DB,"<$datapath/categories.cgi");
while(<DB>){
	chomp;
	my($id,$uid,$catname) = split("\t",$_);
	$calcat{$id} = $catname;	
	}
close DB;

open(DB,"<$datapath/calendars.cgi");
	while(<DB>){
	chomp;
	my($id,$uid,$cid,$calName,@rest) = split("\t",$_);
	next if (!$calName);
	
	
	if((!$udel{$id})&&(!$umod{$id})&&(!$uadd{$id})&&(!$uconf{'deletethiscatall'})&&(!$uconf{'addthiscatall'})&&(!$uconf{'modifythiscatall'})){
		next;
		}
	(!$in{'calid'})&&($in{'calid'} = $id);
	
	if ($in{'calid'} == $id) {
			$selected = 'selected';
			}
		else{
			$selected = '';
		}
	$calendars{$calcat{$cid}.'-'.$calName.'-'.$id} = qq~
	<option value="$id" $selected>$calcat{$cid} - $calName</option>
	~;
	}
	close DB;
	
	foreach my $i (sort keys %calendars){
		$in{'calendars'} .= $calendars{$i};
		}

$in{'rcalid'} = $in{'calid'};
$in{'command'} = 'modify';
$in{'categoryname'} = &GetCatName($in{'calid'});
&GetConfig($in{'calid'});
&ManageView($in{'calid'});

if(($uadd{$in{'calid'}})||($uconf{'addthiscat'})||($uconf{'addthiscatall'})){
	$in{'addeventbutton'} = qq|<input type="button" class="button" onMouseOver="className='buttonOver';" onMouseOut="className='button';" value="Add an Event" onClick="document.form1.command.value='showadde';document.form1.submit();">|;
	}

$in{'calline'} = qq|
<tr><td><font size=2>Current Calendar:</td><td><select name=calid onChange="document.form1.command.value='manage';document.form1.submit();">$in{'calendars'}</option></td></tr>
|;

$in{'cid'} = $in{'calid'};
&PageOut("$cgipath/t_add_edit_calendar_user.htm");
exit;
}

sub Manage{

	if($isUser==1){
		&DoUserManage;
		}
	my ($catId) = $in{'cid'};
	my($selected,%calendars);
	my($file) = &CheckSafe("$datapath/categories.cgi");
	open(DB,"<$file");
	while(<DB>){
		chomp;
		my($id,$uid,$catname) = split("\t",$_);
		($module)&&($in{'atype'} ne 'admin')&&($uid ne $in{'UserName'})&&(next);
		(!$in{'cid'})&&($in{'cid'} = $id)&&($catId = $id);
			if ($id == $catId) {
				$selected = 'selected';
				$in{"CatName"} = $catname; 
				}
			else{
				$selected = '';
				}
		$in{'categories'} .= qq|<option value=\"$id\" $selected>$catname</option>\n|;
		}
	close DB;
	(!$in{'categories'})&&($in{'categories'} = '<option value="">No categories configured</option>');
	my($file) = &CheckSafe("$datapath/calendars.cgi");
	open(DB,"<$file");
	while(<DB>){
		chomp;
		my($id,$uid,$cid,$calName,@rest) = split("\t",$_);
		($module)&&($in{'atype'} ne 'admin')&&($uid ne $in{'UserName'})&&(next);

	$calendars{$calName.'-'.$id} = qq~
	        <tr>
	        	<td align="center" nowrap><font size=1>&nbsp;
	        		<a class="csCalendar" href="$in{'cgiurl'}?command=modify&cid=$catId&calid=$id">Modify</a>&nbsp; |&nbsp;
	        		<a class="csCalendar" href="$in{'cgiurl'}?command=delete&cid=$catId&calid=$id" onclick="if (confirm('Delete This Calendar?')) {return true;} else {return false;}">Delete</a>&nbsp; |&nbsp;
	        		<a class="csCalendar" href="$in{'cgiurl'}?command=sc&cid=$catId&calid=$id">Configure</a>&nbsp;
	        	</font>
	        	</td>
	        	<td align="left" nowrap>
	        		<a class="csCalendar" href="$in{'cgiurl'}?calid=$id&command=viewsmall" target=_blank>$calName</a>
	        	</td>
	        </tr>
	~  unless ($cid != $catId);
	}
	close DB;
	
	foreach my $i (sort keys %calendars){
		$in{'calendars'} .= $calendars{$i};
		}
	
	(!$in{'calendars'})&&($in{'calendars'} = qq|<tr><td colspan=5>No calendars in this category</td></tr>|);
	
	if($in{'atype'} eq 'admin'){
		require("$cgipath/t_cp.htm");
		}
		
	&PageOut("$cgipath/t_manage.htm");
	exit;
	}

sub ShowAddCategory{
	&PageOut("$cgipath/t_add_edit_category.htm");
	exit;
	}

sub AddCategory{
	my($id) = &GetID;
	($in{'catname'} =~ /([<>])/)&&(&PError("Error. $1 characters are not allowed in category name."));
	(length($in{'catname'}) > 50)&&(&PError("Error. Category name has to be 50 characters or less"));
	my($file) = &CheckSafe("$datapath/categories.cgi");
	open(DB,">>$file");
	print DB "$id\t$in{'UserName'}\t$in{'catname'}\n";
	close DB;
	print qq|
		<script>
		window.opener.location='$in{'cgiurl'}?command=manage&cid=$id';
		self.close();
		</script>
		|;
	exit;
}

sub GetID{
	my($id);
	open(DB,"<$datapath/_gcount.cgi");
	$id = <DB>;
	close DB;
	$id++;
	open(DB,">$datapath/_gcount.cgi");
	print DB $id;
	close DB;
	return $id;
	}

sub DeleteCategory {
	my ($catId) = $in{'cid'} || &cgierr("fatal error: DeleteCategory - no id specified");
	my(@c,@p);
	my($file) = &CheckSafe("$datapath/categories.cgi");
	open(DB,"+<$file");
	($flock)&&(flock(DB,2));
	while(<DB>){
		my($id,$uid,$name) = split("\t",$_);
		push(@c,$_) unless ($id eq $catId);
		}
	seek(DB,0,0);
	foreach my $i (@c){
		print DB $i;
		}
	truncate(DB, tell(DB));
	($flock)&&(flock(DB,8));
	close DB;
	undef(@c);
	
	my($file) = &CheckSafe("$datapath/calendars.cgi");
	open(DB,"+<$file");
	($flock)&&(flock(DB,2));
	while(<DB>){
	   	my($id,$uid,$cid,@rest) = split("\t",$_);
	   	($cid eq $catId)?(&DeleteCalendar($id)):(push(@p,$_));
	  	}
	seek(DB,0,0);
	foreach my $i (@p){
	   	print DB $i;
	   	}
	truncate(DB, tell(DB));
	($flock)&&(flock(DB,8));
	close DB;

	&Redirect($in{'cgiurl'} . "?command=manage","Category Deleted");
	}
	
sub DeleteCalendar{
	my($calid) = @_;
	my($file) = &CheckSafe("$datapath/$calid.cgi");
	unlink($file);
	}
	
sub DeleteCal2 {
	my(@p,$d);
	my($file) = &CheckSafe("$datapath/calendars.cgi");
	open(DB,"+<$file");
	($flock)&&(flock(DB,2));
	while(<DB>){
	   	my($id,$uid,$cid,@rest) = split("\t",$_);
	   	($id ne $in{'calid'})&&(push(@p,$_));
	  	}
	seek(DB,0,0);
	foreach my $i (@p){
	   	print DB $i;
	   	}
	truncate(DB, tell(DB));
	($flock)&&(flock(DB,8));
	close DB;
	my($file) = &CheckSafe("$datapath/$in{'calid'}.cgi");
	unlink($file);
	&Redirect($in{'cgiurl'} . "?command=manage&cid=$in{'cid'}","Calendar Deleted");
	}
	
sub ManageView{
my($calid) = @_;

&ViewCalendarSub;
my $sfile = &CheckSafe("$datapath/$calid.cgi");
open(DB,"<$sfile");
while(<DB>){
	chomp;
	@f = split("\t",$_);
	
	if($f[53]){
		$f[3] = qq|<font color="$f[53]">$f[3]</font>|;
		}
	
	#id	calid	cid	title	c1	c2	c3	c4	c5	c6	c7	c8	c9	c10	body	showtimes	sthour	stmin	stsuf	ethour	etmid	suf	etype	sedate	sdate	edate	srdate	erdate	ed	oc	pattern	pdaily	pweekly	wd0	wd1	wd2	wd3	wd4	wd5	wd5	monthlytype	m1	m2	m3	m4	m5	yearlytype	y1	y2	y3	y4	y5	approve
	#0	1	2	3	4	5	6	7	8	9	10	11	12	13	14	15		16	17	18	19	20	21	22	23	24	25	26	27	28	29	30	31	32	33	34	35	36	37	38	39	40		41	42	42	44	45	46		47	48	49	50	51	52

	if($f[22] eq 'single'){
		$when = "$f[23]";
		if($f[15] eq 'checked'){
			if($f[19]){
				$when .= " from $f[16]:$f[17] $f[18] to $f[19]:$f[20] $f[21]";
				}
			else{
				$when .= " at $f[16]:$f[17] $f[18]";			
				}
			}
		}
	elsif($f[22] eq "multiple"){
		$when = "$f[24] to $f[25]";
		if($f[15] eq 'checked'){
			if($f[19]){
				$when .= " from $f[16]:$f[17] $f[18] to $f[19]:$f[20] $f[21]";
				}
			else{
				$when .= " at $f[16]:$f[17] $f[18]";			
				}
			}
		}
	else{
		$when = "starting on $f[26]";
		if($f[28] == 2){
			$when .= " ending after $f[29] occurences";
			}
		if($f[28] == 3){
			$when .= " ending on $f[27]";
			}
		
		
	
	
	if($f[30] == 1){
			 $when .= " repeating every $f[31] day(s)";
			}
			
	if($f[30] == 2){
		undef(@d);
		($f[33])&&(push(@d,"Sunday"));
		($f[34])&&(push(@d,"Monday"));
		($f[35])&&(push(@d,"Tuesday"));
		($f[36])&&(push(@d,"Wednesday"));
		($f[37])&&(push(@d,"Thursday"));
		($f[38])&&(push(@d,"Friday"));
		($f[39])&&(push(@d,"Saturday"));
		$dw = join(", ",@d);
			$when .= " repeating every $f[32] week(s) on $dw";
		}
		
	if($f[30] == 3){
		if($f[40] == 1){
			$when = " repeating day $f[41] of every $f[42] month(s)";
			}
		else{
			$when = " repeating the $f[43] $f[44] of every $f[45] month(s)";
			}
	}
	
	if($f[30] == 4){
		if($f[46] == 1){
			$when = " repeating every $f[47] $f[48]";
			}
		else{
			$when = " repeating the $f[49] $f[50] of $f[51]";
			}
	}
	
	}
	
	if($isUser){
		$editbutton='';$deletebutton='';
		if(($umod{$calid})||($uconf{'modifythiscatall'})){
			$editbutton = qq|<input type="button" class="button" onMouseOver="className='buttonOver';" onMouseOut="className='button';" value="Edit" onClick="Edit('$f[0]')">|;
			}
		if(($udel{$calid})||($uconf{'deletethiscatall'})){
			$deletebutton = qq|<input type="button" class="button" onMouseOver="className='buttonOver';" onMouseOut="className='button';" value="Delete" onClick="Delete('$f[0]')">|;
			}
		if(($editbutton)&&($deletebutton)){
			$editbutton .= '&nbsp;';
			}
	
		if($f[52] == 1){
			$in{'line'} .= qq|
			 <tr>
			    <td align="center">$when</td>
			    <td align="center">$f[3]</td>
			    <td align="center">$editbutton$deletebutton</td>
	                </tr>
			|;
			}
		else{
			$in{'pline'} .= qq|
					 <tr>
					    <td align="center">$when</td>
					    <td align="center">$f[3]</td>
					    <td align="center">$editbutton$deletebutton</td>
	                </tr>
			|;
			}
	}
	else{
		if($f[52] == 1){
			$in{'line'} .= qq|
			 <tr>
			    <td align="center">$when</td>
			    <td align="center">$f[3]</td>
			    <td align="center"><input type="button" class="button" onMouseOver="className='buttonOver';" onMouseOut="className='button';" value="Edit" onClick="Edit('$f[0]')">&nbsp;<input type="button" class="button" onMouseOver="className='buttonOver';" onMouseOut="className='button';" value="Delete" onClick="Delete('$f[0]')"></td>
        	        </tr>
			|;
			}
		else{
			$in{'pline'} .= qq|
				 <tr>
				    <td align="center">$when</td>
				    <td align="center">$f[3]</td>
				    <td align="center"><input type="button" class="button" onMouseOver="className='buttonOver';" onMouseOut="className='button';" value="Edit" onClick="Edit('$f[0]')">&nbsp;<input type="button" class="button" onMouseOver="className='buttonOver';" onMouseOut="className='button';" value="Delete" onClick="Delete('$f[0]')"></td>
        	        </tr>
			|;
			}
	}
}
close DB;
($in{'pline'})?($in{'spline'} = '1'):($in{'spline'} = '');
(!$in{'pline'})&&($in{'pline'} = '<tr><td colspan=3>No events pending approval</td></tr>');
(!$in{'line'})&&($in{'line'} = '<tr><td colspan=3>No events entered</td></tr>');

return;
}


sub DoSingle{
my($line) = @_;
if($in{'e'} eq '1'){
	$in{'viewby'} = 'all';
	}

my($m,$d,$y) = $f[23] =~ /(\d*)[^\d](\d*)[^\d](\d*)/;
$m = sprintf("%.2d",$m);
$d = sprintf("%.2d",$d);
$y = sprintf("%.4d",$y);
$h{$d.$m.$y}='<b>';

$c{$d.$m.$y}="bgcolor=\"$eventcolor\"";

my($h) = $f[16];
if($f[18] eq 'AM'){
	($h == 12)&&($h=0);
	}
else{
	($h < 12)&&($h+=12);
	}
$h = sprintf("%.2d",$h);

if($m == $in{'mymonth'}){
	my ($when);
	if($f[15] eq 'checked'){
		if($f[19]){
			$when = "<br>$f[16]:$f[17] $f[18] - $f[19]:$f[20] $f[21]";
			}
		else{
			$when = "<br>$f[16]:$f[17] $f[18]";		
			}
	}
	
	if(!$f[54]){
		if($f[14]){
			if($in{'pd'} ne '1'){
				$to{$d.$m.$y.$h.$f[17].$f[0]} .= "» <a href=\"$in{'cgiurl'}?calid=$f[1]&command=view&t=1&id=$f[0]&m=$m&d=$d&y=$y\">$f[3]$when</a><br>";
				}
			else{
				$to{$d.$m.$y.$h.$f[17].$f[0]} .= "» <a href=\"javascript:View$in{'rcalid'}('$f[0]-$f[1]','$y','$m','$d');\">$f[3]$when</a><br>";
				}
			}
		else{
			$to{$d.$m.$y.$h.$f[17].$f[0]} .= "$f[3]$when<br>";
			}
		}
	
	#override if URL exists
	if($f[54]){
		if($f[55] eq 'othertarget'){
			$f[55] = $f[56];
			}
		$to{$d.$m.$y.$h.$f[17].$f[0]} .= "» <a href=\"$f[54]\" target=\"$f[55]\">$f[3]$when</a><br>";
		}
	}

if($in{'viewby'} eq 'month'){
	if(($m == $in{'mymonth'})&&($y == $in{'myyear'})){
		$order{"$y$m$d$h$f[17]$f[0]"} = $line;
		}
	}
elsif($in{'viewby'} eq 'day'){
	if(($d == $in{'mday'})&&($m == $in{'mymonth'})&&($y == $in{'myyear'})){
		$order{"$y$m$d$h$f[17]$f[0]"} = $line;
		}
  	}
else{
	$order{"$y$m$d$h$f[17]$f[0]"} = $line;
  	}

}

sub DoMultiple{
my($line) = @_;
my($m,$d,$y) = $f[24] =~ /(\d*)[^\d](\d*)[^\d](\d*)/;
my($me,$de,$ye) = $f[25] =~ /(\d*)[^\d](\d*)[^\d](\d*)/;
$m = sprintf("%.2d",$m);
$d = sprintf("%.2d",$d);
$y = sprintf("%.4d",$y);
$me = sprintf("%.2d",$me);
$de = sprintf("%.2d",$de);
$ye = sprintf("%.4d",$ye);

my($h) = $f[16];
if($f[18] eq 'AM'){
	($h == 12)&&($h=0);
	}
else{
	($h < 12)&&($h+=12);
	}
$h = sprintf("%.2d",$h);
		
#get dates in between.
my($st) = timelocal(0,0,12,$d,$m-1,$y);
my($et) = timelocal(0,0,12,$de,$me-1,$ye);
my($nd) = int(($et-$st)/86400);

my($found)=0;
for my $i (0..$nd){
	my($mt) = $st + (86400*$i);
	my ($mday,$mon,$year) = (localtime($mt))[3,4,5];
	$mon = sprintf("%.2d",$mon+1);
	$mday = sprintf("%.2d",$mday);
	$year = sprintf("%.4d",$year+1900);

	if(($mon == $in{'mymonth'})&&($year == $in{'myyear'})){
		$c{$mday.$mon.$year}="bgcolor=\"$eventcolor\"";
		my($when,$timestart,$timeend);
		#if($f[15] eq 'checked'){
		#	$when = "<br>$f[16]:$f[17] $f[18] - $f[19]:$f[20] $f[21]";
		#}
		
		if($f[15] eq 'checked'){
				if(($f[16])&&($f[17])&&($f[18])){
					my $mt = $m+0;
					$timestart= "$mt$in{'Separator'}$d$in{'Separator'}$y $f[16]:$f[17] $f[18]";
					}
				if(($f[19])&&($f[20])&&($f[21])){
					my $mt = $me+0;
					$timeend = "$mt$in{'Separator'}$de$in{'Separator'}$ye $f[19]:$f[20] $f[21]";
					}
				if($timeend){
					$when = "<br>$timestart to $timeend";
					}
				else{
					$when = "<br>$timestart";
					}
				}
				
		
		if(!$f[54]){
			if($f[14]){
				if($in{'pd'} ne '1'){
					$to{$mday.$mon.$year.$h.$f[17].$f[0]} .= "» <a href=\"$in{'cgiurl'}?calid=$f[1]&command=view&t=1&id=$f[0]&m=$mon&d=$mday&y=$year\">$f[3]$when</a><br>";
					}
				else{
					$to{$mday.$mon.$year.$h.$f[17].$f[0]} .= "» <a href=\"javascript:View$in{'rcalid'}('$f[0]-$f[1]','$year','$mon','$mday');\">$f[3]$when</a><br>";
					}
				}
			else{
				$to{$mday.$mon.$year.$h.$f[17].$f[0]} .= "$f[3]$when</a>";
				}
			}
		$h{$mday.$mon.$year}='<b>';
		
		#override if URL exists
		if($f[54]){
			if($f[55] eq 'othertarget'){
				$f[55] = $f[56];
				}
			$to{$mday.$mon.$year.$h.$f[17].$f[0]} .= "» <a href=\"$f[54]\" target=\"$f[55]\">$f[3]$when</a><br>";
			}
		}
		
		
	if($in{'viewby'} eq 'month'){
		if(($mon == $in{'mymonth'})&&($year == $in{'myyear'})){
		
			$order{"$year$mon$mday$h$f[17]$f[0]"} = $line;
			$h{$mday.$mon.$year}='<b>';
		
			}
		}
	elsif($in{'viewby'} eq 'day'){
		if(($mday == $in{'mday'})&&($mon == $in{'mymonth'})&&($year == $in{'myyear'})){
			
			$order{"$year$mon$mday$h$f[17]$f[0]"} = $line;
			$h{$mday.$mon.$year}='<b>';
			
			}
	  	}
	else{
		
		$order{"$year$mon$mday$h$f[17]$f[0]"} = $line;
		$h{$mday.$mon.$year}='<b>';
			
  		}
	
	}

}

sub DoRecurring{
my($line) = @_;
my($m,$d,$y) = $f[26] =~ /(\d*)[^\d](\d*)[^\d](\d*)/;
my($me,$de,$ye,$ed);
#need to set nc
my($nc)=0;
$m = sprintf("%.2d",$m);
$d = sprintf("%.2d",$d);
$y = sprintf("%.4d",$y);
if($f[28] == 3){
	($me,$de,$ye) = $f[27] =~ /(\d*)[^\d](\d*)[^\d](\d*)/;
	$me = sprintf("%.2d",$me);
	$de = sprintf("%.2d",$de);
	$ye = sprintf("%.4d",$ye);
	
	if(timelocal(0,59,23,$de,$me-1,$ye) < timelocal(0,59,23,1,$in{'mymonth'}-1,$in{'myyear'})){
		return;
		}
	}
my($st) = timelocal(0,0,0,$d,$m-1,$y);
if($f[28]==3){
	($ed) = timelocal(0,59,23,$de,$me-1,$ye);
	}
else{
	#do year's worth
	($ed) = timelocal(0,59,23,1,$in{'mymonth'}-1,$in{'myyear'}) + (86400 * 365);
	}
my($nd) = int(($ed - timelocal(0,59,23,$d,$m-1,$y))/86400);
#daily
if($f[30] == 1){
	for(my $i = 0; $i <= $nd; $i+=$f[31]){
		my($mt) = $st + (86400*$i);
		my ($mday,$mon,$year) = (localtime($mt))[3,4,5];
		$mon = sprintf("%.2d",$mon+1);
		$mday = sprintf("%.2d",$mday);
		$year = sprintf("%.4d",$year+1900);
		$nc++;
		if(($f[29])&&($nc > $f[29])){
			next;
			}
		&SetDay($mon,$mday,$year,$line);
		}
	}
#weekly
if($f[30] == 2){
#rewind to sunday
my ($wd) = (localtime($st))[6];
my($rst) = $st;
#$st = $st - ($wd * (86400 - (43200)));
$st = $st - ($wd * 86400);
$st = $st + 43200;
(!$f[32])&&($f[32]=1);
for(my $mt = $st; $mt <= $ed; $mt+=((7*86400)*$f[32])){

my ($mday,$mon,$year,$min,$hour) = (localtime($mt))[3,4,5,1,2];

$mon = sprintf("%.2d",$mon+1);
$mday = sprintf("%.2d",$mday);
$year = sprintf("%.4d",$year+1900);

$min = sprintf("%.2d",$min);
$hour = sprintf("%.2d",$hour);

		$nc++;
		if($f[33]){
			my ($mday,$mon,$year) = (localtime($mt))[3,4,5];
			$mon = sprintf("%.2d",$mon+1);
			$mday = sprintf("%.2d",$mday);
			$year = sprintf("%.4d",$year+1900);
			if(($f[29])&&($nc > $f[29])){
				next;
				}
			if($mt >= $ed){
				next;
				}			
			if($mt >= $rst){
				&SetDay($mon,$mday,$year,$line);
				}
			
			}
		if($f[34]){
			my ($mday,$mon,$year) = (localtime($mt+(86400*1)))[3,4,5];
			$mon = sprintf("%.2d",$mon+1);
			$mday = sprintf("%.2d",$mday);
			$year = sprintf("%.4d",$year+1900);
			if(($f[29])&&($nc > $f[29])){
				next;
				}
			if(($mt+(86400*1)) >= $ed){
				next;
				}
			if(($mt+(86400*1)) >= $rst){
				&SetDay($mon,$mday,$year,$line);
				}
			
			}
		if($f[35]){
			my ($mday,$mon,$year) = (localtime($mt+(86400*2)))[3,4,5];
			$mon = sprintf("%.2d",$mon+1);
			$mday = sprintf("%.2d",$mday);
			$year = sprintf("%.4d",$year+1900);
			if(($f[29])&&($nc > $f[29])){
							next;
							}
			if(($mt+(86400*2)) >= $ed){
				next;
				}
			if(($mt+(86400*2)) >= $rst){
				&SetDay($mon,$mday,$year,$line);
			}
			
			}
		if($f[36]){
			my ($mday,$mon,$year) = (localtime($mt+(86400*3)))[3,4,5];
			$mon = sprintf("%.2d",$mon+1);
			$mday = sprintf("%.2d",$mday);
			$year = sprintf("%.4d",$year+1900);
			if(($f[29])&&($nc > $f[29])){
							next;
							}
			if(($mt+(86400*3)) >= $ed){
				next;
				}
			if(($mt+(86400*3)) >= $rst){
				&SetDay($mon,$mday,$year,$line);
			}
			
			}
		if($f[37]){
			my ($mday,$mon,$year,$hour,$min,$sec) = (localtime($mt+(86400*4)))[3,4,5,2,1,0];
			$mon = sprintf("%.2d",$mon+1);
			$mday = sprintf("%.2d",$mday);
			$year = sprintf("%.4d",$year+1900);
			
			if(($f[29])&&($nc > $f[29])){
							next;
							}
			if(($mt+(86400*4)) >= $ed){
				next;
				}
			if(($mt+(86400*4)) >= $rst){
				&SetDay($mon,$mday,$year,$line);
				}
			
			}
		if($f[38]){
			my ($mday,$mon,$year) = (localtime($mt+(86400*5)))[3,4,5];
			$mon = sprintf("%.2d",$mon+1);
			$mday = sprintf("%.2d",$mday);
			$year = sprintf("%.4d",$year+1900);
			if(($f[29])&&($nc > $f[29])){
							next;
							}
			if(($mt+(86400*5)) >= $ed){
				next;
				}
			if(($mt+(86400*5)) >= $rst){
				&SetDay($mon,$mday,$year,$line);
			}
			
			}
		if($f[39]){
			my ($mday,$mon,$year) = (localtime($mt+(86400*6)))[3,4,5];
			$mon = sprintf("%.2d",$mon+1);
			$mday = sprintf("%.2d",$mday);
			$year = sprintf("%.4d",$year+1900);
			if(($f[29])&&($nc > $f[29])){
							next;
							}
			if(($mt+(86400*6)) >= $ed){
				next;
				}
			if(($mt+(86400*6)) >= $rst){
				&SetDay($mon,$mday,$year,$line);
				}
			
			}
		}
}
#monthly
if($f[30] == 3){

		my($z) = ($in{'myyear'} - $y)+1;
		my($mx) = $m;
		my($my) = $y;
		my($nm);
		if($f[40] == 1){
			$nm = $f[42];
			}
		else{
			$nm = $f[45];
			}
		(!$nm)&&($nm = 1);
		for(my $i=0;$i <= (12*$z); $i++){

			if($mx > 12){
				$mx = $mx - 12;
				$my++;
				}
			$nc++;

			if(($f[29])&&($nc > $f[29])){
				next;
				}
				$mx = sprintf("%.2d",$mx);
					if($f[40] == 1){
						$md = sprintf("%.2d",$f[41]);
						}
					else{
						$md = &GetD($mx,$my,$f[43],$f[44]);
						}
				$my = sprintf("%.4d",$my);
				$md = sprintf("%.2d",$md);
				$mx = sprintf("%.2d",$mx);
				
				&SetDay($mx,$md,$my,$line);
		$mx += $nm;
		}
	
	
}

#yearly
if($f[30] == 4){

	if(($f[29])&&(($in{'myyear'} - $y) > $f[29])){
		return;
		}
	my($wm);
	
	if($f[46] == 1){
		($f[47] eq 'January')&&($wm=1);
		($f[47] eq 'February')&&($wm=2);
		($f[47] eq 'March')&&($wm=3);
		($f[47] eq 'April')&&($wm=4);
		($f[47] eq 'May')&&($wm=5);
		($f[47] eq 'June')&&($wm=6);
		($f[47] eq 'July')&&($wm=7);
		($f[47] eq 'August')&&($wm=8);
		($f[47] eq 'September')&&($wm=9);
		($f[47] eq 'October')&&($wm=10);
		($f[47] eq 'November')&&($wm=11);
		($f[47] eq 'December')&&($wm=12);
		$wd = $f[48];
		}
	else{
		($f[51] eq 'January')&&($wm=1);
		($f[51] eq 'February')&&($wm=2);
		($f[51] eq 'March')&&($wm=3);
		($f[51] eq 'April')&&($wm=4);
		($f[51] eq 'May')&&($wm=5);
		($f[51] eq 'June')&&($wm=6);
		($f[51] eq 'July')&&($wm=7);
		($f[51] eq 'August')&&($wm=8);
		($f[51] eq 'September')&&($wm=9);
		($f[51] eq 'October')&&($wm=10);
		($f[51] eq 'November')&&($wm=11);
		($f[51] eq 'December')&&($wm=12);
		$wd = &GetD($wm,$in{'myyear'},$f[49],$f[50]);
		}
	$in{'myyear'}= sprintf("%.4d",$in{'myyear'});
	$wd = sprintf("%.2d",$wd);
	$wm = sprintf("%.2d",$wm);
	&SetDay($wm,$wd,$in{'myyear'},$line);
}


}

sub GetD{
my($m,$y,$n,$d) = @_;
my(@wd);
my($sm) = timelocal(0,59,23,1,$m-1,$y);
($d eq 'Sunday')&&($dt = 0);
($d eq 'Monday')&&($dt = 1);
($d eq 'Tuesday')&&($dt = 2);
($d eq 'Wednesday')&&($dt = 3);
($d eq 'Thursday')&&($dt = 4);
($d eq 'Friday')&&($dt = 5);
($d eq 'Saturday')&&($dt = 6);
($n eq 'First')&&($dn = 0);
($n eq 'Second')&&($dn = 1);
($n eq 'Third')&&($dn = 2);
($n eq 'Fourth')&&($dn = 3);
for my $z (0..31){
	my(@a) = localtime($sm + (86400 * $z));
	if($a[6] == $dt){
		push(@wd,$a[3]);
		}
	}
return($wd[$dn]);
}

sub SetDay{
my($mon,$mday,$year,$line) = @_;

my($h) = $f[16];
if($f[18] eq 'AM'){
	($h == 12)&&($h=0);
	}
else{
	($h < 12)&&($h+=12);
	}
$h = sprintf("%.2d",$h);
	
if(($mon == $in{'mymonth'})&&($year == $in{'myyear'})){
	$c{$mday.$mon.$year}="bgcolor=\"$eventcolor\"";
	my($when);
	if($f[15] eq 'checked'){
				if($f[19]){
					$when = "<br>$f[16]:$f[17] $f[18] - $f[19]:$f[20] $f[21]";
					}
				else{
					$when = "<br>$f[16]:$f[17] $f[18]";
					}
	}
	
	if(!$f[54]){
		if($f[14]){
			if($in{'pd'} ne '1'){
				$to{$mday.$mon.$year.$h.$f[17].$f[0]} .= "» <a href=\"$in{'cgiurl'}?calid=$f[1]&command=view&t=1&id=$f[0]&m=$mon&d=$mday&y=$year\">$f[3]$when</a><br>";
				}
			else{
				$to{$mday.$mon.$year.$h.$f[17].$f[0]} .= "» <a href=\"javascript:View$in{'rcalid'}('$f[0]-$f[1]','$year','$mon','$mday');\">$f[3]$when</a><br>";
				}
			}
		else{
			$to{$mday.$mon.$year.$h.$f[17].$f[0]} .= "$f[3]$when<br>";
			}
		}
	
	$h{$mday.$mon.$year}='<b>';
	
	
	
	#override if URL exists
	if($f[54]){
		if($f[55] eq 'othertarget'){
			$f[55] = $f[56];
			}
		$to{$mday.$mon.$year.$h.$f[17].$f[0]} .= "» <a href=\"$f[54]\" target=\"$f[55]\">$f[3]$when</a><br>";
	}
}
	
if($in{'viewby'} eq 'month'){
	if(($mon == $in{'mymonth'})&&($year == $in{'myyear'})){
		$order{"$year$mon$mday$h$f[17]$f[0]"} = $line;
		$h{$mday.$mon.$year}='<b>';
		}
	}
	elsif($in{'viewby'} eq 'day'){
		if(($mday == $in{'mday'})&&($mon == $in{'mymonth'})&&($year == $in{'myyear'})){
			$order{"$year$mon$mday$h$f[17]$f[0]"} = $line;
			$h{$mday.$mon.$year}='<b>';
			}
	}
	else{
			$order{"$year$mon$mday$h$f[17]$f[0]"} = $line;
			$h{$mday.$mon.$year}='<b>';
  	}
  	

}

sub GetEvents{
my ($type) = @_;
my(@myrec);
my(@events,$ec);

#highlight today
$m[3] = sprintf("%.2d",$in{'mday'});
$m[4] = sprintf("%.2d",$in{'mymonth'});
$m[5] = sprintf("%.2d",$in{'myyear'});

$c{$m[3].$m[4].$m[5]}=qq|bgcolor="$todaycolor"|;

my(@cids) = split(/\\0/,$in{'calid'});

$in{'rcid'} = $cids[0];

foreach my $i (@cids){
	my $sfile = &CheckSafe("$datapath/$i.cgi");
	open(DB,"<$sfile");
	while(<DB>){
		chomp;
		if($in{'fcalid'}){
			my(@c) = split("\t",$_);
			($c[1] == $in{'fcalid'})&&(push(@events,$_));
			}
		else{
			push(@events,$_);
			}
		}
	close DB;
	}

foreach my $i (@events){
	@f = split("\t",$i);
	$in{'calid'} = $f[1];
	#id	calid	cid	title	c1	c2	c3	c4	c5	c6	c7	c8	c9	c10	body	showtimes	sthour	stmin	stsuf	ethour	etmid	suf	etype	sedate	sdate	edate	srdate	erdate	ed	oc	pattern	pdaily	pweekly	wd0	wd1	wd2	wd3	wd4	wd5	wd5	monthlytype	m1	m2	m3	m4	m5	yearlytype	y1	y2	y3	y4	y5	approve color
	#0	1	2	3	4	5	6	7	8	9	10	11	12	13	14	15		16	17	18	19	20	21	22	23	24	25	26	27	28	29	30	31	32	33	34	35	36	37	38	39	40		41	42	42	44	45	46		47	48	49	50	51	52       53
	($f[52] != 1)&&(next);

	if($in{'filter'}){
		$in{'filter'} =~ s/([\\\|\(\)\[\{\}\^\$\*\+\?\.])/\\$1/g;
		next if ($f[3] !~ /$in{'filter'}/i);
		}
		
	#color event
	if($f[53]){
		$f[3] = qq|<font color="$f[53]">$f[3]</font>|;
	}

	if($f[22] eq 'single'){
		&DoSingle($i);
		}
	elsif($f[22] eq 'multiple'){
		&DoMultiple($i);
		}
	else{
		&DoRecurring($i);
		}

}

#highlight today
$m[3] = sprintf("%.2d",$in{'mday'});
$m[4] = sprintf("%.2d",$in{'mymonth'});
$m[5] = sprintf("%.2d",$in{'myyear'});
	if($c{$m[3].$m[4].$m[5]} =~ /$eventcolor/){
		$c{$m[3].$m[4].$m[5]}=qq|bgcolor="$eventtodaycolor"|;
	}
	else{
		$c{$m[3].$m[4].$m[5]}=qq|bgcolor="$todaycolor"|;
		}
foreach $i (sort keys %order){
	@f = split("\t",$order{$i});

	if($f[53]){
		$f[3] = qq|<font color="$f[53]">$f[3]</font>|;
		}
	($in{'separator'} eq 'Slash')&&($separator = '/');
	($in{'separator'} eq 'Hyphen')&&($separator = '-');
	($in{'separator'} eq 'Period')&&($separator = '.');
	my($y,$m,$d) = $i =~ /^(\d\d\d\d)(\d\d)(\d\d)/;

	if($in{'DateFormat'} eq 'English'){
		$thisdate = "$m$in{'Separator'}$d$in{'Separator'}$y";
		}
	else{
		$thisdate = "$d$in{'Separator'}$m$in{'Separator'}$y";
		}
	if($f[15] eq 'checked'){
				if($f[19]){
					$thisdate .= "<br>$f[16]:$f[17] $f[18] - $f[19]:$f[20] $f[21]";
					}
				else{
					$thisdate .= "<br>$f[16]:$f[17] $f[18]";
					}
			}
	
	if(($f[22] eq 'multiple')){
		if((!$set{$f[0]})&&($f[25])){
			my($sm,$sd,$sy) = $f[24] =~ /(\d*)[^\d](\d*)[^\d](\d*)/;
			my($em,$ed,$ey) = $f[25] =~ /(\d*)[^\d](\d*)[^\d](\d*)/;

			if($f[15] eq 'checked'){
				if(($f[16])&&($f[17])&&($f[18])){
					$timestart= "$f[16]:$f[17] $f[18]";
					}
				if(($f[19])&&($f[20])&&($f[21])){
					$timeend = "$f[19]:$f[20] $f[21]";
					}
				}
				
			$sd = sprintf("%.2d",$sd);
			$sm = sprintf("%.2d",$sm);
			$ed = sprintf("%.2d",$ed);
			$em = sprintf("%.2d",$em);
			
			if($in{'DateFormat'} eq 'English'){
				$thisdate = "$sm$in{'Separator'}$sd$in{'Separator'}$sy $timestart<br>to<br>$em$in{'Separator'}$ed$in{'Separator'}$ey $timeend";
				}
			else{
				$thisdate = "$sd$in{'Separator'}$sm$in{'Separator'}$sy $timestart<br>to<br>$ed$in{'Separator'}$em$in{'Separator'}$ey $timeend";
				}
			$set{$f[0]}=1;
			}
		else{
			next;
			}
		}	
	
	if($in{'command'} eq 'modify'){
	
		if(($d == $in{'mday'})&&($m == $in{'mymonth'})&&($y == $in{'myyear'})){
			if(!$isUser){
				$in{'dline'} .= qq|<tr>
                            			<td class="calendarday" noWrap align="middle"><font size="1">$thisdate</td>
                            			<td class="calendarday"><a class="calendardaylink" href="javascript:Edit('$f[0]');"><font size="1">$f[3]</font></a></td>
                          		</tr>|;
                         	}
                        else{
                        
                        	if((!$umod{$in{'calid'}})&&(!$uconf{'modifythiscatall'})){
                        		$in{'dline'} .= qq|<tr>
			       				<td class="calendarday" noWrap align="middle"><font size="1">$thisdate</td>
			       				<td class="calendarday"><font size="1">$f[3]</font></td>
                          			</tr>|;
                          		}
                        	else{
                        		$in{'dline'} .= qq|<tr>
				            		<td class="calendarday" noWrap align="middle"><font size="1">$thisdate</td>
				            		<td class="calendarday"><a class="calendardaylink" href="javascript:Edit('$f[0]');"><font size="1">$f[3]</font></a></td>
                          				</tr>|;
                        		}
                        	}
			}
	}
			
	if($in{'e'} eq '1'){
		my($ed) = timelocal(0,59,23,$d,$m-1,$y);
		(!$in{'l'})&&($in{'l'} = 1);
		my $future = time + (86400*$in{'l'});

	  	if(($ed <= time)||($ed >= $future)){
	    		next;
    			}
		}
		
	if($in{'n'} > 0){
		my($ed) = timelocal(0,59,23,$d,$m-1,$y);
		my $future = time + (86400*$in{'l'});
		my $time = time;
		if(($ed <= time)||($ec >= $in{'n'})){
			next;		    	
		}
	    	$ec++;	    	
		}
	
	my($link);
	if($f[14]){		
		if($in{'pd'} eq '1'){
			$link = qq|javascript:View$in{'rcalid'}('$f[0]-$f[1]','$y','$m','$d');|;
			}
		else{
			$link = qq|$in{'cgiurl'}?calid=$f[1]&command=view&t=1&id=$f[0]&m=$m&d=$d&y=$y|;
			}
		}
	
	my(@ar,$ef);
	($in{'cs1'})&&(push(@ar,"<td class=\"calendarday\">$f[4]&nbsp;</td>"));
	($in{'cs2'})&&(push(@ar,"<td class=\"calendarday\">$f[5]&nbsp;</td>"));
	($in{'cs3'})&&(push(@ar,"<td class=\"calendarday\">$f[6]&nbsp;</td>"));
	($in{'cs4'})&&(push(@ar,"<td class=\"calendarday\">$f[7]&nbsp;</td>"));
	($in{'cs5'})&&(push(@ar,"<td class=\"calendarday\">$f[8]&nbsp;</td>"));
	($in{'cs6'})&&(push(@ar,"<td class=\"calendarday\">$f[9]&nbsp;</td>"));
	($in{'cs7'})&&(push(@ar,"<td class=\"calendarday\">$f[10]&nbsp;</td>"));
	($in{'cs8'})&&(push(@ar,"<td class=\"calendarday\">$f[11]&nbsp;</td>"));
	($in{'cs9'})&&(push(@ar,"<td class=\"calendarday\">$f[12]&nbsp;</td>"));
	($in{'cs10'})&&(push(@ar,"<td class=\"calendarday\">$f[13]&nbsp;</td>"));
	
	if(@ar){
		$ef = join("\n",@ar);
		}
	my($et);
	
	if($f[14]){
		$et = qq|<a href="$link" class="calendardaylink">$f[3]</a>|;
		}
	else{
		$et = $f[3];
		}
	
	#override if link exists
	if($f[54]){
		if($f[55] eq 'othertarget'){
			$f[55] = $f[56];
			}
		$et = qq|<a href="$f[54]" target="$f[55]" class="calendardaylink">$f[3]</a>|;
		}
		
	$in{'eventline'} .= qq~
                <tr>
                  <td align="center" class="calendarday" nowrap>$thisdate</td>
                  <td class="calendarday">$et</td>
                  $ef
               $manageline
               </tr>
	~;
	
	}

my(@ar,$ef);
($in{'cs1'})&&(push(@ar,"<td class=\"calendarday\"><b>$in{'c1'}&nbsp;</b></td>"));
($in{'cs2'})&&(push(@ar,"<td class=\"calendarday\"><b>$in{'c2'}&nbsp;</b></td>"));
($in{'cs3'})&&(push(@ar,"<td class=\"calendarday\"><b>$in{'c3'}&nbsp;</b></td>"));
($in{'cs4'})&&(push(@ar,"<td class=\"calendarday\"><b>$in{'c4'}&nbsp;</b></td>"));
($in{'cs5'})&&(push(@ar,"<td class=\"calendarday\"><b>$in{'c5'}&nbsp;</b></td>"));
($in{'cs6'})&&(push(@ar,"<td class=\"calendarday\"><b>$in{'c6'}&nbsp;</b></td>"));
($in{'cs7'})&&(push(@ar,"<td class=\"calendarday\"><b>$in{'c7'}&nbsp;</b></td>"));
($in{'cs8'})&&(push(@ar,"<td class=\"calendarday\"><b>$in{'c8'}&nbsp;</b></td>"));
($in{'cs9'})&&(push(@ar,"<td class=\"calendarday\"><b>$in{'c9'}&nbsp;</b></td>"));
($in{'cs10'})&&(push(@ar,"<td class=\"calendarday\"><b>$in{'c10'}&nbsp;</b></td>"));

$in{'cols'} = $#ar+3;

if(@ar){
	$in{'ef'} = join("\n",@ar);
	}

#do large calendar
foreach my $i (sort keys %to){
	my($d,$m,$y) = $i =~ /^(..)(..)(....)/;
	if($t{$d.$m.$y}){
		$t{$d.$m.$y} .= '<hr size=1>'.$to{$i};
		}
	else{
		$t{$d.$m.$y} .= $to{$i};
		}
	}

}

sub CreateCalendar{
$in{'calendarsmall'} = qq|
<table cellspacing="0" cellpadding="3" border="1" bordercolor="#000000" style="border-collapse: collapse" width="100%">
                <tr align="middle">
                  <td width="14.28%"><font class="calendarday"><b>$DoW[$fmday[0]]</b></font></td>
                  <td width="14.28%"><font class="calendarday"><b>$DoW[$fmday[1]]</b></font></td>
                  <td width="14.28%"><font class="calendarday"><b>$DoW[$fmday[2]]</b></font></td>
                  <td width="14.28%"><font class="calendarday"><b>$DoW[$fmday[3]]</b></font></td>
                  <td width="14.28%"><font class="calendarday"><b>$DoW[$fmday[4]]</b></font></td>
                  <td width="14.28%"><font class="calendarday"><b>$DoW[$fmday[5]]</b></font></td>
                  <td width="14.28%"><font class="calendarday"><b>$DoW[$fmday[6]]</b></font></td>
                </tr>
|;

$in{'calendarlarge'} = qq|
<table cellspacing="0" cellpadding="3" border="1" bordercolor="#000000" style="border-collapse: collapse" width="100%">
                <tr align="middle">
                  <td width="14.28%" align=left><font class="calendarday"><b>$DoW[$fmday[0]]</b></font></td>
                  <td width="14.28%" align=left><font class="calendarday"><b>$DoW[$fmday[1]]</b></font></td>
                  <td width="14.28%" align=left><font class="calendarday"><b>$DoW[$fmday[2]]</b></font></td>
                  <td width="14.28%" align=left><font class="calendarday"><b>$DoW[$fmday[3]]</b></font></td>
                  <td width="14.28%" align=left><font class="calendarday"><b>$DoW[$fmday[4]]</b></font></td>
                  <td width="14.28%" align=left><font class="calendarday"><b>$DoW[$fmday[5]]</b></font></td>
                  <td width="14.28%" align=left><font class="calendarday"><b>$DoW[$fmday[6]]</b></font></td>
                </tr>
|;

my $day;
my $cday;

if($in{'command'} ne 'viewlarge'){
for $h (0..6){
$in{'calendarsmall'} .= qq|<tr align="middle">\n|;
  for $v (0..6){
    $day++;
    $offday = $day - $fdayoffset;
    (($offday <= $dim)&&($offday > 0))?($cday = $offday):($cday = '');
    ($offday > $dim)&&($te = 1);
    $today = sprintf("%.2d",$cday).sprintf("%.2d",$in{'mymonth'}).sprintf("%.4d",$in{'myyear'});
    if($cday){
    $in{'calendarsmall'} .= qq|<td valign=top height="28" width="14.28%" $c{$today} align=left class="calendarday"><a href="javascript:ChangeDay$in{'rcalid'}('$cday');" class="calendardaylink">$h{$today}$cday</b></a></td>\n|;
    }
    else{
    $in{'calendarsmall'} .= qq|<td valign=top height="28" width="14.28%">&nbsp</td>\n|;
    }
    }
$in{'calendarsmall'} .= qq|</tr>\n|;
($te)&&(last);
}
$in{'calendarsmall'} .= qq|</table>|;
}
else{
for $h (0..6){
$in{'calendarlarge'} .= qq|<tr align="middle">\n|;
  for $v (0..6){
    $day++;
    $offday = $day - $fdayoffset;
    (($offday <= $dim)&&($offday > 0))?($cday = $offday):($cday = '');
    ($offday > $dim)&&($te = 1);
    $today = sprintf("%.2d",$cday).sprintf("%.2d",$in{'mymonth'}).sprintf("%.4d",$in{'myyear'});
    if($cday){
    $in{'calendarlarge'} .= qq|<td width="14.28%" $c{$today} align=left valign=top height="75" class="calendarday">$h{$today}$cday<br>$t{$today}</td>\n|;
    }
    else{
    $in{'calendarlarge'} .= qq|<td width="14.28%" height="75">&nbsp</td>\n|;
    }
    }
$in{'calendarlarge'} .= qq|</tr>\n|;
($te)&&(last);
}
$in{'calendarlarge'} .= qq|</table>|;
}
}

sub GetDateInfo{
my ($time) = @_;
my $tmp = $in{'mymonth'};
$time = $time + (3600 * $timeoffset);

&ctime($time);

$bom = timelocal(0,0,0,1,$in{'mymonth'}-1,$in{'myyear'});

@info = localtime($bom);
$fdayoffset = $info[6]-$in{'wstart'};

if($fdayoffset < 0){
	$fdayoffset += 7;
	}

for $i ((0+$in{'wstart'})..(6+$in{'wstart'})){
  $didx = $fday + $i;
  ($didx > 6)&&($didx = $didx - 7);
  $fmday[$i-$in{'wstart'}] = $didx;
  }

for $i (0..32){
  @info = localtime($bom + (86400 * $i));
    if($info[4] != ($in{'mymonth'}-1)){
      last;
      }
  $dim = $info[3];
  }


}


sub PageOutJS{
local($file) = @_;
my $sfile = &CheckSafe("$file");
open(OUT,"$sfile")||print "$!: $file<br>";
while(<OUT>){
$o = $_;
$o =~ s/in\((\w+)\)/$in{$1}/g;
$o =~ s/\"/\\"/g;
$o =~ s/\\n/\\\\n/g;
$o =~ s/(scr)(ipt)/$1\"\+\"$2/gsi;
@mylines = split(/\r*\n/,$o);
    
    foreach $q (@mylines){
      print qq|document.write("$q\\n");\n|;
      }

}
close OUT;
}

sub GetLogin{
    &GetCookies;
    $in{'UserName'} = $cookie{'UserName'};
    $in{'PassWord'} = $cookie{'PassWord'};
    # if no password, then output the login screen    
    if(!$in{'UserName'}){
    	(!$in{'command'})&&($in{'command'} = 'manage');
        &PageOut("$cgipath/t_login.htm");
        exit;
    }
    
    if(($^O =~ /win/i)){
        	if(($in{'UserName'} eq $username)&&($in{'PassWord'} eq $password)){
        			#good to go.
        			$in{'atype'} = 'admin';
        			return 1;
        	}
        }
        else{
        	if(($in{'UserName'} eq $username)&&(crypt($in{'PassWord'},'CS') eq $password)){
    			#good to go.
    			$in{'atype'} = 'admin';
    			return 1;
        	}               
    }
    # password failed
        if(&CheckUserLoginNew){
        	return 1;
    		}
    &PError("Error. Invalid username or password");
}

sub Login{
$in{'command'} = 'manage';
&PageOut("$cgipath/t_login.htm");
exit;
}

sub SaveSetup{
(-e "$basepath/setup.cgi")&&(&PError("Error. Access Denied"));
($ENV{'REQUEST_METHOD'} !~ /post/i)&&(&PError("Error. Access Denied"));
(!$in{'cgipath'})&&(&PError("Error. Please enter a cgipath variable"));
(!$in{'cgiurl'})&&(&PError("Error. Please enter a cgiurl variable"));
(!$in{'datapath'})&&(&PError("Error. Please enter a datapath variable"));
(!$in{'imageurl'})&&(&PError("Error. Please enter an imageurl variable"));
(!$in{'sendmail'})&&(&PError("Error. Please enter the path to sendmail"));
(!$in{'username'})&&(&PError("Error. Please enter a username"));
(!$in{'username'})&&(&PError("Error. Please enter a username"));
(!$in{'password'})&&(&PError("Error. Please enter a password"));
my $sfile = &CheckSafe("$basepath/setup.cgi");

if($^O !~ /win/i){
	    	$in{'password'} = crypt($in{'password'},'CS');
	    	}
	    	
open(SETUP,">$sfile");
print SETUP <<"EOF";
\$cgipath = '$in{'cgipath'}';
\$cgiurl = '$in{'cgiurl'}';
\$datapath = '$in{'datapath'}';
\$imageurl = '$in{'imageurl'}';
\$sendmail = '$in{'sendmail'}';
\$memail = '$in{'memail'}';
\$username = '$in{'username'}';
\$password = '$in{'password'}';
1;
EOF
close SETUP;
print <<"EOF";
<script language=javascript>
alert("Setup.cgi reconfigured");
window.location = "$scriptname?command=login";
</script>
EOF
exit;
}

sub Setup{
use Cwd;
$in{'cgipath'} = Cwd::cwd();
$in{'cgiurl'} = "$ENV{'HTTP_HOST'}/$ENV{'SCRIPT_NAME'}";
$in{'cgiurl'} =~ s/\/\//\//g;
$in{'cgiurl'} = "http://".$in{'cgiurl'};
$in{'cgiurl'} =~ s/\/csCalendar\.cgi//i;
$in{'datapath'} = $in{'cgipath'}.'/data';
$in{'imageurl'} = $in{'cgiurl'}.'/images';
$in{'sendmail'} = '/usr/sbin/sendmail';
$in{'memail'} = 'you@yourdomain.com';
$in{'username'} = 'demo';
$in{'password'} = 'demo';
$in{'scriptname'} = $scriptname;
&PageOut("$basepath/t_setup.htm");
exit;
}

sub CheckSafe{
my ($file) = @_;
($file =~ /\.\./)&&(&PError("Error. Invalid filename"));
($file =~ /\|/)&&(&PError("Error. Invalid filename"));
return $file;
}

sub PageOut{
my ($file) = @_;
if($in{'js'} == 1){
	&PageOutJS($file);
	}
open(OUT,"$file")||print "$!: $file<br>";
while(<OUT>){
$_ =~ s/in\((\w+)\)/$in{$1}/g;
print;
}
close OUT;
}


sub DataOutJS{
my($data) = @_;
$data =~ s/\r//g;
$data =~ s/\"/\\"/g;
$data =~ s/\\n/\\\\n/g;
$data =~ s/(scr)(ipt)/$1\"\+\"$2/gsi;
my @mylines = split(/\r*\n/,$data);
    
    foreach my $q (@mylines){
      print qq|document.write("$q\\n");\n|;
      }

exit;
}

sub PageOutJS{
my($file) = @_;
open(OUT,"$file")||print "$!: $file<br>";
while(<OUT>){
my $o = $_;
$o =~ s/\r//g;
$o =~ s/in\((\w+)\)/$in{$1}/g;
$o =~ s/\"/\\"/g;
$o =~ s/\\n/\\\\n/g;
$o =~ s/(scr)(ipt)/$1\"\+\"$2/gsi;
my @mylines = split(/\r*\n/,$o);
    
    foreach my $q (@mylines){
      print qq|document.write("$q\\n");\n|;
      }

}
close OUT;
exit;
}

sub CheckVars{
##check for long lines
$in{'title'} =~ s/(\S{80,81})/$1 /g;
$in{'body'} =~ s/(\S{100,101})/$1 /g;

$in{'cv1'} =~ s/(\S{80,81})/$1 /g;
$in{'cv2'} =~ s/(\S{80,81})/$1 /g;
$in{'cv3'} =~ s/(\S{80,81})/$1 /g;
$in{'cv4'} =~ s/(\S{80,81})/$1 /g;
$in{'cv5'} =~ s/(\S{80,81})/$1 /g;
$in{'cv6'} =~ s/(\S{80,81})/$1 /g;
$in{'cv7'} =~ s/(\S{80,81})/$1 /g;
$in{'cv8'} =~ s/(\S{80,81})/$1 /g;
$in{'cv9'} =~ s/(\S{80,81})/$1 /g;
$in{'cv10'} =~ s/(\S{80,81})/$1 /g;
##dhtml
if($in{'command'} eq 'submitforapproval'){
	$in{'title'} =~ s/\<.*?\>//gs;
	$in{'body'} =~ s/\<.*?\>//gs;
	$in{'cv1'} =~ s/\<.*?\>//gs;
	$in{'cv2'} =~ s/\<.*?\>//gs;
	$in{'cv3'} =~ s/\<.*?\>//gs;
	$in{'cv4'} =~ s/\<.*?\>//gs;
	$in{'cv5'} =~ s/\<.*?\>//gs;
	$in{'cv6'} =~ s/\<.*?\>//gs;
	$in{'cv7'} =~ s/\<.*?\>//gs;
	$in{'cv8'} =~ s/\<.*?\>//gs;
	$in{'cv9'} =~ s/\<.*?\>//gs;
	$in{'cv10'} =~ s/\<.*?\>//gs;
	($in{'requireapproval'})&&(!$in{'email'})&&(&PError("Please enter your email address"));
	}

$in{'title'} =~ s/&#(\d+);/pack("c",$1)/ge;
$in{'body'} =~ s/&#(\d+);/pack("c",$1)/ge;
$in{'cv1'} =~ s/&#(\d+);/pack("c",$1)/ge;
$in{'cv2'} =~ s/&#(\d+);/pack("c",$1)/ge;
$in{'cv3'} =~ s/&#(\d+);/pack("c",$1)/ge;
$in{'cv4'} =~ s/&#(\d+);/pack("c",$1)/ge;
$in{'cv5'} =~ s/&#(\d+);/pack("c",$1)/ge;
$in{'cv6'} =~ s/&#(\d+);/pack("c",$1)/ge;
$in{'cv7'} =~ s/&#(\d+);/pack("c",$1)/ge;
$in{'cv8'} =~ s/&#(\d+);/pack("c",$1)/ge;
$in{'cv9'} =~ s/&#(\d+);/pack("c",$1)/ge;
$in{'cv10'} =~ s/&#(\d+);/pack("c",$1)/ge;

	
$in{'title'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
$in{'body'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
$in{'body'} =~ s/\r*\n/\\n/g;
$in{'c1'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
$in{'c2'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
$in{'c3'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
$in{'c4'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
$in{'c5'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
$in{'c6'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
$in{'c7'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
$in{'c8'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
$in{'c9'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;
$in{'c10'} =~ s/([^\w\s\n])/'&#'.ord($1).';'/ge;



(!$in{'title'})&&(&PError("Error. Please enter a title"));

if($in{'showtimes'}){
	(!$in{'sthour'})&&(!$in{'stmin'})&&(!$in{'stsuf'})&&(&PError("Please enter a start time"));
	(!$in{'ethour'})&&(!$in{'etmin'})&&(!$in{'etsuf'})&&(&PError("Please enter an end time"));
	}

if($in{'etype'} eq 'single'){
	(!$in{'sedate'})&&(&PError("Please enter a date for this event"));
	($in{'sedate'} !~ /[\d]{1,2}\-[\d]{1,2}\-[\d]{4}/)&&(&PError("Invalid event date format. Must be MM-DD-YYYY"));
	}
	
if($in{'etype'} eq 'multiple'){
	(!$in{'sdate'})&&(&PError("Please enter a start date for this event"));
	($in{'sdate'} !~ /[\d]{1,2}\-[\d]{1,2}\-[\d]{4}/)&&(&PError("Invalid start date format. Must be MM-DD-YYYY"));
	(!$in{'edate'})&&(&PError("Please enter an end date for this event"));
	($in{'edate'} !~ /[\d]{1,2}\-[\d]{1,2}\-[\d]{4}/)&&(&PError("Invalid end date format. Must be MM-DD-YYYY"));
	}

if($in{'etype'} eq 'recurring'){
	(!$in{'srdate'})&&(&PError("Please enter a start date"));
	
	if($in{'ed'} eq '1'){
		$in{'oc'} = '';
		$in{'erdate'} = '';
	}
	
	if($in{'ed'} eq '2'){
		(!$in{'oc'})&&(&PError("Please enter the number of occurrences for this event"));
		$in{'erdate'} = '';
	}
	
	if($in{'ed'} eq '3'){
		(!$in{'erdate'})&&(&PError("Please an end date for this event"));
		($in{'erdate'} !~ /[\d]{1,2}\-[\d]{1,2}\-[\d]{4}/)&&(&PError("Invalid end date format. Must be MM-DD-YYYY"));
		$in{'oc'} = '';
	}
	
	if($in{'pattern'} eq '1'){
		(!$in{'pdaily'})&&(&PError("Please enter the number of days for this event"));
		}
	
	if($in{'pattern'} eq '2'){
		(!$in{'pweekly'})&&(&PError("Please enter the number of weeks for this event"));
		(!$in{'wd0'})&&(!$in{'wd1'})&&(!$in{'wd2'})&&(!$in{'wd3'})&&(!$in{'wd4'})&&(!$in{'wd5'})&&(!$in{'wd6'})&&(&PError("Please select at least one weekday for this event"));
		}
		
	if(($in{'pattern'} eq '3')&&($in{'monthlytype'} eq '1')){
		(!$in{'m1'})&&(&PError("Please the day for this event"));
		(!$in{'m2'})&&(&PError("Please the number of months for this event"));
		}
		
	if(($in{'pattern'} eq '3')&&($in{'monthlytype'} eq '2')){
		(!$in{'m3'})&&(&PError("Please select the day for this event"));
		(!$in{'m4'})&&(&PError("Please select the day for this event"));
		(!$in{'m5'})&&(&PError("Please select the number of months for this event"));
		}
		
		
	if(($in{'pattern'} eq '4')&&($in{'yearlytype'} eq '1')){
		(!$in{'y1'})&&(&PError("Please the month for this event"));
		(!$in{'y2'})&&(&PError("Please the year for this event"));
		}
		
	if(($in{'pattern'} eq '4')&&($in{'yearlytype'} eq '2')){
		(!$in{'y3'})&&(&PError("Please the day for this event"));
		(!$in{'y4'})&&(&PError("Please the month for this event"));
		(!$in{'y5'})&&(&PError("Please the year for this event"));
		}
	
	}

($in{'color'})&&($in{'color'} =~ /[^#0-9A-Za-z]/)&&(&PError("Error. Invalid color specification"));
return;
}

