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

$|=1;
print "Content-type: text/html\n";
#####################################################################
# base_dir set outside of cgi-bin so that suexec can be used.
#####################################################################
$base_dir = "/homed/globalta/calendar/";

#####################################################################
# get common config file
#####################################################################
require('gtcommon.cfg');

#####################################################################
# Main line code  (should be at the top to find it easier)
#####################################################################

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

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

if( defined $ENV{'HTTP_COOKIE'})
{ # aaron put shopping loginid and password into cookie named after store.
  my($zcookie);
  foreach $zcookie (split(/; /,$ENV{'HTTP_COOKIE'}))
  { ($vars{cookie1},$vars{cookie2}) = split(/=/,$zcookie,2);
    ($vars{cookiename},$vars{cookievalue}) = split(/\|/, $vars{cookie2},2);	
    if ($vars{cookie1} eq 'gtlogin')
    { if ($vars{cookiename} ne '')
      { $in{'strEmail'} = $vars{cookiename};        # jxl
        $in{'strPassword'} = $vars{cookievalue};    # jxl
        $in{password}=crypt($gtuv{$in{'strPassword'}},time);
        $vars{loadcookie} = 1;
        if ($in{"ACTION"} ne "logout")
        { print ("\n");
        }
      }
    }                                                         # jxl
  }                                                           # jxl
}                                                             # jxl

#####################################################################
#
# Decide what to do based on the ACTION parameter
#
#####################################################################
if ($in{"ACTION"} eq 'member_login')
{ if ($in{travelcookie} eq "1" && $vars{loadcookie} == 1)
  { &member_login($in{login});		
  }
  elsif ($vars{loadcookie} == 1 || $in{travelcookie} eq '2')
  { &member_login($in{login});		
  }
  else
  { print ("\n");
    &calendar_error_msg('','mytravel_login_html'); 
  }
}
elsif ($in{"ACTION"} eq "member_add")
{ #print("\n");
  &member_add;
}
else
{ if ($in{"ACTION"} eq "logout")
  { &logout;
  }
  print ("\n");
  if ($in{"ACTION"} eq "VIEWDAY")
  { &VIEWDAY;
  }
  elsif ($in{"ACTION"} eq "DO_ADD")
  { &DO_ADD;
  }
elsif ($in{"ACTION"} eq "edit_event")
        { &edit_event;
        }
elsif ($in{"ACTION"} eq "add_event") # by Aaron
        { &add_event;
        }
elsif ($in{"ACTION"} eq "goto_service") # by Aaron
        { &goto_service($in{service}); 
	}
elsif ($in{"ACTION"} eq "goto_service_1") # by Aaron
        { &goto_service_1; 
	}
elsif ($in{"ACTION"} eq 'search_visitor') # by Aaron
        {   &goto_page('calendar_visitorsearch.html'); #Aaron
        }
elsif ($in{"ACTION"} eq "3way") # by Aaron
        {   &goto_page('3way.html'); #Aaron
        }
elsif ($in{"ACTION"} eq "um") # by Aaron
        { &member_login('um'); 
#	&goto_page('um.html');
        }
elsif ($in{"ACTION"} eq "travel") # by Aaron
        { &front_page;
        }
elsif ($in{"ACTION"} eq "member_update")
        { &member_update;
        }
elsif ($in{"ACTION"} eq "member_search")
        { &member_search;
        }
elsif ($in{"ACTION"} eq "pctophone")
        { &pctophone;
        }
elsif ($in{"ACTION"} eq "gotopage")
        { &goto_page("$in{page}");
        }
elsif ($in{"ACTION"} eq "add_phone_page")
        { 
	if ($in{flag} eq 'B') {
		&goto_page("add_phonebook2.html");
		}
	else {         
		&goto_page("add_phonebook.html");
		}
	}
elsif ($in{"ACTION"} eq "add_phone")#Aaron
        { &add_phone;
        }
elsif ($in{"ACTION"} eq "create_phonebook")#Aaron   
        { &create_phonebook;
        }
elsif ($in{"ACTION"} eq "destination")#Aaron
        { &display_destination_services;
        }
elsif ($in{"ACTION"} eq "import")#Aaron
        { &upload_outlook_files;
        }
else {
#	print "ACTION = '$in{ACTION}'";
	&DISPLAY;
	}
}
exit(0);
#####################################################################
# Routine to get working directory
#####################################################################
sub GetCwd {
	if ($base_dir) { $vars{base_dir} = $base_dir; }
	return if $vars{base_dir};
	my $path =  $ENV{'PATH_TRANSLATED'} || $ENV{'SCRIPT_FILENAME'};
	unless ($path) {
		&Error("Your server does not provide the PATH_TRANSLATED or SCRIPT_FILENAME environment variables.<br><br>Please see the installation documentation for how to set the \$base_dir variable manually.");
		exit(0);
		}
	$path =~ s|[^/\\]*$||;
	$vars{base_dir} = $path;
	}
#####################################################################
# Routine to get language template directory
#   calendar-us.pl
#   calendar-big5.pl
#   calendar-kanji.pl
#####################################################################
sub GetLang
{ my($zpgm);

  $zpgm = $0;                              # get program name
  $zpgm =~ s/(\.pl)//;                     # remove program type
  $zpgm =~ s!^(.*/)!!;                     # remove path info
  $vars{pgm}=$zpgm;                        # just the program name
  ($zbase,$vars{lang})=split(/-/,$vars{pgm},2); # language
  $vars{pgm_name}="$vars{pgm}.pl";
  $vars{cfg_name}="$vars{pgm}.cfg";
  if($vars{lang} eq '')
  { $vars{templatedir}='templates';
  }
  else
  { $vars{templatedir}="templates-$vars{lang}";
  }
}
#####################################################################
#
# Parse input
#
#####################################################################
sub ReadParse {
 local (*in) = @_ if @_; 
 local ($i, $loc, $key, $val);
 if ($ENV{'REQUEST_METHOD'} eq "GET") { $in = $ENV{'QUERY_STRING'};} 
 elsif ($ENV{'REQUEST_METHOD'} eq "POST")
      {read(STDIN,$in,$ENV{'CONTENT_LENGTH'});}
if ($in =~ /^-----/i) { #For Form Upload
print ("\n");
 @in = split(/-----/g,$in);
 foreach $i (0 .. $#in) {
  $in[$i] =~ s/\+/ /g;
    ($junk1, $key1, $junk2,$val) = split(/\n/,$in[$i],4);
        if ($key1 =~ /filename/si) {	
	    ($junk1, $key, $junk2, $val,$junk3) = split(/"/,$in[$i],5);
		$junk3 =~  s/Content-Type: application\/octet\-stream+//g;  #Clear Header for IE
		$junk3 =~  s/Content-Type: application\/x\-unknown\-content\-type\-Excel\.CSV+//g; #Clear Header for Netscape
	        $junk3 =~ s|[\r\n]+||s;
               $vars{upload_content} = $junk3;
	}
	else {
    		($junk1, $key, $junk2) = split(/"/,$key1,3);
	}

  $key =~ s/%(..)/pack("c",hex($1))/ge;
  $val =~ s/%(..)/pack("c",hex($1))/ge;

  $val =~ s/^\s+//g;               # remove leading spaces
  $val =~ s/\s+$//g;               # remove trailing spaces
  $val =~ s|[\r\n]+||gs;
  $in{$key} .= "\0" if (defined($in{$key}));
  $in{$key} .= $val;
  } 
}
else {
 @in = split(/&/,$in);
 foreach $i (0 .. $#in)
 { $in[$i] =~ s/\+/ /g;    ($key, $val) = split(/=/,$in[$i],2);
   $key =~ s/%(..)/pack("c",hex($1))/ge;
   $val =~ s/%(..)/pack("c",hex($1))/ge;
   $val =~ s/^ +//g;
   $val =~ s/ +$//g;
   $val =~ s/  +/ /g;
   $in{$key} .= "\0" if (defined($in{$key})); 
   $in{$key} .= $val;  
 }  
}
 return 1; 
 }


#####################################################################
# Print out a small calendar
# Linked month name to view month's calendar
#####################################################################
sub small_calendar {
	my $month = shift;
	my $year = shift;

	my $month_name = $months[$month-1];

	&PerpetualCalendar($month,1,$year);
	$start_day = $perp_dow;
	$days_in_month = $perp_eom;

	$curr_day = 0;
	my $return = <<"END";
<TABLE BORDER=1 CELLPADDING=0 cellspacing=0 BGCOLOR=white>
	<TR><TD COLSPAN=7 VALIGN=TOP ALIGN=CENTER><font size=1><a href=\"$vars{cgi}?Month=$month&Year=$year&config=$vars{config}\">${month_name}&nbsp;$year</a></font></TD></TR>
END
	foreach $date (1-$start_day .. $days_in_month) {
		if ($curr_day == 0) { $return .= "<TR>"; }
		if ($date > 0) {
			$return .= "<TD VALIGN=TOP><font size=1>$date</font></TD>";
			}
		else {
			$return .= "<TD></TD>";
			}
		$curr_day++;
		if ($curr_day == 7) {
			$return .= "</TR>\n";
			$curr_day=0;
			}
		}
	$return .= "</TABLE>\n";
	return $return;
	} #end of small_calendar


#####################################################################
# Print out a small calendar
# Linked dates to view date's details
#####################################################################
sub small_calendar2 {
	my $month = shift;
	my $year = shift;
	my $current_date = shift;
        my $loginid = shift;
        my $eventkey = shift;
        my $member_login = shift;
        my $firstname = shift;
	my $month_name = $months[$month-1];
	my $bgcolor;
	
	&PerpetualCalendar($month,1,$year);
	$start_day = $perp_dow;
	$days_in_month = $perp_eom;

	$curr_day = 0;
	my $return = <<"END";
<TABLE BORDER=1 CELLPADDING=0 cellspacing=0 BGCOLOR=white>
	<TR><TD COLSPAN=7 VALIGN=TOP ALIGN=CENTER><font size=1>${month_name}&nbsp;$year</font></TD></TR>
END
	foreach $date (1-$start_day .. $days_in_month) {
		if ($curr_day == 0) { $return .= "<TR>"; }
		if ($date == $current_date) { $bgcolor=" BGCOLOR=ffda8c "; }
			else { $bgcolor = ""; }
		
		if ($date > 0) {
                  if($member_login eq 'y')
		{ $return .= "<TD VALIGN=TOP $bgcolor><font size=1><a href=\"$vars{cgi}?ACTION=VIEWDAY&Year=$year&Month=$month&Date=$date&config=$vars{config}&loginid=$loginid&eventkey=$eventkey&member_login=$member_login&firstname=$firstname\">$date</a></font></TD>";
                }
                else
                { $return .= "<TD VALIGN=TOP $bgcolor><font size=1><a href=\"$vars{cgi}?ACTION=VIEWDAY&Year=$year&Month=$month&Date=$date&config=$vars{config}&loginid=$loginid&eventkey=$eventkey&firstname=$firstname\">$date</a></font></TD>";
                }
			}
		else {
			$return .= "<TD></TD>";
			}
		$curr_day++;
		if ($curr_day == 7) {
			$return .= "</TR>\n";
			$curr_day=0;
			}
		}
	$return .= "</TABLE>\n";
	return $return;
	} #end of small_calendar2


#####################################################################
#
# Read in config file
#
#####################################################################
sub read_config {
	my $config_file;
	if ($in{config}) {
		$vars{config} = $in{config};
		unless ($vars{config} =~ m|^/|) {
			$config_file = $vars{base_dir} . $vars{config};
			}
		else {
			$config_file = $vars{config};
			}
		}
	else {
		$vars{config} = "calendar-$vars{lang}.cfg";
		$config_file = $vars{base_dir} . $vars{config};
		}
	my $key,$val;
	open(IN,$config_file) || &Error("Can't open config file $config_file.");
	while(<IN>) {
		next if /^#/;
		chomp;
		($key,$val) = ( /([^=]+)=(.*)/ );
		$key = lc($key);
		$val =~ s|\[(\S+)\]|$vars{$1}|g;
		$val =~ s|\s*$||;
		$vars{$key} = $val;
		}
	close(IN);
	
	@months = split(',',$vars{months});
	($vars{month1},$vars{month2},$vars{month3},$vars{month4},$vars{month5},$vars{month6},$vars{month7},$vars{month8},$vars{month9},$vars{month10},$vars{month11},$vars{month12} ) = @months;

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

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

	}


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

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

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


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


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

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

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

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

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

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

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


	# Pass back parsed template
	return $template;
	
	}

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

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

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

	return $template;
	}

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


#####################################################################
#
# DISPLAY()
#
# Display the calendar
#
#####################################################################
sub DISPLAY {
	if($vars{loginid} eq '')
        { $vars{loginid}=$in{loginid};
        }
	if($vars{firstname} eq '')   #Aaron
        { $vars{firstname}=$in{firstname};
        }
	if($vars{member_login} eq '')
        { $vars{member_login}=$in{member_login};
        }
	#$vars{password}=$in{password};
	if($vars{password} eq '')
	{$vars{password}=$in{strPassword};
	}
	&read_cal_data;

	# Get next and last months
	# ------------------------
	$vars{lastyear}  = $vars{year};
	$vars{nextyear}  = $vars{year};
	$vars{lastmonth} = $vars{month}-1;
	$vars{nextmonth} = $vars{month}+1;
	if ($vars{lastmonth} < 1) { $vars{lastmonth}=12; $vars{lastyear}--; }
	if ($vars{nextmonth} > 12){ $vars{nextmonth}=1;  $vars{nextyear}++; }

	$vars{lastmonth_calendar} = &small_calendar( $vars{lastmonth} , $vars{lastyear} );
	$vars{nextmonth_calendar} = &small_calendar( $vars{nextmonth} , $vars{nextyear} );

	$vars{nextmonth_name} = $months[$vars{nextmonth} - 1];
	$vars{lastmonth_name} = $months[$vars{lastmonth} - 1];
	
	$vars{nextmonth_link} = "$vars{cgi}?config=$vars{config}&Year=$vars{nextyear}&Month=$vars{nextmonth}";
	$vars{lastmonth_link} = "$vars{cgi}?config=$vars{config}&Year=$vars{lastyear}&Month=$vars{lastmonth}";

	&PerpetualCalendar(int($vars{'month'}),1,int($vars{'year'}));

	# Last/Next month button
	# --------------------------
	$vars{'select_last_month'} = "<a href='$vars{cgi}?config=$vars{config}&loginid=$vars{loginid}&firstname=$vars{firstname}&password=$vars{password}&eventkey=$vars{eventkey}&member_login=$vars{member_login}&Month=$vars{lastmonth}&Year=$vars{lastyear}'>";
	$vars{'select_last_month'} .= "<img src='/\%7Eglobalta/Latin1/lastmonth.gif' border=0>";
#	$vars{'select_last_month'} .= "last";
	$vars{'select_last_month'} .= "</a>";
	$vars{'select_next_month'} = "<a href='$vars{cgi}?config=$vars{config}&loginid=$vars{loginid}&firstname=$vars{firstname}&password=$vars{password}&eventkey=$vars{eventkey}&member_login=$vars{member_login}&Month=$vars{nextmonth}&Year=$vars{nextyear}'>";
	$vars{'select_next_month'} .= "<img src='/\%7Eglobalta/Latin1/nextmonth.gif' border=0>";
#	$vars{'select_next_month'} .= "next";
	$vars{'select_next_month'} .= "</a>";


	# Generate select box of months
	# -----------------------------
	$month_selected{$vars{month}} = " SELECTED ";
	$year_selected{$vars{year}} = " SELECTED ";
	$vars{'select_month_form'} = "<form action='$vars{cgi}' method=post>\n";
	$vars{'select_month_form'}.= "<input type='hidden' name='config' value='$vars{config}'>\n";
	$vars{'select_month_form'}.= "<input type='hidden' name='loginid' value='$vars{loginid}'>\n";
	$vars{'select_month_form'}.= "<input type='hidden' name='firstname' value='$vars{firstname}'>\n";
	$vars{'select_month_form'}.= "<input type='hidden' name='lastname' value='$vars{lastname}'>\n";
	$vars{'select_month_form'}.= "<input type='hidden' name='password' value='$vars{password}'>\n";
	$vars{'select_month_form'}.= "<input type='hidden' name='eventkey' value='$vars{eventkey}'>\n";
	$vars{'select_month_form'}.= "<input type='hidden' name='member_login' value='$vars{member_login}'>\n";
        $vars{'select_month_form'}.= "<select name='Month' size=1>\n";
	foreach $i (1 .. 12) {
		$temp = "month" . $i;
		$vars{'select_month_form'} .= "<option value='$i' $month_selected{$i}>$vars{$temp}</option>";
		}
	$vars{'select_month_form'} .= "</select><select name='Year' size=1>";
	foreach ($vars{current_year}-1 .. $vars{year}+2) {
		$vars{'select_month_form'} .= "<option value='$_' $year_selected{$_}>$_\n";
		}
	$vars{select_month_form} .= '</select><input type="submit" CLASS="button" value="Go"></form>';

	# Load the template and do the replace
	# ------------------------------------
	$template = &load_template("$vars{calendar_html}");

	# Insert data for each day
	# ------------------------
	# $day_format = template for each separate day
	# $output     = full text of all days to insert into calendar template
	# $tmp_day    = temp variable to hold day's template each time thru
	# 
	
	my ($day_format) = ($template =~ m|<%OUTPUT DAY%>(.+)<%/OUTPUT%>|si);
	my ($output) = "<TR>";
	if ($perp_dow > 0) { $output .= "<TD COLSPAN=$perp_dow >&nbsp;</TD>"; }
	foreach $current_day (1..$perp_eom) {
		my ($tmp_day) = $day_format;
		$vars{current_day} = $current_day;
		$xdatestamp = sprintf("%4.4d%2.2d%2.2d",$vars{year},$vars{month},$vars{current_day});

		# display entries for this date
		$vars{'viewday'} = "javascript:viewday($vars{year},$vars{month},$vars{current_day});";
			
		# define background color		
		if (($vars{year} == $year) && ($vars{month} == $month) && ($vars{current_day} == $mday)) {
			$vars{bgcolor} = $vars{bgcolor_today};
			}
		elsif ( $vars{current_day} == $vars{date} ) {
			$vars{bgcolor} = $vars{bgcolor_current};
			}
		else { $vars{bgcolor} = $vars{bgcolor_day}; }

		# Parse custom event display format
		# ---------------------------------
		# $event_format  = Format of each event's output
		# $events_output = Full text for all events to be inserted
		# $ event_tmp      = temp copy of format for each event
		if ($tmp_day =~ /<%OUTPUT EVENTS%>/si) {
			my ($event_format) = ($tmp_day =~ m|<%OUTPUT EVENTS%>(.+?)<%/OUTPUT EVENTS%>|si);
			my ($events_output) = "";
			foreach $i ( sort keys %{$events{$xdatestamp}} ) {
				my ($event_tmp) = $event_format;
				$event_tmp =~ s|<%=label%>|$events{$xdatestamp}{$i}{label}|sig;
				$event_tmp =~ s|<%=description%>|$events{$xdatestamp}{$i}{description}|sig;
				$events_output .= $event_tmp;
				}
			if ($total_events{$xdatestamp} < 2) {
				$events_output .= "<br>&nbsp;" x (2-$total_events{$xdatestamp});
				}
			$tmp_day =~ s|<%OUTPUT EVENTS%>(.+?)<%/OUTPUT EVENTS%>|$events_output|si;
			}
			 
		# define event_labels
		$vars{event_labels} = "";
		foreach $i ( sort keys %{$events{$xdatestamp}} ) {
# jxl-events		$vars{event_labels} .= "$events{$xdatestamp}{$i}{label}<br>\n";
			$vars{event_labels} .= "$events{$xdatestamp}{$i}{label} <font color=\"red\">$events{$xdatestamp}{$i}{eventkey}</font><br>\n";
			}
		$vars{event_labels} .= "&nbsp;\n";
		if ($total_events{$xdatestamp} < 2) {
			$vars{event_labels} .= "<br>&nbsp;" x (2-$total_events{$xdatestamp});
			}

		$output .= &parse_template( $tmp_day , \%vars );

		$perp_sofar++; $perp_togo -= 1;
		$weekday = ($vars{current_day}+$perp_dow)-(int(($vars{current_day}+$perp_dow)/7)*7);
		if (($weekday == 0) && !($vars{current_day} == $perp_eom)) {
			$output .=  "\n</TR><TR>\n";
		}
	}
	if ($weekday > 0) {
		$leftover = 7-$weekday;
		$output .=  "<TD COLSPAN=$leftover ><P>&nbsp;</TD>";
	}

	# Put the generated output back into the template
	$template =~ s|<%OUTPUT DAY%>(.+?)<%/OUTPUT%>|$output|si;

	# Put in the rest of the variables
	# --------------------------------
	$template = &parse_template($template, \%vars);
	
	# Remove special comments from template
	# -------------------------------------
	$template =~ s|<!--#.*?#-->\r?\n?||sig;
	
	$template =~ s|</body>|<BR>\n</body>|si;
	print $template;
	exit;
	} #end of DISPLAY
#####################################################################
#
# display_date()
#
# Display the date schedule
#
#####################################################################
sub display_date {
	if($vars{loginid} eq '')
        { $vars{loginid}=$in{loginid};
        }
	if($vars{firstname} eq '')   #Aaron
        { $vars{firstname}=$in{firstname};
        }
	if($vars{member_login} eq '')
        { $vars{member_login}=$in{member_login};
        }
	if($vars{password} eq '')
	{$vars{password}=$in{strPassword};
	}
	&read_cal_data;

	$vars{small_calendar} = &small_calendar2( $vars{month} , $vars{year} , $vars{date} , $in{loginid} , $in{eventkey} ,$in{member_login} ,$in{firstname});
	
	&PerpetualCalendar(int($vars{'month'}),1,int($vars{'year'}));

	$vars{current_day} = $current_day;
	$xdatestamp = sprintf("%4.4d%2.2d%2.2d",$vars{year},$vars{month},$vars{current_day});

	# Load the template and do the replace
	# ------------------------------------
	$template = &load_template("$vars{viewday_html}");
			$output = "<table width=80%>";
	for ($xii=0; $xii<=23; $xii++) {
              $output .= "<tr><td><font face=Arial size=2>$xii \: 00</font></td>";
	  $output .= "<td>";
	  foreach $i (sort key %{$events{$xdatestamp}} ) {
	     if ($events{$xdatestamp}{$i}{sdatestamp} == $xdatestamp || ($events{$xdatestamp}{$i}{edatestamp} ne '' && $events{$xdatestamp}{$total_events{$xdatestamp}}{edatestamp} >= $xdatestamp && $events{$xdatestamp}{$i}{sdatestamp} <= $xdatestamp)) { 
                  if ($events{$xdatestamp}{$i}{stime} <= $zii && $events{$xdatestamp}{$i}{etime} >= $zii) {
                    $output .= "$events{$xdatestamp}{$i}{heading} - $events{$xdatestamp}{$i}{description}";
                    }
                  }
              }		
	  $output .= "</td></tr>";
	}
            $output .= "</table>";

	# Put the generated output back into the template
#	$template =~ s|<%OUTPUT DAY%>(.+?)<%/OUTPUT%>|$output|si;

	$vars{output} = $output;

	# Put in the rest of the variables
	# --------------------------------
	$template = &parse_template($template, \%vars);
	
	# Remove special comments from template
	# -------------------------------------
	$template =~ s|<!--#.*?#-->\r?\n?||sig;
	
	$template =~ s|</body>|<BR>\n</body>|si;
	print $template;
	exit;
	} #end of DISPLAY
#####################################################################
#
# DO_ADD()
#
# Add an entry
#
#####################################################################
sub DO_ADD {	
	my($zmsg);
	&read_cal_data;
	$zmsg='';
        if($in{Month} < 1 || $in{Month} > 12)
        { $zmsg.="<li><b>Month</b> must be from 1 to 12.\n";
        }
        if($in{Date} < 1 || $in{Date} > 31)
        { $zmsg.="<li><b>Month</b> must be from 1 to 31.\n";
        }
        if($in{Year} < 2000 || $in{Year} > 2999)
        { $zmsg.="<li><b>Year</b> must be greater than 2000 and less than 3000.\n";
        }
#	if($in{sMonth} < 1 || $in{sMonth} > 12 ||$in{eMonth} < 1 || $in{eMonth} > 12)
#        { $zmsg.="<li><b>Month</b> must be from 1 to 12.\n";
#        }
#	if($in{sDate} < 1 || $in{sDate} > 31 || $in{eDate} < 1 || $in{eDate} > 31)
#        { $zmsg.="<li><b>Month</b> must be from 1 to 31.\n";
#        }
#	if($in{sYear} < 2000 || $in{sYear} > 2999 || $in{eYear} < 2000 || $in{eYear} > 2999)
#        { $zmsg.="<li><b>Year</b> must be greater than 2000 and less than 3000.\n";
#        }
	if($in{heading} eq '')
        { $zmsg.="<li><b>Heading</b> is required.\n";
        }
	if($in{description} eq '')
        { $zmsg.="<li><b>Description</b> is required.\n";
        }
	$in{description} =~ s|[\r\n]+|<BR>|gs;
	$sMonth = $in{sMonth};
	$in{Month} =~ s|^(\d)$|0$1|;
	$in{Date}  =~ s|^(\d)$|0$1|;
        $in{sMonth} =~ s|^(\d)$|0$1|;
        $in{sDate}  =~ s|^(\d)$|0$1|;
        $in{eMonth} =~ s|^(\d)$|0$1|;
        $in{eDate}  =~ s|^(\d)$|0$1|;
	my $datestamp = $in{Year} . $in{Month} . $in{Date};
        my $sdatestamp = $in{sYear} . $in{sMonth} . $in{sDate};
        my $edatestamp = $in{eYear} . $in{eMonth} . $in{eDate};
	if($in{Edit_Option} eq 'Update')
        { &edit_update_delete('Update',$zmsg);
          exit(0);
        }
	if($in{Edit_Option} eq 'Delete')
        { &edit_update_delete('Delete',$zmsg);
          exit(0);
        }
	if($in{Edit_Option} eq 'New')
        { &edit_new($zmsg);
          exit(0);
        }
        if($zmsg ne '')
        { $zmsg="<ul>\n".$zmsg."</ul>\n";
          &calendar_error_msg($zmsg,'calendar_error_html');
          exit(0);
        }
	if ($datestamp =~ /^\d\d\d\d\d\d\d\d$/) {
		open(OUT,">> $vars{calendar_file}") || &Error("Can't open $calendar_file for writing!");
		eval "flock OUT,2";
# jxl event data
		print OUT "$vars{new_id}|$in{loginid}|$in{eventkey}|$in{phonenum}|$datestamp|$in{heading}|$in{description}|$in{Dur_time}|$in{Dur_unit}|$in{sHour}|$in{eHour}|$edatestamp\n";  #Aaron
		close(OUT);
		}
	else { &Error("error"); }	
#	
#	print <<"END";
#<HTML>
#<BODY>
#Your entry has been added. You may now <A HREF="$vars{cgi}?config=$vars{config}\&Month=$Month\&Year=$in{Year}">Return to the calendar</A>.
#</BODY>
#</HTML>
#END
  $vars{loginid}   =$in{loginid};
  $vars{password}   =$in{password};
  $vars{firstname} =$in{firstname};
  $vars{lastname}  =$in{lastname};
	&DISPLAY;
	exit(0);
	} #end of ADD


#####################################################################
#
# VIEWDAY()
#
# Display entries for a single day
#
#####################################################################
sub VIEWDAY {
	&read_cal_data;
	if($vars{firstname} eq '')   #Aaron
        { $vars{firstname}=$in{firstname};
        }
	if($vars{loginid} eq '')   #Aaron
        { $vars{loginid}=$in{loginid};
        }
	$vars{password} = $in{password};
	$vars{small_calendar} = &small_calendar2( $vars{month} , $vars{year} , $vars{date} , $in{loginid} , $in{eventkey} ,$in{member_login} ,$in{firstname});
	
	&PerpetualCalendar(int($vars{'month'}),1,int($vars{'year'}));

	# Load the template and do the replace
	# ------------------------------------
	$template = &load_template("$vars{viewday_html}");

	$template = &parse_output( "EVENTS" , $template , \%{$events{$vars{datestamp}}} );
	$template = &parse_template($template, \%vars);

	print $template;
	exit;
	} # end of VIEWDAY


#####################################################################
#
# Initialize variables
#
#####################################################################
sub INITIALIZE {
	my ($x,$i,$zneg_pos,$zhours);
        my ($ztime);

	# Current date and stuff

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


#####################################################################
#
# Read in calendar data file
#
#####################################################################
sub read_cal_data {
	undef %events;
	my $id, $xdatestamp, $zloginid, $zeventkey, $zphonenum, $xmonth, $zjunk, $zetime, $zstime, $zedatestamp;
	$vars{new_id}=0;
	open(IN,"$vars{calendar_file}") || &Error("Can't open $vars{calendar_file}");
	my $header = <IN>;
	# If file isnt in right format, give error
	unless ($header =~ m/^#id\|loginid\|eventkey\|phonenum\|datestamp\|label\|description/) { #Aaron
		close(IN);
		print "The events file is not in the correct format for this version. Run the calendar_admin script to automatically update the format.";
		exit(0);
		}

	while (<IN>) {
		chomp;
		next unless /^\d/;
# jxl event data
		($id,$zloginid,$zeventkey,$zphonenum,$xdatestamp,$label,$desc,$durtime,$durunit,$zstime,$zetime,$zedatestamp,$zjunk) = split(/\|/,$_,10); #Aaron
		$xdatestamp =~ s|^0000|$vars{year}|;

		if ($id > $vars{new_id}) { $vars{new_id} = $id; }
		
		# Skip it unless it's from the current month
		($xmonth = $vars{month}) =~ s|^(\d)$|0$1|;
#		next unless ($xdatestamp =~ m|^$vars{year}$xmonth|);
                if($in{member_login} ne 'y')
                { next unless ($zeventkey eq '*'         # public events
                         || ($zloginid eq $in{loginid}   # matching login id
                         && ($zeventkey eq ''            # no event key
                          || $zeventkey eq $in{eventkey} # matching event key
                            )));
                }
                else
 		{ next unless ($zloginid eq $in{loginid} # matching login id
#                          || $zeventkey eq '*'  # public events
                          || crypt($in{loginid},$vars{username}) eq $vars{username}); # administrator login id
                }
		if ($vars{html_heading} ne "yes") {
			$label =~ s|[<>]||g;
			}
		if ($vars{html_description} ne "yes") {
			$desc =~ s|[<>]||g;
			}
		
		$total_events{$xdatestamp}++;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{edatestamp} = $zedatestamp;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{sdatestamp} = $zsdatestamp;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{etime} = $etime;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{stime} = $stime;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{description} = $desc;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{label} = $label;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{member_login} = $in{member_login};
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{phonenum} = $zphonenum;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{eventkey} = $zeventkey;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{loginid} = $zloginid;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{id} = $id;

		}
	close(IN);
	$vars{new_id}++;
	}
#####################################################################
#
# Output a calendar error message
#
#####################################################################
sub calendar_error_msg
{ my($xmsg,$xtemplate)=@_;
  my($ztemplate);
  $vars{error_msg}=$xmsg;
  $ztemplate = &load_template("$vars{$xtemplate}");
  $ztemplate = &parse_template($ztemplate, \%vars);
  print $ztemplate;
  exit;
}
#####################################################################
#
# Output a viewday error message
#
#####################################################################
sub viewday_error_msg
{ my($xmsg)=@_;
  my($ztemplate);
  $vars{error_msg}=$xmsg;
  $ztemplate = &load_template("$vars{viewday_error_html}");
  $ztemplate = &parse_template($ztemplate, \%vars);
  print $ztemplate;
  exit;
}
#####################################################################
#
# Edit Event
#
#####################################################################
sub edit_event
{ my $zid, $xsdatestamp, $zloginid, $zeventkey, $zphonenum, $xmonth, $zjunk;
  my(@zcalendar_file,$zline,$zmsg);
  my($zdesc,$zlabel,$zdurtime,$zdurunit,$zetime,$zstime,$xedatestamp); #Aaron
  my($ztemplate);

  open(IN,"<$vars{calendar_file}") || &Error("Can't open $vars{calendar_file} for read by Edit Event");
  my $header = <IN>;
  # If file isnt in right format, give error
  unless ($header =~ m/^#id\|loginid\|eventkey\|phonenum\|datestamp\|label\|description|\durtime|\durunit/) #Aaron
  { close(IN);
    print "The events file is not in the correct format for this version. Run the calendar_admin script to automatically update the format.";
    exit(0);
  }
  @zcalendar_file=<IN>;
  close(IN);
  $zmsg='';
  foreach $zline (@zcalendar_file)
  { next unless ($zline =~ /^\d/);
    ($zid,$zloginid,$zeventkey,$zphonenum,$xdatestamp,$zlabel,$zdesc,$zdurtime,$zdurunit,$zstime,$zetime,$xedatestamp,$zjunk) = split(/\|/,$zline,13); #Aaron
    if($zid == $in{id})
    { $zmsg='ok';
      last;
    }
  }
  if($zmsg ne 'ok')
  { $zmsg="<li>Event not found.  Please reload/refresh your web browser views.";
    $vars{error_msg}='<font color="red"><b>Errors:</b><br>'.$zmsg.'</font>';
  }
  $zdesc =~ s|<br>|\n|ig;
  $vars{id}       =$zid;
  $vars{loginid}  =$zloginid;
  $vars{eventkey} =$zeventkey;
  $vars{phonenum} =$zphonenum;
  $vars{xdatestamp}=$xdatestamp;
  $vars{label}     =$zlabel;
  $vars{desc}      =$zdesc;
  $vars{durtime}      =$zdurtime;  #aaron
  $vars{durunit}      =$zdurunit; #Aaron
  $vars{durunit} =~ s/\n+//;
  $vars{syear} = $year;
  $vars{sdate} = 1;
  $vars{sHour} = $zstime;
  $vars{eHour} = $zetime;
$vars{syear} = substr($xsdatestamp,0,4);
$vars{smonth} = substr($xsdatestamp,4,2);
$vars{sdate} = substr($xsdatestamp,6);	
$vars{eyear} = substr($xedatestamp,0,4); 
$vars{emonth} = substr($xedatestamp,4,2);
$vars{edate} = substr($xedatestamp,6);  
 $vars{'month_form'} = "<select name=Month>\n"; #Aaron
 $zii = 0; #Aaron
  for($zii=1; $zii<=12; $zii++) {
	if ($zii eq $vars{month}) {
		$vars{'month_form'}.= "<option value=$zii selected>$shortmonths[$zii-1]\n";
	}
	else {
		$vars{'month_form'}.= "<option value=$zii>$shortmonths[$zii-1]\n";
	}
}
 $vars{'month_form'} .= "</select>\n"; #Aaron
$vars{'smonth_form'} = "<select name=sMonth>\n"; #Aaron
 $zii = 0; #Aaron
  for($zii=1; $zii<=12; $zii++) {
        if ($zii == $vars{smonth}) {
                $vars{'smonth_form'}.= "<option value=$zii selected>$shortmonths[$zii-1]\n";
        }
        else {
                $vars{'smonth_form'}.= "<option value=$zii>$shortmonths[$zii-1]\n";
        }
}
 $vars{'smonth_form'} .= "</select>\n"; #Aaron
$vars{'emonth_form'} = "<select name=eMonth>\n"; #Aaron
 $zii = 0; #Aaron
  for($zii=1; $zii<=12; $zii++) {
        if ($zii == $vars{emonth}) {
                $vars{'emonth_form'}.= "<option value=$zii selected>$shortmonths[$zii-1]\n";
        }
        else {
                $vars{'emonth_form'}.= "<option value=$zii>$shortmonths[$zii-1]\n";
        }
}
 $vars{'emonth_form'} .= "</select>\n"; #Aaron
$vars{'shour_form'} = "<select name=sHour>\n"; #Aaron
  for($zii=0; $zii<=23; $zii++) {
        if ($zii == $vars{sHour}) {
                $vars{'shour_form'}.= "<option value=$zii selected>$zii:00\n";
        }
        else {
                $vars{'shour_form'}.= "<option value=$zii>$zii:00\n";
        }
}
 $vars{'shour_form'} .= "</select>\n"; #Aaron
$vars{'ehour_form'} = "<select name=eHour>\n"; #Aaron
  for($zii=0; $zii<=23; $zii++) {
        if ($zii == $vars{eHour}) {
                $vars{'ehour_form'}.= "<option value=$zii selected>$zii:00\n";
        }
        else {
                $vars{'ehour_form'}.= "<option value=$zii>$zii:00\n";
        }
}
 $vars{'ehour_form'} .= "</select>\n"; #Aaron
$vars{'durunit_form'} = "<select name=Dur_unit>\n"; #Aaron
	if ($vars{durunit} eq 'hours') {
		$vars{'durunit_form'}.= "<option value=\"hours\" selected>Hours\n";
		$vars{'durunit_form'}.= "<option value=\"days\">Days\n";
	}
	else {
		$vars{'durunit_form'}.= "<option value=\"hours\">Hours\n";
		$vars{'durunit_form'}.= "<option value=\"days\" selected>Days\n";
	}
 $vars{'durunit_form'} .= "</select>\n"; #Aaron

  $vars{member_login}=$in{member_login};
  $vars{firstname}=$in{firstname};
 $vars{password}=$in{password};
  $ztemplate = &load_template("$vars{edit_event_html}");
  $ztemplate = &parse_template($ztemplate, \%vars);
  print $ztemplate;
  exit(0);
}
#####################################################################
#
# Edit new event
#
#####################################################################
sub edit_new
{ my($zmsg)=@_;
  my($template);
  my $datestamp = $in{Year} . $in{Month} . $in{Date};
  if($zmsg eq '')
  { if ($datestamp =~ /^\d\d\d\d\d\d\d\d$/) {
		open(OUT,">> $vars{calendar_file}") || &Error("Can't open $calendar_file for writing!");
		eval "flock OUT,2";
# jxl event data
		print OUT "$vars{new_id}|$in{loginid}|$in{eventkey}|$in{phonenum}|$datestamp|$in{heading}|$in{description}|$in{Dur_time}|$in{Dur_unit}\n"; #Aaron
		close(OUT);
		}
	else { &Error("error"); }
    &VIEWDAY;
  }
  else
  { $vars{error_msg}='<font color="red"><b>Errors:</b><br>'.$zmsg.'</font>';
    &edit_event;
  }
  exit(0);
}
#####################################################################
#
# Edit update or delete event
#
#####################################################################
sub edit_update_delete
{ my($zopr,$zmsg)=@_;
  my $id, $xdatestamp, $zloginid, $zeventkey, $zphonenum, $xmonth, $zjunk;
  my(@zcaldata,$zline); 
  my($template);

  if($zmsg eq '')
  { open(CALLK,">$vars{calendar_lock}")
     || &Error("Can't lock the $vars{calendar_lock} file by edit update/delete!");
    eval "flock CALLK,2";
    if(-e "$vars{calendar_file}")
    { if(!open(CALFN,"<$vars{calendar_file}"))
      { close(CALLK);
        &Error("Can't open $vars{calendar_file} file for read by edit update/delete!");
        exit;
      }
      @zcaldata=<CALFN>;
      close(CALFN);
      if(!open(CALFN,">$vars{calendar_file}-tmp"))
      { close(CALLK);
        &Error("Can't open $vars{calendar_file}-tmp file for write by edit update/delete!");
      }
      foreach $zline (@zcaldata)
      { ($id,$zloginid,$zeventkey,$zphonenum,$xdatestamp,$label,$desc,$durtime,$durunit,$zjunk) = split(/\|/,$zline,10); #Aaron
        if($id == $in{id})
        { if($zopr eq 'Update')
          { $in{description} =~ s|[\r\n]+|<BR>|gs;
            print CALFN "$id|$zloginid|$in{eventkey}|$in{phonenum}|$xdatestamp|$in{heading}|$in{description}|$in{Dur_time}|$in{Dur_unit}\n"; #Aaron
          }
          $zmsg='ok';
        }
        else
        { print CALFN $zline;
        }
      }
      close(CALFN);
      if($zmsg ne 'ok')
      { $zmsg="<li>Event not found.  Please reload/refresh your web browser views.";
        $vars{error_msg}='<font color="red"><b>Errors:</b><br>'.$zmsg.'</font>';
      }
      else
      { # rename
        rename "$vars{calendar_file}-tmp","$vars{calendar_file}";
      }
    }
    else
    { $zmsg="<li>$vars{calendar_file} does not exist for edit update/delete. Please reload/refresh your web browser views.";
    }
    close(CALLK);
  }
  if($zmsg eq '' || $zmsg eq 'ok')
  { &VIEWDAY;
  }
  else
  { $vars{error_msg}='<font color="red"><b>Errors:</b><br>'.$zmsg.'</font>';
    &edit_event;
  }
  exit(0);
}
#####################################################################
#
# PC to Phone
#
#####################################################################
sub pctophone
{
  my($template);
  $vars{phonenum}=$in{phonenum};
  $vars{loginid}=$in{loginid};
  $template = &load_template("$vars{pctophone_html}");
  $template = &parse_template($template, \%vars);
  print $template;
  exit;
}
#####################################################################
#
# Get member data and put it into the %gtuv hash
# return code 0 is match with just the loginid.
#
# NOTE: the calling routine has to unlock the member_lock.
#       this is done to handle the "member add/update" condition.
#
#####################################################################
sub member_get
{ my($xloginid)=@_;
# my($zmemgrp);
  my($ztmp,$zrec,$zkey,$zii);
  my($zcityphone,$zcity,$zphone);

# $zmemgrp=substr($xloginid,0,3);

  ###################################################################
  # lock and read the member db
  ###################################################################
  open(MEMLK,">$vars{member_lock}")
   || &Error("Can't lock $vars{member_lock} file!");
  eval "flock MEMLK,2";
  if(-e "$vars{member_file}")
  { if(!open(MEMFN,"<$vars{member_file}"))
    { close(MEMLK);
      &Error("Can't open $vars{member_file} file for read!");
      exit;
    }
    @memdata=<MEMFN>;
    close(MEMFN);
  }
  else
  { @memdata=();
  }
  ###################################################################
  # search for the userid
  ###################################################################
  foreach $zrec (sort @memdata)
  { $ztmp=$zrec;
    chomp($tmp);
    #################################################################
    # put member data into gtuv hash
    #################################################################
    foreach $zkey (@gtMemDB)
    { ($gtuv{$zkey},$ztmp)=split(/\|/,$ztmp,2);
    }
    #################################################################
    # match with requested userid
    #################################################################
    if($gtuv{u_userid} eq $xloginid)
    {
      ###############################################################
      # ensure that city/phone are clear
      ###############################################################
      $zii=0;
      for($zii=1; $zii<=9; $zii++)
      { $gtuv{"u_loccity$zii"}='';
        $gtuv{"u_locphone$zii"}='';
      }
      ###############################################################
      # process city/phone
      ###############################################################
      $zii=0;
      $ztmp=$gtuv{u_loc};
      while($ztmp ne '')
      { $zii++;
        ($zcityphone,$ztmp)=split(/:/,$ztmp,2);
        ($zcity,$zphone,$zjunk)=split(/\#/,$zcityphone,3);
        $zkey="u_loccity$zii";
        $gtuv{$zkey}=$zcity;
        $zkey="u_locphone$zii";
        $gtuv{$zkey}=$zphone;
      }
      $gtuv{u_loccity}=$gtuv{u_loccity1};
      $gtuv{u_locphone}=$gtuv{u_locphone1};
      return(0);
    }
  }
  return(1);                            # not found
}
#####################################################################
#
# Add a member
#
#####################################################################
sub member_add
{ my($zmsg,$zmem);
  my($zemail,$zpassword,$zfirstname,$zlastname,$zloc,$zjunk);
  my($zfield,$ztmp,$zkeyuv,$zkeyin,$zkeyvar);

  ###################################################################
  # check arguments
  ###################################################################
  if($in{strFirstName} eq '' || $in{strFirstName} =~ /[^0-9a-zA-Z-. ]/)
  { $zmsg .= "<li>Member first name is required and can only contain alphanumeric characters and - and ..\n";
  }
  if($in{strLastName} eq '' || $in{strLastName} =~ /[^0-9a-zA-Z-. ]/)
  { $zmsg .= "<li>Member last name is required and can only contain alphanumeric characters and - and ..\n";
  }
  if($in{strEmail} eq '' || $in{strEmail} =~ /[^.-\@0-9a-zA-Z]/)
  { $zmsg .= "<li>Member email address (login id) is required and must be in a valid email format.\n";
  }
  if($in{strPassword} eq '' ||$in{strPassword} =~ /[^,.#-:\[\]';0-9a-zA-Z ]/
   ||length($in{strPassword}) < 5
   ||$in{strPassword} eq $in{strEmail})
  { $zmsg .= "<li>Member password is required and cannot contain some special characters and must be at least 5 characters long and cannot be the same as your email address (login id).\n";
  }
  if($in{strPwdConfirm} ne $in{strPassword})
  { $zmsg .= "<li>Member password, <b>$in{strPassword}</b>, does not match confirmation password, <b>$in{strPwdConfirm}</b>.\n";
  }
  if($in{strLocCity} eq '' || $in{strLocCity} =~ /[^0-9a-zA-Z-. ,]/)
  { $zmsg .= "<li>Where you are is required and can only contain alphanumeric characters and - and . and ,.\n";
  }
  $in{strLocPhone} =~ s/ +//g;            # remove spaces
  $in{strLocPhone} =~ s/-+//g;            # remove dashes
  $in{strLocPhone} =~ s/\(+//;           # remove left parenthesis
  $in{strLocPhone} =~ s/\)+//;           # remove right parenthesis
  if($in{strLocPhone} ne '' && $in{strLocPhone} =~ /[^0-9- ]/)
  { $zmsg .= "<li>Phone number can only contain digits 0-9.\n";
  }
  if($in{strAccount} ne 'basic')
  { if($in{strStreet}  eq ''
     ||$in{strCity}    eq ''
     ||$in{strCountry} eq '')
    { $zmsg.="<li>Street, City, and Country must be entered for VIP accounts.\n";
    }
    if($in{strCCType} eq ''
     ||$in{strCCNum}  eq ''
     ||$in{strCCExp}  eq ''
     ||$in{strCCName} eq '')
    { $zmsg.="<li>Credit card information must be entered for VIP accounts.\n";
    }
  }
  if($in{strLocPhone} ne ''
   &&$in{strLocCity} eq '')
  { $zmsg .= "<li>A City must be entered if you entered a Phone Number.\n";
  }
  ###################################################################
  # check if userid already used
  ###################################################################
  $zret=&member_get($in{strEmail});
  if($zret == 0)
  { close(MEMLK);
    $zmsg .= "<li>Email address (login id), <b>$in{strEmail}</b>, is already in use.\n";
  }
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  { print ("\n");
    &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  ###################################################################
  # put data into gtuv, in, and vars
  ###################################################################
  foreach $zfield (@gtMemCal)
  { $ztmp=$zfield;
    ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
    $vars{$zkeyvar}=$in{$zkeyin};
    $gtuv{$zkeyuv}=$in{$zkeyin};
  }
  if($in{strLocCity} ne '')
  { $gtuv{u_loc}="$in{strLocCity}#$in{strLocPhone}";
  }
  else
  { $gtuv{u_loc} = '';
  }
  ###################################################################
  # encrypt passwd that is displayed on web pages
  ###################################################################
  $vars{strPassword}=crypt($gtuv{u_passwd},time);
  $vars{password}=$vars{strPassword};
  ###################################################################
  # create new member string
  ###################################################################
  $zmemstr='';
  foreach $zkeyuv (@gtMemDB)
  { $zmemstr .= "|$gtuv{$zkeyuv}";
  }
  $zmemstr=substr($zmemstr,1);
  ###################################################################
  # add new member to in-storage array
  ###################################################################
  push(@memdata,"$zmemstr\n");
  @memdata=sort(@memdata);
  ###################################################################
  # output the new member file to a temp file
  ###################################################################
  if(!open(MEMFN,">$vars{member_file}-tmp"))
  { close(MEMLK);
	print ("\n"); #Aaron
    &Error("Can't open $vars{member_file}-tmp file for write!");
  }
  print MEMFN @memdata;
  close(MEMFN);
  ###################################################################
  # rename the file to the main member file name
  ###################################################################
  rename "$vars{member_file}-tmp","$vars{member_file}";
  close(MEMLK);
  &create_phonebook; #Aaron
  $in{loginid} = $in{strEmail};
  $in{password} = $vars{password};
      $vars{sc_cookie}="Set-Cookie:gtlogin=$in{strEmail}|$in{strPassword};path=/\n";        # Aaron
    $vars{loadcookie} = 1;
      print ("$vars{sc_cookie}\n\n");
  &DISPLAY;
}
#####################################################################
#
# Member login
#
#####################################################################
sub member_login
{ my($xopr)=@_;
  my(@zmemdata,$zmem,$zmsg);
  my($zloginid,$zpassword,$zfirstname,$zlastname,$zloc,$zjunk);
  my($zret,$ztmp,$zfield,$zkeyuv,$zkeyin,$zkeyvar);

  $zmsg='';
  ###################################################################
  # check arguments
  ###################################################################
  if($in{strEmail} eq '' || $in{strPassword} eq '')
  { $zmsg="A <b>login id</b> and <b>Password</b> must be entered!\n";
  }
  ###################################################################
  # check if userid and passwd match an existing user
  ###################################################################
  else
  { $zret=&member_get($in{strEmail});
    if($zret == 1)
    { close(MEMLK);
      $zmsg .= "<li>Email address (login id), <b>$in{strEmail}</b>, not found in our database.\n";
    }
    else
    { if($xopr eq 'Login'
       ||$xopr eq 'Update'
       ||$xopr eq 'Phonebook'        ||$xopr eq 'Phonebook1' #Aaron
       ||$xopr eq 'Main' )
      { if(crypt($gtuv{u_passwd},$in{strPassword}) ne $in{strPassword} && $gtuv{u_passwd} ne $in{strPassword})
        { close(MEMLK);
          $zmsg.="<li>Email address, (login id), <b>$in{strEmail}</b> and password not found in our database.\n";
        }
      }
      elsif($gtuv{u_passwd} ne $in{strPassword})
      { close(MEMLK);
        $zmsg .= "<li>Email address (login id), <b>$in{strEmail}</b>, and password, <b>$in{strPassword}</b>, not found in our database.\n";
      }
    }
  }
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  {     print ("\n"); #Aaron
	&calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  ###################################################################
  # extract logged in user values
  ###################################################################
  close(MEMLK);
  foreach $zfield (@gtMemCal)
  { $ztmp=$zfield;
    ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
    $vars{$zkeyvar}=$gtuv{$zkeyuv};
  }
  $vars{member_login}='y';
  $in{member_login}='y';
  $in{loginid}    =$in{strEmail};
  if ($vars{loadcookie} == 0 && $xopr eq 'Login') { #Aaron
      $vars{sc_cookie}="Set-Cookie:gtlogin=$in{strEmail}|$gtuv{u_passwd};path=/\n";        # Aaron
    $vars{loadcookie} = 1;
      print ("$vars{sc_cookie}");
    #print ("\n");
}
print ("\n");
  ###################################################################
  # encrypt passwd that is displayed on web pages
  ###################################################################
  $vars{strPassword}=crypt($gtuv{u_passwd},time);
  $vars{password}=$vars{strPassword}; 
  #$in{password}=$vars{password};
  ###################################################################
  # display the calendar for login or update form for update
  ###################################################################
  if($xopr eq 'Login')
  {   &DISPLAY;
  }
  if($xopr eq 'Update')
	  { 
  	$vars{strInfo} =~ s/\n+//;            # remove spaces
	print ("\n");
	&calendar_error_msg('','member_update_html');
  }
  if($xopr eq 'Phonebook')
	  { &calendar_error_msg('','phonebook_html'); #by Aaron
  }
  if($xopr eq 'Phonebook1')
	  { &display_phone_book($in{level}); #by Aaron
  }
  if($xopr eq 'um')
          {
	&calendar_error_msg('','um_html');
#       &goto_page('um.html'); #by Aaron
  }
  else
  	  {
#  &calendar_error_msg('','mytravel_html'); #by Aaron
	&DISPLAY; 
 }
}
#####################################################################
#
# Member update
#
#####################################################################
sub member_update
{ my(@zmemdata,$zmem,$zmsg);
  my($zloginid,$zpassword,$zfirstname,$zlastname,$zloc,$zjunk);
  my(@zmemupdi,$zmemval);
  my($zcityphone,$zcity,$zphone);

  $zmsg='';
  ###################################################################
  # check new passwd
  ###################################################################
  if($in{strPassword1} ne '' || $in{strPwdConfirm1} ne '')
  { if($in{strPassword1} ne $in{strPwdConfirm1})
    { $zmsg .= "<li>New Password, <b>'$in{strPassword1}'</b>, must equal Confirm New Password, <b>'$in{strPwdConfirm1}'</b>.\n";
    }
    if($in{strPassword1} ne ''
     &&($in{strPassword1} =~ /[^,.#-:\[\]';0-9a-zA-Z ]/
      ||length($in{strPassword1}) < 5
      ||$in{strPassword1} eq $in{strEmail}))
    { $zmsg .= "<li>New password cannot contain some special characters and must be at least 5 characters long and cannot be the same as your email address (login id).\n";
    }
  }
  ###################################################################
  # check phone card and pin values
  ###################################################################
  $in{strPCPhone} =~ s/ //g;
  if($in{strPCPhone} ne ''
   &&$in{strPCPhone} =~ /[^0-9]/)
  { $zmsg .= "<li>Phone card phone number, <b>$in{strPCPhone}</b>, can only contain digits.\n";
  }
  $in{strPCPin} =~ s/ //g;
  if($in{strPCPin} ne ''
   &&$in{strPCPin} =~ /[^0-9#]/)
  { $zmsg .= "<li>Phone card PIN number, <b>$in{strPCPin}</b>, can only contain digits and # character.\n";
  }
  ###################################################################
  # check city/phone pairs
  ###################################################################
  for($zii=1; $zii<=9; $zii++)
  { $zcity="strLocCity$zii";
    $zphone="strLocPhone$zii";
    if($in{$zcity} eq ''
     &&$in{$zphone} ne '')
    { $zmsg .= "<li>City must be entered for phone number <b>$in{$zphone}</b>.\n";
    }
    $in{$zphone} =~ s/ //g;
    if($in{$zphone} =~ /[^0-9]/)
    { $zmsg .= "<li>Phone number <b>$in{$zphone}</b> can only contain numeric digits.\n";
    }
  }
  ###################################################################
  # check submit passwd
  ###################################################################
  if($in{strEmail} eq '' || $in{strPassword} eq '')
  { $zmsg .= "<li>Your current <b>Password</b> must be entered to submit updates!\n";
  }
  ###################################################################
  # check if userid and passwd match an existing user
  ###################################################################
  if($zmsg eq '')
  { $zret=&member_get($in{strEmail});
    if($zret == 1)
    { close(MEMLK);
      $zmsg .= "<li>Email address (login id), <b>$in{strEmail}</b>, not found in our database.\n";
    }
    else
    { if($gtuv{u_passwd} ne $in{strPassword})
      { close(MEMLK);
        $zmsg .= "<li>Email address (login id), <b>$in{strEmail}</b>, and password, <b>$in{strPassword}</b>, not found in our database.\n";
      }
    }
  }
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  { &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  ###################################################################
  # merge city/phone data into one field
  ###################################################################
  $zii=0;
  $zcityphone='';
  for($zii=1; $zii<=9; $zii++)
  { $zcity="strLocCity$zii";
    $zphone="strLocPhone$zii";
    if($in{$zcity} ne '')
    { $zcityphone .= ":$in{$zcity}#$in{$zphone}";
    }
  }
  $zcityphone=substr($zcityphone,1);
  $in{strLoc}=$zcityphone;
  $gtuv{u_loc}=$zcityphone;
  ###################################################################
  # ck for new passwd and also set phone card number and pin
  ###################################################################
  if($in{strPassword1} ne ''
   &&$in{strPassword1} eq $in{strPwdConfirm1})
  { $gtuv{u_passwd}=$in{strPassword1};
    $in{strPassword}=$in{strPassword1};
  }
  $gtuv{u_pcphone}=$in{strPCPhone};
  $gtuv{u_pcpin}  =$in{strPCPin};
  ###################################################################
  # put data into gtuv, in, and var
  ###################################################################
  foreach $zfield (@gtMemCal)
  { $ztmp=$zfield;
    ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
    $vars{$zkeyvar}=$in{$zkeyin};
    $gtuv{$zkeyuv}=$in{$zkeyin};
  }
  ###################################################################
  # create member string
  ###################################################################
  $zmemstr='';
  foreach $zkey (@gtMemDB)
  { $zmemstr .= "|$gtuv{$zkey}";
  }
  $zmemstr=substr($zmemstr,1);
  ###################################################################
  # encrypt passwd that is displayed on web pages
  ###################################################################
  $vars{strPassword}=crypt($gtuv{u_passwd},time);
  $vars{password}=$vars{strPassword};
  ###################################################################
  # add new member to in-storage array
  ###################################################################
  @zmemdata=();
  foreach $zfield (@memdata)
  { $ztmp=$zfield;
    ($zuserid,$zjunk)=split(/\|/,$ztmp,2);
    if($gtuv{u_userid} eq $zuserid)
    { push(@zmemdata,"$zmemstr\n");
    }
    else
    { push(@zmemdata,$zfield);
    }
  }
  @memdata=sort(@zmemdata);
  ###################################################################
  # output the new member file to a temp file
  ###################################################################
  if(!open(MEMFN,">$vars{member_file}-tmp"))
  { close(MEMLK);
    &Error("Can't open $vars{member_file}-tmp file for write!");
  }
  print MEMFN @memdata;
  close(MEMFN);
  ###################################################################
  # rename the file to the main member file name
  ###################################################################
  rename "$vars{member_file}-tmp","$vars{member_file}";
  close(MEMLK);
  &DISPLAY;
#  &calendar_error_msg('','mytravel_html'); #Aaron
  return;
}
#####################################################################
#
# Member search
#
#####################################################################
sub member_search
{ my(@zmemdata,$zmem,$zmsg,$zcgi,$zmember_search);
  my($zloginid,$zpassword,$zfirstname,$zlastname,$zloc,$z6,$z7,$z8,$z9,$z10,$z11,$z12,$z13,$z14,$z15,$z16,$z17,$z18,$zinfo,$zjunk);
  my($zcity,$zcityphone,$zphone,$zcityphone1); #Aaron
  my($zwrk,$zfield);
  $zcgi="calendar-$vars{lang}.pl?config=".$vars{config}.'&ACTION=DISPLAY';
  $zmember_search='';
  $zmsg='';
  if($in{strSearch} eq '')
  { $zmsg="Three (3) or more characters and/or numbers are needed to do the search.\n";
  }
  else
  { if(-e "$vars{member_file}")
    { if(!open(MEMFN,"<$vars{member_file}"))
      { close(MEMLK);
        &Error("Can't open $vars{member_file} file for read!");
        exit;
      }
      @zmemdata=<MEMFN>;
      close(MEMFN);
    }
    foreach $zmem(sort @zmemdata)
    { ($zloginid,$zpassword,$zfirstname,$zlastname,$zloc,$z6,$z7,$z8,$z9,$z10,$z11,$z12,$z13,$z14,$z15,$z16,$z17,$z18,$zinfo,$zjunk)=split(/\|/,$zmem,20); #Aaron
($zcity,$zcityphone)=split(/\#/,$zloc,2); #Aaron
($zphone,$zcityphone1)=split(/\:/,$zcityphone,2); #Aaron
  $zinfo =~ s/\n+//;   #Aaron
      if($zloginid eq $in{strSearch})
      { $zmsg='ok';
  $in{loginid}    =$zloginid;   #Aaron
  $vars{loginid}  =$zloginid;   #Aaron 
  $vars{password} =$zpassword;  #Aaron
  $vars{firstname}=$zfirstname; #Aaron
  $vars{lastname} =$zlastname;  #Aaron
  &DISPLAY;                     #Aaron
  exit;                         #Aaron
      }
      else
      { $zwrk=$in{strSearch};
        while($zwrk)
        { ($zfield,$zwrk)=split(/ +/,$zwrk,2);
          if(($zloginid =~ /$zfield/i
           ||$zfirstname =~ /$zfield/i
           ||$zlastname =~ /$zfield/i)
           &&$zmember_search !~ /$zloginid/)
          { $zmember_search .= "<tr><td><font face=Arial size=2><a href=\"$zcgi&loginid=$zloginid&eventkey=$in{strEventkey}&firstname=$zfirstname&lastname=$zlastname\"><u>$zfirstname $zlastname</a></font></td><td><font face=Arial size=2><a href=\"mailto:$zloginid\">$zloginid</a></font></td>\n";
	if ($zinfo eq 'none' || $zphone eq '') {$zmember_search .= "<td><font face=Arial size=2>N/A</font></td></tr>\n"} #Aaron
	else {$zmember_search .= "<td><font face=Arial size=2>$zphone</font></td></tr>\n"} #Aaron
          }
        }
      }
    }
  }
  if($zmsg ne 'ok')
  { if($zmsg eq '')
    { if($zmember_search eq '')
      { $zmsg="No member information was found that met your <b>$in{strSearch}</b> search criteria.\n";
      }
      else
      { $zmsg="The following members met your <b>$in{strSearch}</b> search criteria.\n";
        $zmsg .= "<br>Click their <b>Member Name</b> to display their calendar.\n";
        $zmsg .='<table border="1"><tr bgcolor="#FF9900"><th><font face="Arial" size=3 color=#000000><b>Member Name</b></font></th><th><font face="Arial" size=3 color=#000000><b>Email Address</b></font></th><th><font face="Arial" size=3 color=#000000><b>Phone Number</b></font></th></tr>'.$zmember_search.'</table>';
      }
    }
    &calendar_error_msg($zmsg,'calendar_error_html');
    exit(0);
  }
  $in{loginid}    =$zloginid;
  $vars{loginid}  =$zloginid;
  $vars{password} =$zpassword;
  $vars{firstname}=$zfirstname;
  $vars{lastname} =$zlastname;
  &DISPLAY;
}

#####################################################################
#
# Display add event page by Aaron
#
#####################################################################
sub add_event
{
  my($ztemplate);

  $vars{loginid}=$in{loginid};
  $vars{password}=$in{password};
  $vars{firstname}=$in{firstname};
  $vars{lastname}=$in{lastname};
 $vars{'month_form'} = "<select name=Month>\n";
 $zii = 0;
  for($zii=1; $zii<=12; $zii++) {
	if ($zii eq $vars{month}) {
		$vars{'month_form'}.= "<option value=$zii selected>$shortmonths[$zii-1]\n";
	}
	else {
		$vars{'month_form'}.= "<option value=$zii>$shortmonths[$zii-1]\n";
	}
}
 $vars{'month_form'} .= "</select>\n";
 $vars{'smonth_form'} = "<select name=sMonth>\n"; 
 $zii = 0; 
  for($zii=1; $zii<=12; $zii++) {
        if ($zii eq $vars{month}) {
                $vars{'smonth_form'}.= "<option value=$zii selected>$shortmonths[$zii-1]\n";
        }
        else {   
                $vars{'smonth_form'}.= "<option value=$zii>$shortmonths[$zii-1]\n";
        }
}
 $vars{'smonth_form'} .= "</select>\n"; 
 $vars{'emonth_form'} = "<select name=eMonth>\n"; 
 $zii = 0; 
  for($zii=1; $zii<=12; $zii++) {
        if ($zii eq $vars{month}) {
                $vars{'emonth_form'}.= "<option value=$zii selected>$shortmonths[$zii-1]\n";
        }
        else {   
                $vars{'emonth_form'}.= "<option value=$zii>$shortmonths[$zii-1]\n";
        }
}
 $vars{'emonth_form'} .= "</select>\n";  
if ($in{repeat} eq 'Yes') {	
 $ztemplate = &load_template("$vars{addrepeatevent_html}");
}
else {
 $ztemplate = &load_template("$vars{addevent_html}");
}
  $ztemplate = &parse_template($ztemplate, \%vars);
  print $ztemplate;
  exit;
}
#####################################################################
#
# Display mytravel main page by Aaron
#
#####################################################################
sub front_page
{
  my($template);
  $vars{loginid}=$in{loginid};
  $vars{password}=$in{password};
  $vars{firstname}=$in{firstname};
  $vars{lastname}=$in{lastname};
  $template = &load_template("$vars{mytravel_html}");
  $template = &parse_template($template, \%vars);
  print $template;
  exit;
}


#####################################################################
#
# Output a service page by Aaron
#
#####################################################################
 sub goto_service
{ my($xtemplate)=@_;
  my($template);
  $vars{error_msg}=$xmsg;
  $template = &load_template("/homed/globalta/calendar/$vars{templatedir}/services/$xtemplate");
  $vars{cat}=$in{cat};
  $vars{service}=$in{service};
  $vars{firstname}=$in{firstname};
  $vars{lastname}=$in{lastname};
  $vars{strLocPhone1}=$in{strLocPhone1};
  $vars{loginid}=$in{loginid};
  $vars{password}=$in{password};
  $template = &parse_template($template, \%vars);
  print $template;
  exit;
}

#####################################################################
#
# Output a service page by category by Aaron
#
#####################################################################
sub goto_service_1
{ my($xtemplate)=@_;
  my($template);
  $vars{error_msg}=$xmsg;
  $template = &load_template("/homed/globalta/calendar/$vars{templatedir}/services/$in{cat}-$in{service}");
  $vars{cat}=$in{cat};
  $vars{service}=$in{service};
  $vars{loginid}=$in{loginid};
  $vars{password}=$in{password};
  $template = &parse_template($template, \%vars);
  print $template;
  exit;
}

#####################################################################
#
# Go to pages
#
#####################################################################
sub goto_page
{ my($xtemplate)=@_;
  my($template);
  $vars{error_msg}=$xmsg;
  $template = &load_template("/homed/globalta/calendar/$vars{templatedir}/$xtemplate");
  $vars{loginid}=$in{loginid};
  $vars{password}=$in{password};
  $vars{flag}=$in{flag};
  $vars{firstname}=$in{firstname};
  $vars{lastname}=$in{lastname};                                  
  $vars{strLocPhone1}=$in{strLocPhone1};
  $template = &parse_template($template, \%vars);
  print $template;
  exit;
}

#####################################################################
#
# Logout My Travel
#
#####################################################################
sub logout
{
  $vars{error_msg}=$xmsg;
      $vars{sc_cookie}="Set-Cookie:gtlogin=|;path=/\n";        # Aaron
      print ("$vars{sc_cookie}\n\n");
  $template = &load_template("/homed/globalta/calendar/$vars{templatedir}/mytravel.html");
  $template = &parse_template($template,);
  print $template;
  exit;
}

#####################################################################
#
# Read in phone book data file
#
#####################################################################
sub read_phone_data {
	undef %phones;
	$vars{new_phone_id}=0;
	my($zloginid, $zid, $zflag, $zlname,$zfname);
        my($zhphone,$zbphone,$zcphone,$zpager);
        my($zcompany,$zemail,$zaddress,$zcity,$zstate,$zzip,$zcountry);
        my($zwebpage,$zbirthday,$znotes,$zcategory,$zsubcat,$zjunk);
        my $total_phones = 0;
        my(@zpdb);


      open(IN,"<$vars{phone_file}/$in{loginid}") || &Error("Can't open $vars{phone_file}/$in{loginid} for read");
       @zpd=<IN>;
        close(IN);
      @userdb=(); 
      foreach $zrec (@zpd) { 
         chomp($zrec);
          $zrec2=$zrec;
          $zrec3=$zrec;
          foreach $zkey (@gtDataPhone)   { 
            ($gtuv{$zkey},$zrec3)=split(/\|/,$zrec3,2);   # create user hash
              }
         if ($zflag eq $in{flag} || ($zflag eq 'CB' && $in{flag} eq 'B') || ($zflag eq 'B' && $in{flag} eq 'CB')) {
	push(@userdb,"$zrec2\n");
	}

}
#	open(IN,"$vars{phone_file}/$in{loginid}") || &Error("Can't open $vars{phone_file}/$in{loginid}");
#	my $header = <IN>;
#	# If file isnt in right format, give error
#	unless ($header =~ m/^#loginid\|id\|flag\|lname\|fname\|home/) { #Aaron
#		close(IN);
#		print "The phone book file is not in the correct format for this version.";
#		exit(0);
#		}

#	while (<IN>) {
#		chomp;
#		next unless /^\d/;
# jxl event data
#		($zloginid,$zid,$zflag,$zlname,$zfname,$zhphone,$zbphone,$zcphone,$zpager,$zcompany,$zemail,$zaddress,$zcity,$zstate,$zzip,$zcountry,$zwebpage,$zbirthday,$znotes,$zcategory,$zsubcat,$zjunk) = split(/\|/,$_,22); #Aaron
#		if ($zid > $vars{new_phone_id}) { $vars{new_phone_id} = $zid; }

		# Skip it unless login id match database
#		next unless ($zloginid eq $in{loginid});
#		next unless ($zflag eq $in{flag} || ($zflag eq 'CB' && $in{flag} eq 'B') || ($zflag eq 'B' && $in{flag} eq 'CB'));
 #               $total_phones++;
#		${$phones{$in{loginid}}}{$total_phones}{loginid} = $zloginid;
#		${$phones{$in{loginid}}}{$total_phones}{id} = $zid;
#		${$phones{$in{loginid}}}{$total_phones}{flag} = $zflag;
#		${$phones{$in{loginid}}}{$total_phones}{fname} = $zfname;
#		${$phones{$in{loginid}}}{$total_phones}{lname} = $zlname;
#		${$phones{$in{loginid}}}{$total_phones}{hphone} = $zhphone;
#		${$phones{$in{loginid}}}{$total_phones}{bphone} = $zbphone;
#		${$phones{$in{loginid}}}{$total_phones}{cphone} = $zcphone;
#		${$phones{$in{loginid}}}{$total_phones}{pager} = $zpager;
#		${$phones{$in{loginid}}}{$total_phones}{company} = $zcompany;
#		${$phones{$in{loginid}}}{$total_phones}{email} = $zemail;
#		${$phones{$in{loginid}}}{$total_phones}{address} = $zaddress;
#		${$phones{$in{loginid}}}{$total_phones}{city} = $zcity;
#		${$phones{$in{loginid}}}{$total_phones}{state} = $zstate;
#		${$phones{$in{loginid}}}{$total_phones}{zip} = $zzip;
#		${$phones{$in{loginid}}}{$total_phones}{country} = $zcountry;
#		${$phones{$in{loginid}}}{$total_phones}{webpage} = $zwebpage;
#		${$phones{$in{loginid}}}{$total_phones}{birthday} = $zbirthday;
#		${$phones{$in{loginid}}}{$total_phones}{notes} = $znotes;
#		${$phones{$in{loginid}}}{$total_phones}{category} = $zcategory;
#		${$phones{$in{loginid}}}{$total_phones}{subcat} = $zsubcat;
#		}
#	close(IN);
#	$vars{new_phone_id}++;
	}

#####################################################################
#
# display_phone_book()
#
# Display the phone book
#
#####################################################################
sub display_phone_book {
my($xopr)=@_;
if($vars{loginid} eq '') { 
   $vars{loginid}=$in{loginid};
    }
if($vars{firstname} eq '')  { #Aaron 
   $vars{firstname}=$in{firstname};
    }
if($vars{member_login} eq ''){ 
   $vars{member_login}=$in{member_login};
    }
$vars{password}=$in{password};
if($vars{password} eq '') {
   $vars{password}=$in{strPassword};
   }
$vars{flag} = $in{flag};

# Copy / Update or Delete function
# --------------------------------
if($in{Copy} eq 'Yes') {
   &copy_phonebook;
   }
if ($in{Update} eq 'Yes') {
   &update_phonebook_delete('Update','');
   }
if ($in{Delete} eq 'Yes') {
     &update_phonebook_delete('Delete','');
    exit(0);
}

# Load the correct Template for Display Detail info and Modify phone
# ------------------------------------------------------------------
if ($xopr eq 'detail') {
   if ($in{flag} eq 'B' || $in{flag} eq 'CB') {
      $template = &load_template("$vars{phonedetail2_html}");
      }
   else {
      $template = &load_template("$vars{phonedetail_html}");	
      }	
   }
elsif ($xopr eq 'modify'){
   if ($in{flag} eq 'B') {
       $template = &load_template("$vars{editphonebook2_html}");
      }
     elsif ($in{flag} eq 'CB') {
         $template = &load_template("$vars{editphonebook1_html}");
         }
     else {
        $template = &load_template("$vars{editphonebook_html}");
     }
   }
else{
   if ($in{flag} eq 'B' || $in{flag} eq 'CB') {
      $template = &load_template("$vars{phonebook2_html}");
      }
   else {
          $template = &load_template("$vars{phonebook1_html}");
        }
   }

$vars{phone_list} = "";

# Load the file
# -------------

open(IN,"<$vars{phone_file}/$in{loginid}") || &Error("Can't open $vars{phone_file}/$in{loginid} for read");
@zpd=<IN>;
 close(IN);
@userdb=(); 
foreach $zrec (@zpd) { 
   chomp($zrec);
   $zrec2=$zrec;
   $zrec3=$zrec;
   foreach $zkey (@gtDataPhone)   { 
     ($gtuv{$zkey},$zrec3)=split(/\|/,$zrec3,2);   # create user hash
     }
   if ($gtuv{p_flag} eq $in{flag} || ($gtuv{p_flag} eq 'CB' && $in{flag} eq 'B') || ($gtuv{p_flag} eq 'B' && $in{flag} eq 'CB')) {
#    push(@userdb,"$zrec2\n");
#   }


#@userdb = sort (@userdb);

# Display the table
# -----------------

if ($in{lsearch} eq '' || ($in{flag} eq 'P' && $gtuv{p_lname} =~ /^$in{lsearch}/i) ||
   (($in{flag} eq 'B' || $in{flag} eq 'CB') && $gtuv{p_city} =~ /^$in{lsearch}/i)) {

   $vars{phone_list} .="<tr bgcolor=#DADADA>";
   if ($gtuv{p_flag} eq 'B') {
      $vars{phone_list} .="<td><font face=Arial size=2>$gtuv{p_city}&nbsp;</font></td>\n";
      $vars{phone_list} .="<td><font face=Arial size=2>$gtuv{p_category}&nbsp; $gtuv{p_subcat}&nbsp;</font></td>\n";
      $vars{phone_list} .="<td><font face=Arial size=2><a href=https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=calendar-Latin1.cfg&ACTION=member_login&login=Phonebook1&level=detail&strEmail=$in{loginid}&strPassword=$in{password}&id=$gtuv{p_id}&firstname=$vars{firstname}&flag=$vars{flag}><font color=#000000>$gtuv{p_company}</font></a></font></td>\n";
      }
   elsif ($gtuv{p_flag} eq 'CB') {
      $vars{phone_list} .="<td><font face=Arial size=2>$gtuv{p_city}&nbsp;</font></td>\n";
      $vars{phone_list} .="<td><font face=Arial size=2><a href=https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=calendar-Latin1.cfg&ACTION=member_login&login=Phonebook1&level=detail&strEmail=$in{loginid}&strPassword=$in{password}&id=$gtuv{p_id}&firstname=$vars{firstname}&flag=$gtuv{p_flag}><font color=#000000>$gtuv{p_lname}, $gtuv{p_fname}</font></a></font></td>\n";
      $vars{phone_list} .="<td><font face=Arial size=2><font color=#000000>$gtuv{p_company}</font></font></td>\n";
      }
   else {
      $vars{phone_list} .="<td><font face=Arial size=2><a href=https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=calendar-Latin1.cfg&ACTION=member_login&login=Phonebook1&level=detail&strEmail=$in{loginid}&strPassword=$in{password}&id=$gtuv{p_id}&firstname=$vars{firstname}&flag=$vars{flag}><font color=#000000>$gtuv{p_lname}, $gtuv{p_fname}</font></a></font></td>\n";
      $vars{phone_list} .="<td><font face=Arial size=2>$gtuv{p_hphone}&nbsp;</font></td>\n";
   }

   $vars{phone_list} .="<td><font face=Arial size=2>$gtuv{p_bphone}&nbsp;</font></td>\n";
   if ($gtuv{p_flag} eq 'P') {
      $vars{phone_list} .="<td><font face=Arial size=2><a href=mailto:$gtuv{p_email}><font color=#000000>$gtuv{p_email}</font></a>&nbsp;</font></td>\n";
      $zret=&member_get($gtuv{p_email}); 
      if($zret == 1) { 
         close(MEMLK);
         $vars{phone_list} .="<td><div align=center><img src=/\%7Eglobalta/Latin1/cross.gif width=15 height=15 border=0></div></td>\n";
         }
      else {
         $vars{phone_list} .="<td><div align=center><font face=Arial color=#000000><a href=https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=calendar2-Latin1.cfg\&ACTION=member_search\&strSearch=$gtuv{email}><img src=/\%7Eglobalta/Latin1/check.gif width=15 height=15 border=0></a></font></div></td>";
          }
      }

   $vars{phone_list} .="</tr>\n\n";

   if ($gtuv{p_id} eq "$in{id}") {
      $vars{id} = $in{id};
       $vars{fname} = $gtuv{p_fname};
       $vars{lname} = $gtuv{p_lname};
       $vars{hphone} = $gtuv{p_hphone};
       $vars{bphone} = $gtuv{p_bphone};
       $vars{cphone} = $gtuv{p_cphone};
       $vars{pager} = $gtuv{p_pager};
       $vars{company} = $gtuv{p_company};
       $vars{email} = $gtuv{p_email};
       $vars{address} = $gtuv{p_address};
       $vars{city} = $gtuv{p_city};
       $vars{state} = $gtuv{p_state};
       $vars{zip} = $gtuv{p_zip};
       $vars{country} = $gtuv{p_country};
       $vars{webpage} = $gtuv{p_webpage};
       $vars{birthday} = $gtuv{p_birthday};
       $vars{notes} = $gtuv{p_notes};
      $vars{notes} =~ s|<BR>|\n|ig;
       $vars{category} = $gtuv{p_category};
       $vars{subcat} = $gtuv{p_subcat};
      }
   }
 }
}
# Put in the rest of the variables
# --------------------------------
$template = &parse_template($template, \%vars);
	
# Remove special comments from template
# -------------------------------------
$template =~ s|<!--#.*?#-->\r?\n?||sig;
	
$template =~ s|</body>|<BR>\n</body>|si;
print $template;
exit;
} #end of display phone book


#####################################################################
#
# add_phone()
#
# Add an phone entry
#
#####################################################################
sub add_phone {	
	my($zmsg);
	$vars{flag} = $in{flag};	
        my (@zpd);
	&read_phone_data;
	$zmsg='';
        if($in{fname} eq '' && $in{flag} ne 'B')
        { $zmsg.="<li><b>First Name</b> is required.\n";
        }
        if($in{lname} eq '' && $in{flag} ne 'B')
        { $zmsg.="<li><b>Last Name</b> is required.\n";
        }
        if($in{flag} eq 'B' && $in{company} eq '')
        { $zmsg.="<li><b>Business Company</b> is required.\n";
        }
  	$in{hphone} =~ s/ +//g;            # remove spaces     
  	$in{hphone} =~ s/-+//g;            # remove dashes     
  	$in{hphone} =~ s/\(+//;           # remove left parenthesis     
  	$in{hphone} =~ s/\)+//;           # remove right parenthesis       
  	$in{cphone} =~ s/ +//g;            # remove spaces     
  	$in{cphone} =~ s/-+//g;            # remove dashes     
  	$in{cphone} =~ s/\(+//;           # remove left parenthesis      
  	$in{cphone} =~ s/\)+//;           # remove right parenthesis     
  	$in{bphone} =~ s/ +//g;            # remove spaces       
  	$in{bphone} =~ s/-+//g;            # remove dashes       
  	$in{bphone} =~ s/\(+//;           # remove left parenthesis       
  	$in{bphone} =~ s/\)+//;           # remove right parenthesis       
  	$in{pager} =~ s/ +//g;            # remove spaces      
  	$in{pager} =~ s/-+//g;            # remove dashes      
  	$in{pager} =~ s/\(+//;           # remove left parenthesis      
  	$in{pager} =~ s/\)+//;           # remove right parenthesis  
        $in{notes} =~ s|[\r\n]+|<BR>|gs;
        $in{webpage} =~ s/http:\/\/+//g;
        if($zmsg ne '')
        { $zmsg="<ul>\n".$zmsg."</ul>\n";
          &calendar_error_msg($zmsg,'calendar_error_html');
          exit(0);
        }
		open(OUT,">> $vars{phone_file}/$in{loginid}") || &Error("Can't open $calendar_file for writing!");
		eval "flock OUT,2";
# jxl event data
		print OUT "$in{lname}|$vars{new_phone_id}|$in{flag}|$in{lname}|$in{fname}|$in{hphone}|$in{bphone}|$in{cphone}|$in{pager}|$in{company}|$in{email}|$in{address}|$in{city}|$in{state}|$in{zip}|$in{country}|$in{webpage}|$in{birthday}|$in{notes}|$in{category}|$in{subcat}\n"; #Aaron
		close(OUT);

        open(IN,"<$vars{phone_file}/$in{loginid}") || &Error("Can't open $vars{phone_file}/$in{loginid} for read");
        @zpd=<IN>;
        @zpd=sort(@zpd);
        open(IN,">$vars{phone_file}/$in{loginid}") || &Error("Can't open $vars{phone_file}/$in{loginid} for write");
        print IN @zpd;
        close(IN);

        $vars{loginid}   =$in{loginid};
        $vars{password}   =$in{password};
        $vars{firstname} =$in{firstname};
        $vars{lastname}  =$in{lastname};
        $vars{password}  =$in{password};
	&display_phone_book;
	exit(0);
	} #end of ADD phone book
#####################################################################
#
# Edit update or delete phonebook entry
#
#####################################################################
sub update_phonebook_delete
{ my($zopr,$zmsg)=@_;
my $zloginid, $zid, $zflag, $zlname,$zfname,$zhphone,$zbphone,$zcphone,$zpager,$zcompany,$zemail,$zaddress,$zcity,$zstate,$zzip,$zcountry,$zwebpage,$zbirthday,$znotes,$zcategory,$subcat,$zjunk;
  my(@zphonedata,$zline); 
  my($template);
  &read_phone_data;
	$in{notes} =~ s|[\r\n]+|<BR>|gs;
        $in{webpage} =~ s/http:\/\/+//g; 
  $in{hphone} =~ s/ +//g;            # remove spaces
  $in{hphone} =~ s/-+//g;            # remove dashes
  $in{hphone} =~ s/\(+//;           # remove left parenthesis
  $in{hphone} =~ s/\)+//;           # remove right parenthesis
  $in{cphone} =~ s/ +//g;            # remove spaces
  $in{cphone} =~ s/-+//g;            # remove dashes
  $in{cphone} =~ s/\(+//;           # remove left parenthesis
  $in{cphone} =~ s/\)+//;           # remove right parenthesis
  $in{bphone} =~ s/ +//g;            # remove spaces
  $in{bphone} =~ s/-+//g;            # remove dashes
  $in{bphone} =~ s/\(+//;           # remove left parenthesis
  $in{bphone} =~ s/\)+//;           # remove right parenthesis
  $in{pager} =~ s/ +//g;            # remove spaces
  $in{pager} =~ s/-+//g;            # remove dashes
  $in{pager} =~ s/\(+//;           # remove left parenthesis
  $in{pager} =~ s/\)+//;           # remove right parenthesis
  if($zmsg eq '')
  { open(PHONEK,">$vars{phone_lock}")
     || &Error("Can't lock the $vars{phone_lock} file by edit update/delete!");
    eval "flock PHONEK,2";
    if(-e "$vars{phone_file}/$in{loginid}")
    { if(!open(PHONEF,"<$vars{phone_file}/$in{loginid}"))
      { close(PHONEK);
        &Error("Can't open $vars{phone_file}/$in{loginid} file for read by edit update/delete!");
        exit;
      }
      @zphonedata=<PHONEF>;
      close(PHONEF);
      if(!open(PHONEF,">$vars{phone_file}/$in{loginid}-tmp"))
      { close(PHONEK);
        &Error("Can't open $vars{phone_file}/$in{loginid}-tmp file for write by edit update/delete!");
      }
      foreach $zline (@zphonedata)
	{	($zloginid,$zid,$zflag,$zlname,$zfname,$zhphone,$zbphone,$zcphone,$zpager,$zcompany,$zemail,$zaddress,$zcity,$zstate,$zzip,$zcountry,$zwebpage,$zbirthday,$znotes,$zjunk) = split(/\|/,$zline,20); #Aaron
        if($zid eq "$in{id}")
        { if($zopr eq 'Update')
          { 
            print PHONEF "$in{lname}|$zid|$zflag|$in{lname}|$in{fname}|$in{hphone}|$in{bphone}|$in{cphone}|$in{pager}|$in{company}|$in{email}|$in{address}|$in{city}|$in{state}|$in{zip}|$in{country}|$in{webpage}|$in{birthday}|$in{notes}\n"; #Aaron
          }
          $zmsg='ok';
        }
        else
        { print PHONEF $zline;
        }
      }
      close(PHONEF);

      if($zmsg ne 'ok')
      { $zmsg="<li>ID $in{id} not found.  Please reload/refresh your web browser views.";
        $vars{error_msg}='<font color="red"><b>Errors:</b><br>'.$zmsg.'</font>';
      }
      else
      { # rename
        rename "$vars{phone_file}/$in{loginid}-tmp","$vars{phone_file}/$in{loginid}";
      }
    }
    else
    { $zmsg="<li>$vars{phone_file}/$in{loginid} does not exist for edit update/delete. Please reload/refresh your web browser views.";
    }
    close(PHONEK);
  }
        open(IN,"<$vars{phone_file}/$in{loginid}") || &Error("Can't open $vars{phone_file}/$in{loginid} for read");
        @zpd=<IN>;
        @zpd=sort(@zpd);
        open(IN,">$vars{phone_file}/$in{loginid}") || &Error("Can't open $vars{phone_file}/$in{loginid} for write");
        print IN @zpd;
        close(IN);
  if($zmsg ne '' && $zmsg ne 'ok')
  { $vars{error_msg}='<font color="red"><b>Errors:</b><br>'.$zmsg.'</font>';
          &calendar_error_msg($vars{error_msg},'calendar_error_html');
	 exit;
  }
  if ($zopr eq 'Delete' || $zopr eq 'Update') {
	$in{Delete} = 'No';
        $in{Update} = 'No';
	&display_phone_book('');
	}
}

#####################################################################
#
# Create Phonebook File
#
#####################################################################
sub create_phonebook {

if(!open(PHONEF,">$vars{phone_file}/$in{strEmail}"))
      {
        $vars{error_msg} = "Can't open $vars{phone_file}/$in{loginid} file for write by edit update/delete!";
          &calendar_error_msg($vars{error_msg},'calendar_error_html');
      }
else {
	print PHONEF "#loginid|id|flag|lname|fname|home phone\n";
#	&display_phone_book('$in{level}');
	}
}

#####################################################################
#
# copy_phonebook()
#
# Copy the phone data to another flag
#
#####################################################################
sub copy_phonebook {
        if($vars{loginid} eq '')
        { $vars{loginid}=$in{loginid};
        }
        if($vars{firstname} eq '')   #Aaron
        { $vars{firstname}=$in{firstname};
        }
        if($vars{member_login} eq '')
        { $vars{member_login}=$in{member_login};
        }
        $vars{flag} = $in{flag};
        $vars{password}=$in{password};
        if($vars{password} eq '')
	{$vars{password}=$in{strPassword};
	}
        
        &read_phone_data;

 	if ($in{flag} eq 'B') {
#                $template = &load_template("$vars{phonebook1_html}");
		$vars{new_flag} = 'P';
		$in{flag} = 'P';
                }
        else {
#                $template = &load_template("$vars{phonebook2_html}");
                $vars{new_flag} = 'CB';
                $in{flag} = 'B';
	}

	foreach $i(sort keys %{$phones{$in{loginid}}}) {
		if ($phones{$in{loginid}}{$i}{id} eq "$in{id}") {
                $vars{fname} = $phones{$in{loginid}}{$i}{fname};
                $vars{lname} = $phones{$in{loginid}}{$i}{lname};
                $vars{hphone} = $phones{$in{loginid}}{$i}{hphone};
                $vars{bphone} = $phones{$in{loginid}}{$i}{bphone};
                $vars{cphone} = $phones{$in{loginid}}{$i}{cphone};
                $vars{pager} = $phones{$in{loginid}}{$i}{pager};
                $vars{company} = $phones{$in{loginid}}{$i}{company};
                $vars{email} = $phones{$in{loginid}}{$i}{email};
                $vars{address} = $phones{$in{loginid}}{$i}{address};
                $vars{city} = $phones{$in{loginid}}{$i}{city};
                $vars{state} = $phones{$in{loginid}}{$i}{state};
                $vars{zip} = $phones{$in{loginid}}{$i}{zip};
                $vars{country} = $phones{$in{loginid}}{$i}{country};
                $vars{webpage} = $phones{$in{loginid}}{$i}{webpage};
                $vars{birthday} = $phones{$in{loginid}}{$i}{birthday};
                $vars{notes} = $phones{$in{loginid}}{$i}{notes};
                $vars{notes} =~ s|<BR>|\n|ig;				
		}
	}
	open(OUT,">> $vars{phone_file}/$in{loginid}") || &Error("Can't open $calendar_file for writing!");
                eval "flock OUT,2";
                print OUT "$vars{lname}|$vars{new_phone_id}|$vars{new_flag}|$vars{lname}|$vars{fname}|$vars{hphone}|$vars{bphone}|$vars{cphone}|$vars{pager}|$vars{company}|$vars{email}|$vars{address}|$vars{city}|$vars{state}|$vars{zip}|$vars{country}|$vars{webpage}|$vars{birthday}|$vars{notes}\n";
                close(OUT);
	$in{Copy} = '';
#	&display_phone_book;
}

#####################################################################
#
# Read in destination service data file
#
#####################################################################
sub read_dest_data {
	undef %dest;
	$vars{new_dest_id}=0;
	my $zid, $zcity, $zcategory, $zsubcat,$zcompany,$zaddress,$zcross,$zphone,$zstate,$zzip,$zcountry,$zjunk;
	open(IN,"$vars{dest_file}/$in{city}.txt") || &Error("Can't open $vars{dest_file}/$in{city}.txt");
	my $header = <IN>;
	# If file isnt in right format, give error
	while (<IN>) {
		chomp;
		($zid,$zcity,$zcategory,$zsubcat,$zcompany,$zaddress,$zcross,$zphone,$zstate,$zzip,$zcountry,$zjunk) = split(/\|/,$_,12); #Aaron
		if ($zid > $vars{new_dest_id}) { $vars{new_dest_id} = $zid; }

		# Skip it unless login id match database
		next unless ($zcity eq $in{city});
		next unless ($zcategory eq $in{category});
		next unless ($zsubcat eq $in{subcat});
                $total_dest++;
		${$dest{$in{city}}}{$total_dest}{id} = $zid;
		${$dest{$in{city}}}{$total_dest}{city} = $zcity;
		${$dest{$in{city}}}{$total_dest}{category} = $zcategory;
		${$dest{$in{city}}}{$total_dest}{subcat} = $zsubcat;
		${$dest{$in{city}}}{$total_dest}{company} = $zcompany;
		${$dest{$in{city}}}{$total_dest}{address} = $zaddress;
		${$dest{$in{city}}}{$total_dest}{cross} = $zcross;
                ${$dest{$in{city}}}{$total_dest}{phone} = $zphone;
                ${$dest{$in{city}}}{$total_dest}{state} = $zstate;
                ${$dest{$in{city}}}{$total_dest}{zip} = $zzip;
                ${$dest{$in{city}}}{$total_dest}{country} = $zcountry;
		}
	close(IN);
	$vars{new_dest_id}++;
	}

#####################################################################
#
# display_destination_services()
#
# Display the Destination Services Page
#
#####################################################################
sub display_destination_services {
my($xopr)=@_;
	if($vars{loginid} eq '')
        { $vars{loginid}=$in{loginid};
        }
	if($vars{firstname} eq '')   #Aaron
        { $vars{firstname}=$in{firstname};
        }
	if($vars{member_login} eq '')
        { $vars{member_login}=$in{member_login};
        }
	$vars{password}=$in{password};
	if($vars{password} eq '')
	{$vars{password}=$in{strPassword};
	}

	$vars{category} = $in{category};
	$vars{subcat} = $in{subcat};

	&read_dest_data;

#if ($in{Update} eq 'Yes') {
#	&update_phonebook_delete('Update','');
#	&read_phone_data;
#}
#if ($in{Delete} eq 'Yes') {
#        &update_phonebook_delete('Delete','');
#	exit(0);
#}
if ($in{Detail} eq 'Yes') {
		$template = &load_template("$vars{dest_detail_html}");	
	}
elsif ($xopr eq 'modify'){
	        $template = &load_template("$vars{editphonebook2_html}");	
}
else{
        # Load the template and do the replace
        # ------------------------------------
		$template = &load_template("$vars{dest_list_html}");
}

$vars{dest_list} = "";
foreach $i(sort keys %{$dest{$in{city}}}) {

#if ($in{lsearch} eq '' || ($in{flag} eq 'P' && $phones{$in{loginid}}{$i}{lname} =~ /^$in{lsearch}/i) ||
#($in{flag} eq 'B' && $phones{$in{loginid}}{$i}{city} =~ /^$in{lsearch}/i)) {

	$vars{cities} = $dest{$in{city}}{$i}{city};
        $vars{cities} =~ s|[ ]+|%20|gs;
$vars{dest_list} .="<tr><td bgcolor=#ffffff><div align=center><input type=checkbox name=checkbox value=checkbox> </div></td>\n";
$vars{dest_list} .="<td bgcolor=#ffffff><font face=Arial size=2><a href=https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?ACTION=destination&Detail=Yes&config=calendar-Latin1.cfg&loginid=<%=loginid%>&password=<%=password%>&firstname=<%=firstname%>&id=$dest{$in{city}}{$i}{id}&city=$vars{cities}&category=$dest{$in{city}}{$i}{category}&subcat=$dest{$in{city}}{$i}{subcat}>$dest{$in{city}}{$i}{company}</a></font></td>\n";
$vars{dest_list} .="<td bgcolor=#ffffff><font face=Arial size=2>$dest{$in{city}}{$i}{address}</font></td>\n";
$vars{dest_list} .="<td bgcolor=#ffffff><font face=Arial size=2>$dest{$in{city}}{$i}{cross}</font></td>\n";
$vars{dest_list} .="<td bgcolor=#ffffff><font face=Arial size=2>$dest{$in{city}}{$i}{phone}</font></td></tr>\n";
                $vars{city} = $dest{$in{city}}{$i}{city};

if ($dest{$in{city}}{$i}{id} eq $in{id}) {
$vars{dest_list} .="YESYES";
		$vars{id} = $in{id};
                $vars{city} = $dest{$in{city}}{$i}{city};
                $vars{category} = $dest{$in{city}}{$i}{category};
                $vars{subcat} = $dest{$in{city}}{$i}{subcat};
                $vars{company} = $dest{$in{city}}{$i}{company};
                $vars{address} = $dest{$in{city}}{$i}{address};
                $vars{cross} = $dest{$in{city}}{$i}{cross};
                $vars{phone} = $dest{$in{city}}{$i}{phone};
                $vars{state} = $dest{$in{city}}{$i}{state};
                $vars{zip} = $dest{$in{city}}{$i}{zip};
                $vars{country} = $dest{$in{city}}{$i}{country};
		}
	}
#}

	# Put in the rest of the variables
	# --------------------------------
	$template = &parse_template($template, \%vars);
	
	# Remove special comments from template
	# -------------------------------------
	$template =~ s|<!--#.*?#-->\r?\n?||sig;
	
	$template =~ s|</body>|<BR>\n</body>|si;
	print $template;
	exit;
	} #end of display destination service

#####################################################################
#
# Read imported Outlook express file
#
#####################################################################
sub read_upload_outlook_file {
	my($filename)=@_;
	undef %outlook, %zfield, %zfieldname;
	my $head = 0;
	my $zjunk;
	open(IN,"$filename") || &Error("Can't open $filename");
	my $header = <IN>;
	($zfield{1},$zfield{2},$zfield{3},$zfield{4},$zfield{5},$zfield{6},$zfield{7},$zfield{8},$zfield{9},$zfield{10},$zfield{11},$zfield{12},$zfield{13},$zfield{14},$zfield{15},$zfield{16},$zfield{17},$zfield{18},$zfield{19},$zfield{20},$zfield{21},$zfield{22},$zfield{23},$zfield{24},$zfield{25},$zfield{26},$zfield{27},$zfield{28},$zfield{29}) = split(/\,/,$header,29); #Aaron
	  for($zii=1; $zii<=29; $zii++) {
				if ($zfield{$zii} eq 'First Name') {
					$zfieldname{$zii} = 'fname';
					}
				elsif ($zfield{$zii} eq 'Last Name') {
					$zfieldname{$zii} = 'lname';
					}
				elsif ($zfield{$zii} eq 'Name') {
					$zfieldname{$zii} = 'name';
					}
				elsif ($zfield{$zii} eq 'E-mail Address') {
					$zfieldname{$zii} = 'email';
					}
				elsif ($zfield{$zii} eq 'Home Street') {
					$zfieldname{$zii} = 'address';
					}
				elsif ($zfield{$zii} eq 'Home City') {
					$zfieldname{$zii} = 'city';
					}
				elsif ($zfield{$zii} eq 'Home Postal Code') {
					$zfieldname{$zii} = 'zip';
					}
				elsif ($zfield{$zii} eq 'Home State') {
					$zfieldname{$zii} = 'state';
					}
				elsif ($zfield{$zii} eq 'Home Country') {
					$zfieldname{$zii} = 'country';
					}
				elsif ($zfield{$zii} eq 'Home Phone') {
					$zfieldname{$zii} = 'hphone';
					}
				elsif ($zfield{$zii} eq 'Business Phone') {
					$zfieldname{$zii} = 'bphone';
					}
				elsif ($zfield{$zii} eq 'Company') {
					$zfieldname{$zii} = 'company';
					}
                                elsif ($zfield{$zii} eq 'Mobile Phone') {
                                        $zfieldname{$zii} = 'cphone';
                                        }
                                elsif ($zfield{$zii} eq 'Personal Web Page') {
                                        $zfieldname{$zii} = 'webpage';
                                        }
                                elsif ($zfield{$zii} eq 'Pager') {
                                        $zfieldname{$zii} = 'pager';
                                        }
                                elsif ($zfield{$zii} eq 'Notes') {
                                        $zfieldname{$zii} = 'notes';
                                        }
				else    {
					$zfieldname{$zii} = "$zfield{$zii}";
					}
				}
	while (<IN>) {
		chomp;
		($zfield{1},$zfield{2},$zfield{3},$zfield{4},$zfield{5},$zfield{6},$zfield{7},$zfield{8},$zfield{9},$zfield{10},$zfield{11},$zfield{12},$zfield{13},$zfield{14},$zfield{15},$zfield{16},$zfield{17},$zfield{18},$zfield{19},$zfield{20},$zfield{21},$zfield{22},$zfield{23},$zfield{24},$zfield{25},$zfield{26},$zfield{27},$zfield{28},$zfield{29}) = split(/\,/,$_,29); #Aaron
	        $total_outlook++;
			  for($ziii=1; $ziii<=29; $ziii++) {
				${$outlook{$in{loginid}}}{$total_outlook}{$zfieldname{$ziii}} = $zfield{$ziii};
				}
	
			if ($outlook{$in{loginid}}{$total_outlook}{fname} eq '' && $outlook{$in{loginid}}{$total_outlook}{lname} eq '' && $outlook{$in{loginid}}{$total_outlook}{name} ne '') {
				($outlook{$in{loginid}}{$total_outlook}{fname},$outlook{$in{loginid}}{$total_outlook}{lname}) = split(/ /,$outlook{$in{loginid}}{$total_outlook}{name},2);
				} 
		}
	close(IN);
	}


#####################################################################
#
# upload_files()
#
#####################################################################
sub upload_outlook_files
{
    my $bytes_read=0;
    my $size='';
    my $buff='';
    my $start_time;
    my $time_took;
    my $filepath='';
    my $filename='';
    my $write_file='';
  my $g_debug = 0;
  my $g_overwrite = 1;

    $filepath=$in{'upload_file'};
	$vars{upload_content} =~ s|[\r\n\n]+|\n|gs;

    # James Bee" <JamesBee@home.com> reported that from Windows filename
    # such as c:\foo\fille.x saves as c:\foo\file.x, so we've to get the
    # filename out of it
    # look at the last word, hold 1 or more chars before the end of the line
    # that doesn't include / or \, so it will take care of unix path as well
    # if it happens, muquit, Jul-22-1999
    if ($filepath =~ /([^\/\\]+)$/)
    {
        $filename="$1";
    }
    else
    {
        $filename="$filepath";
    }
    # if there's any space in the filename, get rid of them
    $filename =~ s/\s+//g;

    $write_file="$vars{upload_outlook_file}" . "/" . "$filename";    

    print "Filename=$filename<br>\n" if $g_debug;
    print "Writefile= $write_file<br>\n" if $g_debug;

    if ($g_overwrite == 0)
    {
        if (-e $write_file)
        {
          &calendar_error_msg("File $filename exists, will not overwrite",'calendar_error_html');
            exit;
        }
    }

    if (!open(WFD,">$write_file"))
    {
          &calendar_error_msg("Error opening file for writing $filename, $write_file, $in",'calendar_error_html'); 
        exit;
    }

	print WFD $vars{upload_content};

    close(WFD);

    if ((stat $write_file)[7] <= 0)
    {
        unlink($write_file);
          &calendar_error_msg("Could not upload file: $filename, $write_file, $in",'calendar_error_html'); 
        exit;
    }
    else
    {
	&copy_outlook_phonebook("$write_file");
    }
exit;
}

#####################################################################
#
# copy_outlood_phonebook()
#
# Copy the outlook file phone data to phone book
#
#####################################################################
sub copy_outlook_phonebook {
	my($xopr)=@_;
        if($vars{loginid} eq '')
        { $vars{loginid}=$in{loginid};
        }
        if($vars{firstname} eq '')   #Aaron
        { $vars{firstname}=$in{firstname};
        }
        if($vars{member_login} eq '')
        { $vars{member_login}=$in{member_login};
        }
        $vars{flag} = $in{flag};
        $vars{password}=$in{password};
        if($vars{password} eq '')
	{$vars{password}=$in{strPassword};
	}
        &read_upload_outlook_file($xopr);
	&read_phone_data;
	foreach $i(sort keys %{$outlook{$in{loginid}}}) {
                $vars{fname} = $outlook{$in{loginid}}{$i}{fname};
                $vars{lname} = $outlook{$in{loginid}}{$i}{lname};
                $vars{hphone} = $outlook{$in{loginid}}{$i}{hphone};
                $vars{bphone} = $outlook{$in{loginid}}{$i}{bphone};
                $vars{cphone} = $outlook{$in{loginid}}{$i}{cphone};
                $vars{pager} = $outlook{$in{loginid}}{$i}{pager};
		$vars{hphone} =~ s/ +//g;            # remove spaces
  		$vars{hphone} =~ s/-+//g;            # remove dashes
  		$vars{hphone} =~ s/\(+//;           # remove left parenthesis
  		$vars{hphone} =~ s/\)+//;           # remove right parenthesis
  		$vars{cphone} =~ s/ +//g;            # remove spaces
  		$vars{cphone} =~ s/-+//g;            # remove dashes
  		$vars{cphone} =~ s/\(+//;           # remove left parenthesis
  		$vars{cphone} =~ s/\)+//;           # remove right parenthesis
  		$vars{bphone} =~ s/ +//g;            # remove spaces
  		$vars{bphone} =~ s/-+//g;            # remove dashes
  		$vars{bphone} =~ s/\(+//;           # remove left parenthesis
  		$vars{bphone} =~ s/\)+//;           # remove right parenthesis
  		$vars{pager} =~ s/ +//g;            # remove spaces
  		$vars{pager} =~ s/-+//g;            # remove dashes
  		$vars{pager} =~ s/\(+//;           # remove left parenthesis
  		$vars{pager} =~ s/\)+//;           # remove right parenthesis
                $vars{company} = $outlook{$in{loginid}}{$i}{company};
                $vars{email} = $outlook{$in{loginid}}{$i}{email};
                $vars{address} = $outlook{$in{loginid}}{$i}{address};
                $vars{city} = $outlook{$in{loginid}}{$i}{city};
                $vars{state} = $outlook{$in{loginid}}{$i}{state};
                $vars{zip} = $outlook{$in{loginid}}{$i}{zip};
                $vars{country} = $outlook{$in{loginid}}{$i}{country};
                $vars{webpage} = $outlook{$in{loginid}}{$i}{webpage};
                $vars{birthday} = $outlook{$in{loginid}}{$i}{birthday};
                $vars{notes} = $outlook{$in{loginid}}{$i}{notes};
                $vars{notes} =~ s|<BR>|\n|ig;				

	open(OUT,">> $vars{phone_file}/$in{loginid}") || &Error("Can't open $calendar_file for writing!");
                eval "flock OUT,2";
                print OUT "$in{loginid}|$vars{new_phone_id}|P|$vars{lname}|$vars{fname}|$vars{hphone}|$vars{bphone}|$vars{cphone}|$vars{pager}|$vars{company}|$vars{email}|$vars{address}|$vars{city}|$vars{state}|$vars{zip}|$vars{country}|$vars{webpage}|$vars{birthday}|$vars{notes}\n";
                close(OUT);
	$vars{new_phone_id}++;
	}
	$in{Copy} = '';
	$in{flag} = P;
	&display_phone_book;
}
