#!/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'};
@gtuvlist= '';
&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'};
$vars{'page'} = $in{'Page'};
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{'currentdatestamp'} = sprintf("%4.4d%2.2d%2.2d",$year,$month,$mday);
$vars{'currentmonthstamp'} = sprintf("%4.4d%2.2d",$year,$month);
                                $vars{loadcookie} = 0;

# jxl $in{strEmailAddress} = lc ($in{strEmailAddress});
# jxl $in{strEmail} = lc ($in{strEmail});


if( defined $ENV{'HTTP_COOKIE'} 
   && $in{"ACTION"} ne "member_add" && $in{"ACTION"} ne 'member_add_1'
   && $in{"ACTION"} ne 'affiliate_add' && $in{"ACTION"} ne 'member_add_2'
   && $in{"ACTION"} ne 'signup_800num'
   && $in{"ACTION"} ne 'infinex_signup_member'
   && $in{"ACTION"} ne 'infinex_signup_affiliate'
   && $in{"ACTION"} !~ /^aff/g )
{ # 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);
#       $in{password}=crypt($gtuv{$in{'strPassword'}},time);
#       $in{password}=crypt($gtuv{$in{'strPassword'}},$in{strPassword});
        $vars{loadcookie} = 1;
        if ($in{"ACTION"} ne "logout" && $in{"ACTION"} ne "member_update")
        { print ("\n");
        }
#print "<br>vars{cookiename}='$vars{cookiename}'\n";
#print "<br>vars{cookievalue}='$vars{cookievalue}'\n";
#print "<br>gtuv{in{'strPassword'}='gtuv{$in{'strPassword'}}'='$gtuv{$in{'strPassword'}}'\n";
#print "<br>in{password}=crypt(gtuv{in{'strPassword'}},time)\n";
#print "<br>in{password}=crypt(gtuv{$in{'strPassword'}},time)\n";
#print "<br>in{password}=crypt($gtuv{$in{'strPassword'}},time)\n";
#print "<br>in{password}='$in{password}'\n";

#$ztime=substr(time,length(time)-2);
#print "<br>time='$ztime'\n";
#$ztime=crypt($gtuv{u_passwd},substr(time,length(time)-2));
#if($ztime eq crypt($gtuv{u_passwd},$ztime))
#{
#}
#print "<br>ztime='$ztime'\n";
      }
    }                                                         # jxl
  }                                                           # jxl
}                                                             # jxl
if( defined $ENV{'HTTP_COOKIE'} 
   && ($in{"ACTION"} eq "member_add" || $in{"ACTION"} eq 'member_add_1')
   && $in{strGTAffID} eq '')
{ # aaron put special affiliate id into record.
  my($zcookie);
  foreach $zcookie (split(/; /,$ENV{'HTTP_COOKIE'}))
  { ($vars{cookie1},$vars{cookie2}) = split(/=/,$zcookie,2);
    if ($vars{cookie1} eq 'gtaffid')
    {  if ($vars{cookie2} ne '')
       { $in{'strAffNumber'} = $vars{cookie2};        # jxl
         $in{'gtaffid'} = $in{strAffNumber};
#         last;
       }
    }                                                         # jxl
  }                                                           # jxl
}                                                             # jxl

#####################################################################
#
# Decide what to do based on the ACTION parameter
#
#####################################################################
# Member login password protected page
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'); 
  }
}
# Affiliate login password protected page
elsif ($in{"ACTION"} eq 'affiliate_login')
{ &member_login($in{login});
}
# Member signup function for different package -step 1 (not done)
elsif ($in{"ACTION"} eq "member_add_1")
{ #print("\n");
  if ($in{strRowNumber} eq '')
  { $in{strRowNumber} = 5;
  }
  &member_add_1;
}
# Member signup function for different package -step 2 (not done)
elsif ($in{"ACTION"} eq "member_add_2")
{ #print("\n");
  if ($in{strRowNumber} ne '' || $in{RowNumber} ne '')
  { &member_add_1;
  }
  else
  { $in{memberadd2} = 'Yes';
    &member_add_1;
  }
}
# Member Signup
elsif ($in{"ACTION"} eq "member_add")
{ &member_add;
}
# Affiliate Signup
elsif ($in{"ACTION"} eq "affiliate_add")
{  $vars{affiliatepage} = 'Yes';
   &member_add;
} 
# Infinex function - display signup member page
elsif ($in{"ACTION"} eq "infinex_signup_member")
{ $vars{sc_cookie}="Set-Cookie:gtaffid=$in{strEmail};path=/\n";        # Aaron
  print "$vars{sc_cookie}\n\n";
  $vars{affnumber} = 'A1001';
  $vars{loginid} = 'infinex';
  $vars{password} = $in{strPassword};
  &calendar_error_msg('','inf_800_signup_html');
}
elsif ($in{"ACTION"} eq "infinex_signup_affiliate") 
{ print "\n";
  $vars{affnumber} = 'A1001';
  $vars{loginid} = 'infinex';
  $vars{password} = $in{strPassword};
  &calendar_error_msg('','inf_aff_signup_html');
}
else
{ # Logout
  if ($in{"ACTION"} eq "logout")
  { &logout;
  }
# Member update their personal profile
  if ($in{"ACTION"} eq "member_update")
  { &member_update;
  }
  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 "edit_country")
        { $vars{edit_country} = "Yes";
          &edit_event;
        }
elsif ($in{"ACTION"} eq "add_event") # by Aaron
        { &add_event;
        }
elsif ($in{"ACTION"} eq "add_country") # by Aaron
        {   $vars{add_country} = "Yes";
            &add_event;
        }
# 800 number signup step1 by Aaron
elsif ($in{"ACTION"} eq "vip_signup")
        {   &calendar_error_msg('','signup_selectcountry_html'); 
        }
# 800 number signup step2 by Aaron
elsif ($in{"ACTION"} eq "signup_800num")
        {  &vip_signup_step_1;
           &generate_phone_num($in{countrynumber});
           $vars{countrynumber} = $in{countrynumber}; 
           &calendar_error_msg('','vip_signup_html'); 
        }
# Virtual Office Signup by Aaron
elsif ($in{"ACTION"} eq "vo_signup")
        {  &generate_phone_num; 
           &calendar_error_msg('','vo_signup_html'); 
        }
# Signup for different package (working but postponed) by Aaron
elsif ($in{"ACTION"} eq "vip_signup_1")
        {  &calendar_error_msg('','signup_html'); 
        }
# Signup for 800 number by affiliate after affiliate login - step1
elsif ($in{"ACTION"} eq "aff_signup_800_step_1")
        {  &aff_signup_800_step_1; 
           &generate_phone_num($in{countrynumber});
           $vars{countrynumber} = $in{countrynumber};
           $vars{strInfMemPasswd} = $in{strInfMemPasswd};
           if ($in{strEmail} eq 'infinex')
           { &calendar_error_msg('','inf_800_signup_1_html');
           }
           else
           { &calendar_error_msg('','aff_800_signup_1_html');
           }           
        }
# Signup for 800 number by affiliate after affiliate login - step2
elsif ($in{"ACTION"} eq "aff_signup_800_step_2")
        {  &aff_signup_800_step_1;
           &aff_signup_800_step_2;
        }           
elsif ($in{"ACTION"} eq "goto_service") # by Aaron
        { &goto_service($in{service}); 
	}
elsif ($in{"ACTION"} eq "goto_service_1") # by Aaron
        { &goto_service_1; 
	}
# search member's locator
elsif ($in{"ACTION"} eq 'search_visitor') # by Aaron
        {   &goto_page('calendar_visitorsearch.html'); #Aaron
        }
# Display 3way conference call page
elsif ($in{"ACTION"} eq "3way") # by Aaron
        {   &goto_page('3way.html'); #Aaron
        }
# Display UM page
elsif ($in{"ACTION"} eq "um") # by Aaron
        { &member_login(um); 
#	&goto_page('um.html');
        }
# Display mytravel frontpage
elsif ($in{"ACTION"} eq "travel") # by Aaron
        { &front_page;
        }
# Billing function - update member account
elsif ($in{"ACTION"} eq "billing_update")
        { &check_officer_password;
          if($in{strPaymentHistory} ne '')
          { $vars{strForwardTo} = $in{strForwardTo};
            $vars{strMemberID} = $in{strMemberEmail};
            $vars{strGTAffID} = $in{strGTAffID};
            &calendar_error_msg('','payment_history_html');
          }
          else
          { &billing_update;
            &calendar_error_msg('','billing_html'); #Aaron
          }
        }
# Member upgrade from basic package to get a 800 number
elsif ($in{"ACTION"} eq "member_upgrade")
        { &member_upgrade;
        }
elsif ($in{"ACTION"} eq "member_upgrade_step_1")
        { &member_upgrade_step_1;
          &calendar_error_msg('','member_upgrade_step1_html');
        }
elsif ($in{"ACTION"} eq "member_upgrade_step_2")
        {  &generate_phone_num($in{countrynumber});
           $vars{countrynumber} = $in{countrynumber};           
           &member_upgrade_step_1;
           &member_upgrade_step_2;           
        }
# Member update their forward to number
elsif ($in{"ACTION"} eq "followme_update")
        { &followme_num_update;
        }
elsif ($in{"ACTION"} eq "followme_update_1")
        { if ($in{strRowNumber} ne '' || $in{RowNumber} ne '')
          { $in{Page}="update_gtf_html";
            $in{login}= "MoreRows";
            $vars{strRowNumber} = $in{strRowNumber};
            &member_login($in{login});
          }
          else
          { &followme_num_update_1;
          }
        }
# Member update their callback accesing number (DID)
elsif ($in{"ACTION"} eq "callback_update")
        { &callback_num_update;
        }
# Member add calling time to thier account
elsif ($in{"ACTION"} eq "add_calling_time")
        { &add_calling_time;
        }
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;
        }
# Create Phone Book file after new member signup
elsif ($in{"ACTION"} eq "create_phonebook")#Aaron   
        { &create_phonebook;
        }
# Display Destination service page (hidden)
elsif ($in{"ACTION"} eq "destination")#Aaron
        { &display_destination_services;
        }
# Import Outlook Express File to phone book (not test)(hidden) 
elsif ($in{"ACTION"} eq "import")#Aaron
        { &upload_outlook_files;
        }
# Admin function - check 800 numbers and display a list
elsif ($in{"ACTION"} eq "check_800_num")
        { &check_officer_password;
          &check_800_num;
        }
# Admin function - check 800 numbers and display a detail report on 1 account
elsif ($in{"ACTION"} eq "billing_display_800_detail")
        { &check_officer_password;
          $vars{billingdetail} = "Yes";
          &check_800_num;
        }
# Admin function - modify 800 number info
elsif ($in{"ACTION"} eq "modify_800_num")
        { &check_officer_password;
          &modify_800_num;
        }
# Admin function - add 800 number to the list of the 800 number file
elsif ($in{"ACTION"} eq "add_800_num")
        { &check_officer_password;
          &add_800_num;
        }
# Admin function - view all member's info
elsif ($in{"ACTION"} eq "check_members")
        { &check_officer_password;
          $vars{loginid} = $in{strEmail};
          $vars{password} = $in{strPassword};
          &calendar_error_msg('','admin_member_html'); #by Aaron
        }
# Admin function - view all affiliate's info
elsif ($in{"ACTION"} eq "check_affiliate")
        { &check_officer_password;
          &calendar_error_msg('','admin_affiliate_html');
        }
# Admin function - view affiliate detail info
elsif ($in{"ACTION"} eq "admin_affiliate_detail")
        { &check_officer_password;
          $vars{strAffNumber} = $in{strAffNumber};
          &calendar_error_msg('','admin_affiliate_detail_html');
        }
# Display the link method page for affiliate
elsif ($in{"ACTION"} eq "aff_show_banner") #Aaron
        {  $vars{loginid} = $in{strEmail};
           $vars{firstname} = $in{strFirstName};
           $vars{affnumber} = $in{strAffNumber};
           &calendar_error_msg('','aff_banner_html');
        }
# Affiliate update thier record
elsif ($in{"ACTION"} eq "affiliate_update") #Aaron
        { $vars{loginid} = $in{strEmail};
          &affiliate_update;
        }
# Billing function - process account through cybercash (not done)
elsif ($in{"ACTION"} eq "cybercash")
        { &check_officer_password;
          &send_info_to_cybercash;
        }
# Billing function - Generate billing statement file
elsif ($in{"ACTION"} eq "billing_statement")
        { &check_officer_password;
          &bill_member;
        }
# Billing function - View list of monthly bill statement 
elsif ($in{"ACTION"} eq "check_monthly_bill")
        { &check_officer_password;
          &check_monthly_bill;   
        }
# Billing function - View a monthly bill statement detail 
elsif ($in{"ACTION"} eq "check_monthly_bill_detail")
        { &check_officer_password;
          &check_monthly_bill_detail;   
        }
# Billing function - View 800 PTF activity 
elsif ($in{"ACTION"} eq "billing_800_activity")
        { &check_officer_password;
          &calendar_error_msg('',$in{'Page'});   
        }
# Billing function - View 800 charge rates 
elsif ($in{"ACTION"} eq "billing_800_charge_rates")
        { &check_officer_password;
          &calendar_error_msg('',$in{'Page'});   
        }
# Infinex function - check 800 numbers and display a detail report on 1 account
elsif ($in{"ACTION"} eq "infinex_display_800_detail")
        { &check_officer_password;
          $vars{billingdetail} = "Yes";
          &check_800_num;
        }
# Infinex function - update member account
elsif ($in{"ACTION"} eq "infinex_update")
        { &check_officer_password;
          &billing_update;
          &calendar_error_msg('','infinex_html'); #Aaron
        }
# Display affiliate login page which only to the special deal page
elsif ($in{"ACTION"} eq "special_deal_login_index")
        { $vars{affid} = $in{affid};
          &calendar_error_msg('','special_deal_index'); #Aaron
        }
# Display affiliate login page which only to the special deal page
elsif ($in{"ACTION"} eq "special_deal_login")
        { $vars{affid} = $in{affid};
          &calendar_error_msg('','special_deal_login_html'); #Aaron
        }
# Display time zone popup
elsif ($in{"ACTION"} eq "time_zone")
        {# &calendar_error_msg('','billing_time_zone_html'); 
          &calendar_error_msg('',$in{'Page'});   
        }
# Display my travel front page
elsif ($in{"ACTION"} eq "DISPLAY")#Aaron
        { &DISPLAY;
        }
# Display Login Page
else { &calendar_error_msg('','mytravel_login_html'); #by Aaron
	}
}
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("<li>GetCwd[01]: 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'});}
 else {&Error("<li>ReadParse[01]: Can't Read And Parse");}
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/^ +//g; 
  $val =~ s/\n+//g;  
  $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/^\s+//g;           # remove leading spaces
   $val =~ s/\s+$//g;           # remove trailing spaces
   $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&password=$in{password}&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("<li>read_config[01]: 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>[AA01]: Base Directory (\$base_dir): $base_dir
		<li>[AA02]: Template Directory (\$template_dir): $template_dir
		<li>[AA03]: Calendar Events File (\$calendar_file): $calendar_file
		<li>[AA04]: Current Calendar Template (\$calendar_html): $calendar_html
		<li>[AA05]: 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>[AA06]: The base directory does not exist\n"; }
	unless (-e $calendar_file) { print "<li>[AA07]: The calendar events file does not exist\n"; }
	unless (-w $calendar_file) { print "<li>[AA08]: The calendar events file is not world-writeable (chmod 777)\n"; }
	unless (-d $template_dir) { print "<li>[AA09]: The Template directory does not exist\n"; }
	unless (-e $calendar_html) { print "<li>[AA10]: The calendar template file does not exist\n"; }
	unless (-w $calendar_html) { print "<li>[AA11]: The calendar template file is not world-writeable (chmod 777)\n"; }
	unless (-e $viewday_html) { print "<li>[AA12]: The view day template file does not exist\n"; }
	unless (-w $viewday_html) { print "<li>[AA13]: 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("<li>load_template[01]: 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;
  my($zkey,$zpgm,$ztemplate);
  my($zpattern1,$zpattern2);

  &set_date_values;                    # set date values routine jimlum
#  ###################################################################
#  # 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%> template string <%/TAG%>    by jimlum@infinex.com
  # 
  # TAG is the name of a perl subroutine.
  # The TAG subroutine can process the template string and repeat it
  # as many times as needed ... while replacing variables.
  # The resulting string should be returned and will replace the 
  # <%TAG%> template string <%/TAG%> in the master string.
  #
  # Example:
  # sub TAG
  # { my($xtemplate,%xhash)=@_;                     # input args
  #   my($zrec,$zkey,$zresult,%zhash);              # internal variables
  #
  #   $zresult='';                                  # reset output
  #   foreach $zrec (@somelist)                     # subset of db entries
  #   { foreach $zkey (@dbstruct)                   # db structure
  #     { ($zhash{$zkey},$zrec)=split(/\|/,$zrec,2);# hash of db subset
  #     }
  #     %zhash=(%xhash,%zhash);                     # merge hashes
  #     $zresult.=$xtemplate;                       # concat template to result
  #     foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
  #     { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
  #       $zresult =~ s/<%=$zkey%>/$zhash{$zkey}/g; # replace with value
  #     }
  #   }                                             # next subset db entry
  #   return($zresult);                             # return result
  # }
  #
  ###################################################################
   foreach $zpgm ($template =~ /<%.*?%>/g)
   { $zpgm=substr($zpgm,2,length($zpgm)-4);
     next if(substr($zpgm,0,1) eq '=' || substr($zpgm,0,1) eq '/');
   $template =~ s/<%$zpgm%>(.*?)<%\/$zpgm%>/&$zpgm($1,%vars);/sge;
   }
  ###################################################################
  # old original code.
  ###################################################################
# foreach $zkey (sort keys %$data)
# {
#   if (defined ${$data}{$zkey})
#   {
#     $template =~ s|<%$zkey%>(.+?)<%/$zkey%>|
#       my($tmp2) = $1;
#       $tmp2 =~ s!<%=VALUE%>!${$data}{$zkey}!s;
#       "$tmp2";
#     |esgx;
##    $template =~ s|<%$zkey%>(.+?)<%/$zkey%>|${data}{$zkey}|esgx;
#   }
#   else
#   { $template =~ s|<%$zkey%>(.*?)<%/$zkey%>||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;
  ###################################################################
  # process select option fields
  ###################################################################
  foreach $zkey (@gtSelect)
  { $zpattern1="option value=\"${$data}{$zkey}\"";
    $zpattern2=$zpattern1.' SELECTED';
    $template =~ s/$zpattern1/$zpattern2/ig;
  }
  ###################################################################
  # Pass back parsed template
  ###################################################################
  return $template;
}
#####################################################################
# process city/phone locations
# template lines from parse_template routine.
#####################################################################
sub city_loc_phone
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables

  $zresult='';                                  # reset output
  $zu_loc=$xhash{u_loc}.':#:#';
  ($zcityphone,$zu_loc)=split(/:/,$zu_loc,2);   # skip first entry
  $xhash{ii}=1;                                 # start at 2
  while ($zu_loc ne '')
  { $xhash{ii}++;
    ($zcityphone,$zu_loc)=split(/:/,$zu_loc,2); # next city/phone group
    ($xhash{uu_city},$xhash{uu_phone})=split(/#/,$zcityphone,2);
    $zresult.=$xtemplate;                       # concat template to result
    foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
    { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
      $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
    }
  }                                             # next subset db entry
  return($zresult);                             # return result
}
#####################################################################
# process extension rows - Aaronzzz
# template lines from parse_template routine.
#####################################################################
sub extensions
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables

  $zresult='';                                  # reset output
  $zu_ext=$xhash{strGTFExtension};
  $zu_follow=$xhash{strFollowme};
  if ($in{strRowNumber} ne '')
  { for ($zii=1; $zii<=$in{strRowNumber}; $zii++)
    { $xhash{ii}++;
      ($xhash{uu_ext},$zu_ext)=split(/\#/,$zu_ext,2);
      ($xhash{uu_num},$zu_follow)=split(/\#/,$zu_follow,2);
      $zresult.=$xtemplate;                       # concat template to result
      foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
      { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
        $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
      }
     }
  }
  else
  { $xhash{ii}=0;                                 # start at 1
    while ($zu_ext ne '')
    { $xhash{ii}++;
      ($xhash{uu_ext},$zu_ext)=split(/\#/,$zu_ext,2);
      ($xhash{uu_num},$zu_follow)=split(/\#/,$zu_follow,2);
      $zresult.=$xtemplate;                       # concat template to result
      foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
      { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
        $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
      }
    }                                             # next subset db entry
  }
  return($zresult);                             # return result
}
#####################################################################
# Admin function to show 800 number list - Aaronzzz
# template lines from parse_template routine.
#####################################################################
sub show_800_numbers
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables

  $zresult='';                                  # reset output
  if(!open(PHONEL,"<$xhash{phone_list_file}"))
  { &Error("<li>show_800_numbers[01]: Can't open $xhash{phone_list_file} file for read!");
    exit;
  }
  @zphonelist=<PHONEL>;
  close(PHONEL);
  $xhash{ii}=0;                                 # start at 1
  foreach $zrec (@zphonelist)
  { chomp ($zrec);
    ($xhash{uu_800_num},$xhash{uu_owner},$zjunk) = split (/,/,$zrec,3);
    if ($xhash{uu_owner} eq '')
    { $xhash{uu_owner} = '&nbsp;';
    }
    if ($in{search800} eq '' || $xhash{uu_800_num} =~ /^$in{search800}/g)
    { $zresult.=$xtemplate;                       # concat template to result
      foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
      { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
        $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
      }
      $xhash{ii}++;
    }
  }
  return($zresult);                             # return result
}
#####################################################################
# Admint function to display member list - Aaronzzz
# template lines from parse_template routine.
#####################################################################
sub show_members
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables

  $zresult='';                                  # reset output
  if(!open(MEML,"<$vars{member_file}"))
  { &Error("<li>show_members[01]: Can't open $vars{member_file} file for read!");
    exit;
  }
  @zmemlist=<MEML>;
  close(MEML);
  $xhash{ii}=0;                                 # start at 1
  foreach $zrec (@zmemlist)
  { chomp ($zrec);
    foreach $zfield (@gtMemDB)
    { $zfield1 = 'u'.$zfield;
      ($xhash{$zfield1},$zrec) = split(/\|/, $zrec, 2);
    }
    if ($in{searchmember} eq '' || $xhash{uu_userid} =~ /^$in{searchmember}/g)
    { $zresult.=$xtemplate;                       # concat template to result
      foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
      { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
        $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
      }
      $xhash{ii}++;
    }
  }
  return($zresult);                             # return result
}
#####################################################################
# Admin function to show 800 number list - Aaronzzz
# template lines from parse_template routine.
#####################################################################
sub affiliate_check_commission
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables

  $zresult='';                                  # reset output
  if(!open(MEM,"<$xhash{member_file}"))
  { &Error("<li>affiliate_check_commission[01]: Can't open $xhash{member_file} file for read!");
    exit;
  }
  @zmemlist=<MEM>;
  close(MEM);
  $xhash{ii}=0;                                 # start at 1
  foreach $zrec (@zmemlist)
  { chomp ($zrec);
    $ztmp = $zrec;
    #################################################################
    # put member data into gtuv hash
    #################################################################
    foreach $zkey (@gtMemDB)
    { ($gtuv{$zkey},$ztmp)=split(/\|/,$ztmp,2);
    }
    if (($in{strGTAffID} eq $xhash{u_gtaffid}) 
        && ($in{searchMonth} eq '' || $xhash{u_signupdate} =~ /^$in{searchMonth}/g))
    { $zresult.=$xtemplate;                       # concat template to result
      foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
      { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
        $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
      }
      $xhash{ii}++;
    }
  }
  return($zresult);                             # return result
}
#####################################################################
# process phone cards
# template lines from parse_template routine.
#####################################################################
sub phone_cards
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zii,$zu_pcp,$zpcp,$zkey,$zresult);        # internal variables

  $zresult='';                                  # reset output
  $zu_pcp=$xhash{u_pcp}.':##:##';               # add two null entries
  $zii=0;                                       # start at 1
  while ($zu_pcp ne '')
  { $zii++;                                     # next phone card
    $xhash{ii}=$zii;
    ($zpcp,$zu_pcp)=split(/:/,$zu_pcp,2);       # next phone card
    ($xhash{uu_pcp_type},$xhash{uu_pcp_num},$xhash{uu_pcp_pin})=split(/#/,$zpcp,3);
    $zresult.=$xtemplate;                       # concat template to result
    foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
    { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
      $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
    }
  }                                             # next subset db entry
  return($zresult);                             # return result
}
#####################################################################
# 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;
	}
#####################################################################
# send an email
#####################################################################
sub send_email
{ my($xto,$xbodyfn,%xmrg)=@_;

  my($zfn,$ztemplatedir);
  my($zrec,$zkey,$zjunk);
  my(@zemail,$zcc,$zbcc,$zsubj,$zbody);

  ###################################################################
  # Get the email message template
  ###################################################################
  if(!open(EMAILFN,"<$xbodyfn"))
  { &Error("<li>send_email[01]: Unable to read <b>$xbodyfn</b> to send an email.\n");
      exit(0);
  }
  @zemail=<EMAILFN>;
  close(EMAILFN);
  ###################################################################
  # Fill in the email message template
  ###################################################################
  $zcc ='';
  $zbcc ='';
  $zsubj='';
  $zbody='';
  foreach $zrec (@zemail)
  { chomp($zrec);
    foreach $zkey ($zrec =~ /<%=.*?%>/g)
    { $zkey=substr($zkey,3,length($zkey)-5);
      $zrec =~ s/<%=$zkey%>/$xmrg{$zkey}/g;
    }
    if($zrec =~ /^subject:/i)
    { ($zjunk,$zsubj)=split(/:/,$zrec,2);
      next;
    }
    if($zrec =~ /^cc:/i)
    { ($zjunk,$zcc)=split(/:/,$zrec,2);
      next;
    }
    if($zrec =~ /^bcc:/i)
    { ($zjunk,$zbcc)=split(/:/,$zrec,2);
      next;
    }
    $zbody .= "$zrec\n";
  }
  ###################################################################
  # Check to see if the cc is formatted correctly
  ###################################################################
  if(index($zcc,',') == 0)
  { $xcc=substr($zcc,1);            # remove leading comma
  }
  ###################################################################
  # Check to see if the bcc is formatted correctly
  ###################################################################
  if(index($zbcc,',') == 0)
  { $zbcc=substr($zbcc,1);          # remove leading comma
  }
  if($xbcc ne ''
   &&$gt_bcc ne '')
  { $zbcc .= ",$gt_bcc";      # append non-null common bcc
  }
  else
  { $zbcc .= $gt_bcc;         # all other cases
  }
  ###################################################################
  # Send the email
  ###################################################################
  if(!open (MAIL, "|$gt_send_mail"))
  { &Error("<li>send_email[02]: Unable to open <b>$gt_send_mail</b> to send an email.\n");
      exit(0);
  }
  print MAIL <<__END_OF_MAIL__;
To: $xto
From: $gt_from
Cc: $zcc
Bcc: $zbcc
Subject: $zsubj

$zbody

__END_OF_MAIL__

}
#####################################################################
# DISPLAY()
#
# Display the calendar
#####################################################################
sub DISPLAY {
        $vars{strEmailAddress} = $in{strEmailAddress};
	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{eventkey} eq '')   #Aaron
        { $vars{eventkey}=$in{eventkey};
        }
	#$vars{password}=$in{password};
	if($vars{password} eq '')
	{
        if($in{password} ne '')
        {$vars{password}=$in{password};
        }
        else
        {$vars{password}=$in{strPassword};
        }
	}
        if($in{password} ne '')
        {$vars{password}=$in{password};
        } 
	&read_cal_data;
	&set_date_values;            # moved to sub routine by jimlum

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

        &date_choice;    # allow user to select a date

	# 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};
			$vars{bgcolor1} = $vars{bgcolor_today};
			$vars{bgcolor2} = $vars{bgcolor_day};
       			}
		elsif ( $vars{current_day} == $vars{date} ) {
			$vars{bgcolor} = $vars{bgcolor_current};
			$vars{bgcolor1} = $vars{bgcolor_day};
			$vars{bgcolor2} = $vars{bgcolor_current};
			}
		else { $vars{bgcolor} = $vars{bgcolor_day};
			$vars{bgcolor1} = $vars{bgcolor_day};
			$vars{bgcolor2} = $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  - AARON
                if ($in{config} eq 'calendar2-Latin1.cfg')
                { $vars{event_labels} = "Location";
                }
                else
                { $vars{event_labels} = "<a href=https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=calendar-Latin1.cfg&ACTION=add_country&firstname=$vars{firstname}&loginid=$vars{loginid}&password=$vars{password}&member_login=y&ehour=99&shour=99&Date=$vars{current_day}&Month=$vars{month}&Year=$vars{year}>Location</a>";
                }
		foreach $i ( sort keys %{$events{$xdatestamp}} ) {
# jxl-events		$vars{event_labels} .= "$events{$xdatestamp}{$i}{label}<br>\n";
                        if ($events{$xdatestamp}{$i}{label} eq 'Location' && $events{$xdatestamp}{$i}{description} eq 'Location')
                        { if ($in{config} eq 'calendar2-Latin1.cfg')
                          { $vars{event_labels} = "$events{$xdatestamp}{$i}{location}";
                          }
                          else
                          { $vars{event_labels} = "<a href=https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=calendar-Latin1.cfg&ACTION=edit_country&member_login=y&id=$events{$xdatestamp}{$i}{id}&loginid=$vars{loginid}&password=$vars{password}&firstname=$vars{firstname}&Month=$vars{month}&Date=$vars{current_day}&Year=$vars{year}>$events{$xdatestamp}{$i}{location}</a>";
                          }
                          if (($vars{year} == $year) && ($vars{month} == $month) && ($vars{current_day} == $mday))
                          {  $vars{bgcolor2} = $vars{bgcolor_detail};
                          }
                          elsif ( $vars{current_day} == $vars{date} )
                          { $vars{bgcolor2} = $vars{bgcolor_current};
                          }
                          else
                          { $vars{bgcolor2} = $vars{bgcolor_detail};
                          }
                        }
#			$vars{event_labels} .= "$events{$xdatestamp}{$i}{label} <font color=\"red\">$events{$xdatestamp}{$i}{eventkey}</font><br>\n";
                        if (($vars{year} == $year) && ($vars{month} == $month) && ($vars{current_day} == $mday))
                        {  $vars{bgcolor1} = $vars{bgcolor_today};
                        }
                        elsif ( $vars{current_day} == $vars{date} )
                        { $vars{bgcolor1} = $vars{bgcolor_current};
                        }
                        else
                        { $vars{bgcolor1} = $vars{bgcolor_detail};
                        }
	        }
		$vars{event_labels} .= "&nbsp;\n";
#		if ($total_events{$xdatestamp} < 1) {
#			$vars{event_labels} .= "&nbsp" x (1-$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;</p></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
#####################################################################
# fields to allow a user to select a date   made into a subb routine by jimlum
#####################################################################
sub set_date_values
{
	# Get next and last months
	# ------------------------
	$vars{lastyear}  = $vars{year};
	$vars{nextyear}  = $vars{year};
        if($vars{Year} eq '')
        { $vars{Year}=$vars{year};
        }
	$vars{lastmonth} = $vars{month}-1;
	$vars{nextmonth} = $vars{month}+1;
        if($vars{Month} eq '')
        { $vars{Month}=$vars{month};
        }
	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];
        if($vars{thismonth_name} eq '')
        { $vars{thismonth_name}=$months[$vars{month}-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}";

}
#####################################################################
# fields to allow a user to select a date   made into a subb routine by jimlum
#####################################################################
sub date_choice
{
	# Last/Next month button
	# --------------------------
	$vars{'select_last_month'} = "<a href='$vars{cgi}?config=$vars{config}&ACTION=member_login&login=Locator&loginid=$vars{loginid}&firstname=$vars{firstname}&password=$vars{password}&eventkey=$in{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}&ACTION=member_login&login=Locator&loginid=$vars{loginid}&firstname=$vars{firstname}&password=$vars{password}&eventkey=$in{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='ACTION' value='member_login'>\n";
	$vars{'select_month_form'}.= "<input type='hidden' name='login' value='Locator'>\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='$in{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>';

}
#####################################################################
# 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_date
#####################################################################
#
# DO_ADD()
#
# Add an entry
#
#####################################################################
sub DO_ADD {	
	my($zmsg);
        my ($zloc, $zpnum);
	&read_cal_data;
	$zmsg='';
        if($in{Month} < 1 || $in{Month} > 12)
        { $zmsg.="<li>[AB00]: <b>Month</b> must be from 1 to 12.\n";
        }
        if($in{Date} < 1 || $in{Date} > 31)
        { $zmsg.="<li>[AB01]: <b>Month</b> must be from 1 to 31.\n";
        }
        if($in{Year} < 2000 || $in{Year} > 2999)
        { $zmsg.="<li>[AB02]: <b>Year</b> must be greater than 2000 and less than 3000.\n";
        }
        if(($in{Dur_time} < 1 || $in{Dur_time} > 14) && $in{Dur_time} ne '')
        { $zmsg.="<li>[AB03]: <b>Event Duration</b> must be within 2 weeks (1-14 days).\n";
        }
	if($in{heading} eq '')
        { $zmsg.="<li>[AB04]: <b>Heading</b> is required.\n";
        }
        if (($in{shour} eq '-' && $in{ehour} ne '-') || ($in{ehour} eq '-' && $in{shour} ne '-'))
        { $zmsg.="<li>[AB05]: Both <b>Start Time</b> and <b>End Time</b> must be entered\n";
        }
        if ($in{shour} > $in{ehour})
        { $zmsg.="<li>[AB06]: <b>Start Time</b> cannot be later than <b>End Time</b>\n";
        }
        if($in{description} eq '')
        { $zmsg.="<li>[AB07]: <b>Description</b> is required.\n";
        }
#        if($in{location} eq '')
#        { $zmsg.="<li>[AB08]: <b>Location</b> is required.\n";
#        }
        if ($in{Dur_time} eq '' && $in{Duration_Range} ne '')
        { $in{Dur_time} = $in{Duration_Range};
        }
        elsif ($in{Dur_time} eq '' && $in{Duration_Range} eq '')
        { $in{Dur_time} = 1;
        }
        $in{phonenum} =~ s/ +//g;            # remove spaces
        $in{phonenum} =~ s/-+//g;            # remove dashes
        $in{phonenum} =~ s/\(+//;           # remove left parenthesis
        $in{phonenum} =~ s/\)+//;           # remove right parenthesis
        $in{phonenum} =~ s/\.+//;           # remove period 
        ($zloc, $zpnum) = split (/\|/, $in{pro_location}, 2);
        if ($in{location} eq '' && $in{phonenum} eq '' && $zloc ne '')
        {  $in{location} = $zloc;
           $in{phonenum} = $zpnum;
        }                 
        &get_variable;
       
        ##########################################
        #  Check login id and password
        ##########################################
        $zret=&member_get($in{strEmail},'');
        if($zret == 1)
        { close(MEMLK);
          $zmsg .= "<li>[AB09]: Email address (login id), <b>$in{strEmail}</b>, not found in our database.\n";
        }
        else
        {
           if((crypt($vars{password},$in{password}) ne $in{password}) || $in{password} eq '')
           { close(MEMLK);
             $zmsg.="<li>[AB10]: Email address, (login id), <b>$in{loginid}</b>  and password not found in our database.\n";
           }
        }
        #End Checking

	$in{description} =~ s|[\r\n]+|<BR>|gs;
	$sMonth = $in{sMonth};
	$in{Month} =~ s|^(\d)$|0$1|;
        $in{Date}  =~ s|^(\d)$|0$1|;
        my $datestamp = $in{Year} . $in{Month} . $in{Date};
        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);
        }
        &PerpetualCalendar($in{Month},1,$in{Year});
        $newyear = $in{Year};     
        $newmonth = $in{Month};   
        $newdate = $in{Date};
        for ($xii=1; $xii<=$in{Dur_time}; $xii++)
        {
	  if ($datestamp =~ /^\d\d\d\d\d\d\d\d$/)
          {     open(OUT,">> $vars{calendar_file}")
                || &Error("<li>DO_ADD[01]: 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{location}|$in{shour}|$in{ehour}\n";  #Aaron
		close(OUT);
                if ($newdate >= $perp_eom)
                {  if ($newmonth == 12)
                   { $newyear = $in{Year} + 1;
                     $newyear =~ s|^(\d)$|0$1|;
                     $newmonth = 1;
                     $newmonth =~ s|^(\d)$|0$1|; 
                   }
                   else
                   { $newyear= $in{Year};
                     $newmonth = $in{Month} + 1;
                     $newmonth =~ s|^(\d)$|0$1|;
                   }
                   $newdate = 1;
                   $newdate =~ s|^(\d)$|0$1|; 
                }
                else
                { $newdate = $newdate + 1;
                  $newdate =~ s|^(\d)$|0$1|;
                }
                $datestamp = $newyear . $newmonth . $newdate;
                $vars{new_id}++;
	  }
	  else { &Error("<li>DO_ADD[02]: error"); }	
	}
#aaronx
        #############################################################
        #  Modify member profile for location and moblie number
        #############################################################
        $znewloc = 0;
        if (($in{location} ne '$zloc' || $in{phonenum} ne '$zpnum') && $in{location} ne '')
        { $znewloc = 1;
          @memberlist = '';
          open (MEMLK, "$vars{member_file}") ||
           &file_open_error("$vars{member_file}",
                    "Member profile", __FILE__, __LINE__);
          @memberlist = <MEMLK>;
          close (MEMLK);
          foreach $zrec (@memberlist)
          { $ztmp=$zrec;
            chomp $ztmp; 
          foreach $zkey (@gtMemDB)
           { ($gtuv{$zkey},$ztmp)=split(/\|/,$ztmp,2);
             $gtuv{$zkey} =~ s/\n+//g;
          }
           if($gtuv{u_userid} eq $in{loginid})
           { $zii = 1;
             $ztmp = "strLocCity1";
             $ztmp1 = "strLocPhone1";
             $gtuv{u_loc} = '';
             $zupd = 0;
             while($vars{$ztmp} ne '')  # create "location#phonenum" string
             { 
               if ($in{location} ne $vars{$ztmp})
               { $gtuv{u_loc} .= "\:$vars{$ztmp}\#$vars{$ztmp1}";
               }
               elsif ($in{location} eq $vars{$ztmp})
               { $gtuv{u_loc} .= "\:$in{location}\#$in{phonenum}";
                 $zupd = 1;
               }
               $zii++;
               $ztmp = "strLocCity$zii";  
               $ztmp1 = "strLocPhone$zii";
             }
             if ($zupd == 0) #Check whether new location
             { $gtuv{u_loc} .= "\:$in{location}\#$in{phonenum}";
             }
             $gtuv{u_loc}=substr($gtuv{u_loc},1);
             $zmemstr='';
             foreach $zkey (@gtMemDB)
             { $zmemstr .= "|$gtuv{$zkey}";
             }
             $zmemstr=substr($zmemstr,1);
            
            }
           }
          @zmemberlist= '';
          foreach $zfield (@memberlist)
          { $ztmp=$zfield;
           ($zuserid,$zjunk)=split(/\|/,$ztmp,2);
           if($zuserid eq $in{loginid})
           { push(@zmemberlist,"$zmemstr\n");
           }
           else
           { push(@zmemberlist,$zfield);
           }
          }
          @memberlist=sort(@zmemberlist);
          
          if(!open(MEMDB,">$vars{member_file}-tmp"))
          { close(MEMLK);
            &Error("<li>DO_ADD[03]: Can't open $vars{member_file}-tmp file for write!");
          }
             
          print MEMDB @memberlist;
          close(MEMDB);
           
          rename "$vars{member_file}-tmp","$vars{member_file}";
          close(MEMLK);
        }
#	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{simcity} = $in{location};
#        $vars{firstname} =$in{firstname};
#        $vars{lastname}  =$in{lastname};
        if ($zupd == 0 && $znewloc == 1)
        { &calendar_error_msg('','order_sim_html');
        }
        else
        {
	&DISPLAY;
        }
	exit(0);
	} #end of ADD
#####################################################################
#
# VIEWDAY()
#
# Display entries for a single day
#
#####################################################################
sub VIEWDAY {
	&read_cal_data;
        $vars{strEmailAddress} = $in{strEmailAddress};
	if($vars{firstname} eq '')   #Aaron
        { $vars{firstname}=$in{firstname};
        }
	if($vars{loginid} eq '')   #Aaron
        { $vars{loginid}=$vars{strEmailAddress};
        }
	if($vars{eventkey} eq '')   #Aaron
        { $vars{eventkey}=$in{eventkey};
        }
        $vars{member_login} = $in{member_login};
	$vars{password} = $in{password};
	$vars{small_calendar} = &small_calendar2( $vars{month} , $vars{year} , $vars{date} , $vars{strEmailAddress} , $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}");

        my (%zevents); #aaronx
         for ($zi=0; $zi<= $total_events{$vars{datestamp}}; $zi++)
         { if ($events{$vars{datestamp}}{$zi}{label} eq 'Location'
                   && $events{$vars{datestamp}}{$zi}{description} eq 'Location')
           { $vars{event_location} = "<br>Location: $events{$vars{datestamp}}{$zi}{location}";
             $vars{event_phonenum} = "<br>Phone Number: $events{$vars{datestamp}}{$zi}{phonenum}";
           }
           if (($events{$vars{datestamp}}{$zi}{shour} eq '-' || $events{$vars{datestamp}}{$zi}{shour} eq '')
                   && $events{$vars{datestamp}}{$zi}{id} ne '' 
                   && $events{$vars{datestamp}}{$zi}{label} ne 'Location'
                   && $events{$vars{datestamp}}{$zi}{description} ne 'Location')
           { 
             if (crypt($vars{strEmailAddress},$vars{username}) eq $vars{username})
             { $zevents{other} .= "$events{$vars{datestamp}}{$zi}{loginid}<br>";
             }
             if ($in{password} ne '' && $in{config} eq 'calendar-Latin1.cfg')
             {$zevents{other} .= "<a href=https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=$vars{config}&ACTION=edit_event&member_login=$vars{member_login}&id=$events{$vars{datestamp}}{$zi}{id}&loginid=$vars{loginid}&password=$vars{password}&firstname=$vars{firstname}&Month=$vars{month}&Date=$vars{date}&Year=$vars{year}>";}
             $zevents{other} .= "<b>$events{$vars{datestamp}}{$zi}{label}<b>";
             if ($in{password} ne '' && $in{config} eq 'calendar-Latin1.cfg')
             {$zevents{other} .= "</a>";}
             $zevents{other} .= ": $events{$vars{datestamp}}{$zi}{description} <font color=red>$events{$vars{datestamp}}{$zi}{eventkey}</font><br>\n";
             $zevents{other} .= "Location:$events{$vars{datestamp}}{$zi}{location} Phone Number:\n";
               if ($in{password} eq '' || $in{config} ne 'calendar-Latin1.cfg')
               { $zevents{other} .= "<a href=\"/cgi-bin/calendar/calendar-Latin1.pl?config=calendar2-Latin1.cfg&ACTION=pctophone&loginid=$vars{strEmailAddress}&phonenum=$events{$vars{datestamp}}{$zi}{phonenum}\">$events{$vars{datestamp}}{$zi}{phonenum}</a><br>\n";
                 if ($vars{cookievalue} eq '')
                 { $zevents{other} .= "Email: <a href=mailto:$events{$vars{datestamp}}{$zi}{loginid}>$events{$vars{datestamp}}{$zi}{loginid}</a><br>";}
                 else
                 { $zevents{other} .= "Email: <a href=mailto:$events{$vars{datestamp}}{$zi}{loginid}>$events{$vars{datestamp}}{$zi}{loginid}</a><br>";}
                    #$zevents{other} .= "Email: <a href=\"https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=calendar-Latin1.cfg&ACTION=goto_service&service=../compose.html&firstname=$in{firstname}&loginid=$vars{strEmailAddress}&password=$in{password}&sendto=$events{$var{datestamp}}{$zi}{loginid}\" target=\"main\" onClick=setTimeout('window.close()',500)>$events{$vars{datestamp}}{$zi}{loginid}</a><br\n";}
               }
               else
               { $zevents{other} .= "$events{$vars{datestamp}}{$zi}{phonenum}<br>\n";}                                 
                    #aaronz
           }
           for ($zii=0; $zii<24; $zii++)
           { 
             if ($events{$vars{datestamp}}{$zi}{shour} <= $zii && $events{$vars{datestamp}}{$zi}{ehour} > $zii)
             { 
               if (crypt($vars{strEmailAddress},$vars{username}) eq $vars{username})
               { $zevents{$zii} .= "$events{$vars{datestamp}}{$zi}{loginid}<br>";
               }
               if ($in{password} ne '' && $in{config} eq 'calendar-Latin1.cfg')
               {$zevents{$zii} .= "<a href=https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=$vars{config}&ACTION=edit_event&member_login=$vars{member_login}&id=$events{$vars{datestamp}}{$zi}{id}&loginid=$vars{loginid}&password=$vars{password}&firstname=$vars{firstname}&Month=$vars{month}&Date=$vars{date}&Year=$vars{year}>";}
               $zevents{$zii} .= "<b>$events{$vars{datestamp}}{$zi}{label}</b>";
               if ($in{password} ne '' && $in{config} eq 'calendar-Latin1.cfg')
               {$zevents{$zii} .= "</a>";}
               $zevents{$zii} .= ": $events{$vars{datestamp}}{$zi}{description} <font color=red>$events{$vars{datestamp}}{$zi}{eventkey}</font><br>\n";
               $zevents{$zii} .= "Location:$events{$vars{datestamp}}{$zi}{location} Phone Number:";
               if ($in{password} eq '' || $in{config} ne 'calendar-Latin1.cfg')
               { $zevents{$zii} .= "<a href=\"/cgi-bin/calendar/calendar-Latin1.pl?config=calendar2-Latin1.cfg&ACTION=pctophone&loginid=$vars{strEmailAddress}&phonenum=$events{$vars{datestamp}}{$zi}{phonenum}\">$events{$vars{datestamp}}{$zi}{phonenum}</a><br>\n";
                 if ($vars{cookievalue} eq '')
                 { $zevents{$zii} .= "Email: <a href=\"mailto:$events{$vars{datestamp}}{$zi}{loginid}\">$events{$vars{datestamp}}{$zi}{loginid}</a><br>";
                 }
                 else
                 { $zevents{$zii} .= "Email: <a href=\"mailto:$events{$vars{datestamp}}{$zi}{loginid}\">$events{$vars{datestamp}}{$zi}{loginid}</a><br>"; 
                   # $zevents{$zii} .= "Email: <a href=\"https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=calendar-Latin1.cfg&ACTION=goto_service&service=../compose.html&firstname=$in{firstname}&loginid=$vars{strEmailAddress}&password=$in{password}&sendto=$events{$var{datestamp}}{$zi}{loginid}\" target=\"main\" onClick=setTimeout('window.close()',500)>$events{$vars{datestamp}}{$zi}{loginid}</a><br\n";
                 }
               }
               else
               { $zevents{$zii} .= "$events{$vars{datestamp}}{$zi}{phonenum}<br>\n";}
             }      #aaronz
           }
         }
        $vars{appointment} = '';
        if ($in{start} == '0' && $in{start} ne '')
        { $zstart = 0;
          $zend = 9;
          $vars{start1} = 0;
          $vars{start2} = 9;
        }
        elsif ($in{start} == '18')
        { $zstart = 18;
          $zend = 24;
          $vars{start1} = 9;
          $vars{start2} = 18;
        }
        else
        { $zstart = 9;
          $zend = 18;
          $vars{start1} = 0;
          $vars{start2} = 18;
        }
        for ($zii=$zstart; $zii<$zend; $zii++)
        { #if ($zevents{$zii} ne '')
#          { 
            $ziii = $zii + 1;
            $vars{appointment} .= "<tr><td></td><td valign=TOP><font size=1 face=Arial>";
              if ($in{password} ne '' && $in{config} eq 'calendar-Latin1.cfg')
              { $vars{appointment} .= "<a href=https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=calendar-Latin1.cfg&ACTION=add_event&firstname=$vars{firstname}&loginid=$vars{loginid}&password=$vars{password}&Date=$vars{date}&Month=$vars{month}&Year=$vars{year}&member_login=y&shour=$zii&ehour=$ziii target=main onClick=setTimeout('window.close()',500)>";}
              if ($zii <10)
              { $vars{appointment} .="0$zii:00";}
              else
              { $vars{appointment} .="$zii:00";}
              if ($in{password} ne '' && $in{config} eq 'calendar-Latin1.cfg')
              { $vars{appointment} .= "</a>";}
              $vars{appointment} .= "</font></td>";
              $vars{appointment} .= "<td><font size=1 face=Arial>\n";
            $vars{appointment} .= "$zevents{$zii}\n";
            $vars{appointment} .= "</font></td></tr>\n";    
        }
          $vars{appointment} .= "<tr><td></td><td valign=TOP><font size=1 face=Arial>";
#          if ($in{password} ne '' && $in{config} eq 'calendar-Latin1.cfg')
#          { $vars{appointment} .= "<a href=https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=calendar-Latin1.cfg&ACTION=add_event&firstname=$vars{firstname}&loginid=$vars{loginid}&password=$vars{password}&Date=$vars{date}&Month=$vars{month}&Year=$vars{year}&member_login=y target=main onClick=setTimeout('window.close()',500)>";}
          $vars{appointment} .= "Other";
#          if ($in{password} ne '' && $in{config} eq 'calendar-Latin1.cfg')
#          { $vars{appointment} .= "</a>";}
          $vars{appointment} .= "</font></td>";
          $vars{appointment} .= "<td><font size=1 face=Arial>\n";
          $vars{appointment} .= "$zevents{other}\n";
          $vars{appointment} .= "</font></td></tr>\n";    

	$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, $zlocation, $zehour, $zshour, $zedatestamp;
	$vars{new_id}=0;
	open(IN,"$vars{calendar_file}")
         || &Error("<li>read_cal_data[01]: 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,$zlocation,$zshour,$zehour,$zjunk) = split(/\|/,$_,13); #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 $vars{strEmailAddress}   # matching login id
                         && ($zeventkey eq ''            # no event key
                          || $zeventkey eq $in{eventkey} # matching event key
                            )));
                }
                else
 		{ next unless ($zloginid eq $vars{strEmailAddress} # matching login id
#                          || $zeventkey eq '*'  # public events
                          || crypt($vars{strEmailAddress},$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}}{ehour} = $zehour;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{shour} = $zshour;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{durtime} = $durtime;
		${$events{$xdatestamp}}{$total_events{$xdatestamp}}{location} = $zlocation;
		${$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,$zlocation,$zehour,$zshour,$xedatestamp); #Aaron
  my($ztemplate);

  open(IN,"<$vars{calendar_file}")
   || &Error("<li>edit_event[01]: 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,$zlocation,$zshour,$zehour,$zjunk) = split(/\|/,$zline,13); #Aaron
    if($zid == $in{id})
    { $zmsg='ok';
      last;
    }
  }
  if($zmsg ne 'ok')
  { $zmsg="<li>[AC00]: 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} = $zshour;
  $vars{eHour} = $zehour;
  $vars{location} = $zlocation;
$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};
  if ($vars{edit_country} ne '') 
  { $ztemplate = &load_template("$vars{edit_country_html}");
  }
  else
  { $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("<li>edit_new[01]: Can't open $calendar_file for writing!");
		eval "flock OUT,2";
# jxl event data
		print OUT "$vars{new_id}|$vars{strEmailAddress}|$in{eventkey}|$in{phonenum}|$datestamp|$in{heading}|$in{description}|$in{Dur_time}|$in{Dur_unit}|$in{location}|$in{shour}|$in{ehour}\n"; #Aaron
		close(OUT);
		}
	else { &Error("<li>edit_new[02]: 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("<li>edit_update_delete[01]: 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("edit_update_delete[02]: 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("<li>edit_update_delete[03]: 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}|$in{location}|$in{shour}|$in{ehour}\n"; #Aaron
          }
          $zmsg='ok';
        }
        else
        { print CALFN $zline;
        }
      }
      close(CALFN);
      if($zmsg ne 'ok')
      { $zmsg="<li>[AD00]: 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>[AD01]: $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')
  { if ($in{heading} eq "Location" && $in{description} eq "Location")
    { &DISPLAY;
    }
    else
    { &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}=$vars{strEmailAddress};
  $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,$xemail)=@_;
# my($zmemgrp);
  my($ztmp,$zrec,$zkey,$zii);
  my($zcityphone,$zcity,$zphone);
  my ($zflag) = 1;
# $zmemgrp=substr($xloginid,0,3);

  ###################################################################
  # lock and read the member db
  ###################################################################
  if ($in{"ACTION"} eq 'affiliate_login' || $in{"ACTION"} eq 'affiliate_add' || $in{"ACTION"} eq 'affiliate_update')
  { $zfile = $vars{aff_file};
  }
  else
  { $zfile = $vars{member_file};
  }
  open(MEMLK,">$vars{member_lock}")
   || &Error("<li>member_get[01]: Can't lock $vars{member_lock} file!");
  eval "flock MEMLK,2";
  if(-e "$zfile")
  { if(!open(MEMFN,"<$zfile"))
    { close(MEMLK);
      &Error("<li>member_get[02]: Can't open $zfile file for read!");
      exit;
    }
    @memdata=<MEMFN>;
    close(MEMFN);
  }
  else
  { @memdata=();
  }
  ###################################################################
  # search for the userid
  ###################################################################
  foreach $zrec (sort @memdata)
  { $ztmp=$zrec;
    chomp($ztmp);
    $ztmp1=$ztmp;
    $ztmp1a=$ztmp;
    $zbreak = 0;
    #################################################################
    # put member data into gtuv hash
    #################################################################
    if($in{"ACTION"} eq 'affiliate_login' || $in{"ACTION"} eq 'affiliate_update')
    { foreach $zkey (@gtAffDB)
      { ($gtuv{$zkey},$ztmp)=split(/\|/,$ztmp,2);
      }
    }
    else
    { ($zacctnum, $zloginid, $zpasswd, $zjunk) = split(/\|/, $ztmp1a,4);
      if((($xloginid ne '' && $xloginid eq $zacctnum) || ($xemail ne '' && $xemail eq $zloginid)) 
          && ($zpasswd eq $in{strPassword} || crypt($zpasswd,$in{strPassword}) eq $in{strPassword}))
      { 
        foreach $zkey (@gtMemDB)
        { ($gtuv{$zkey},$ztmp)=split(/\|/,$ztmp,2);
        }
      }
      else
      { $zbreak = 1;
      }
    }
    if ($zbreak == 1)
    { next;
    }
    #################################################################
    # match with requested userid
    #################################################################
    if(  ($xloginid ne '' && $gtuv{u_userid} eq $xloginid)
       || ($xloginid ne '' && $gtuv{aff_userid} eq $xloginid)
       || ($xemail ne '' && $gtuv{u_email} eq $xemail && $xloginid eq ''))
    { $ztmp2 = $ztmp1;
      ###############################################################
      # ensure that city/phone are clear
      ###############################################################
      $zii=0;
      for($zii=1; $zii<=$gtgv{max_city_phones}; $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};
      if(crypt($gtuv{u_passwd},$in{strPassword}) eq $in{strPassword} || $gtuv{u_passwd} eq $in{strPassword})
      { push(@gtuvlist,"$ztmp1\n");
      }
      elsif($gtuv{u_userid} ne '' && $in{strMemberEmail} eq '' && $in{login} ne 'Phonebook1')
      { next;
      }
      if ($zflag == 1)
      { $zflag = 0;
      }
      else
      { $zflag = 2;
      }
      if ($in{strEmail} ne '' || $gtuv{aff_userid} ne '')
      { return(0);
      }
    }
  }
  if ($zflag == 0)
  { foreach $zkey (@gtMemDB)
    { ($gtuv{$zkey},$ztmp2)=split(/\|/,$ztmp2,2);
    }
  }
  return($zflag);                            # not found
}
#####################################################################
# Add a member step 1
#####################################################################
sub member_add_1
{ my($zmsg,$zmem);
  my($zemail,$zpassword,$zfirstname,$zlastname,$zloc,$zjunk);
  my($zfield,$ztmp,$zkeyuv,$zkeyin,$zkeyvar);
  my($zauth_800,$znum,@zext,$zznum,$zextname,$znumname);
  my (@zphonelist);
  if(!open(PHONEL,"<$vars{phone_list_file}"))
  { &Error("<li>member_add_1[01]: Can't open $vars{phone_list_file} file for read!");
    exit;
  }
  @zphonelist=<PHONEL>;
  close(PHONEL);
  ###################################################################
  # check Check Personal Info arguments
  ###################################################################
#  if($in{strFirstName} eq '' || $in{strFirstName} =~ /[^0-9a-zA-Z-. ]/)
  if($in{strFirstName} eq '' )
  { $zmsg .= "<li>[AE00]: Member first name is required and can only contain alphanumeric characters and - and ..\n";
  }
#  if($in{strLastName} eq '' || $in{strLastName} =~ /[^0-9a-zA-Z-. ]/)
  if($in{strLastName} eq '')
  { $zmsg .= "<li>[AE01]: 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>[AE02]: 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>[AE03]: 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>[AE04]: Member password, <b>$in{strPassword}</b>, does not match confirmation password, <b>$in{strPwdConfirm}</b>.\n";
  }
  if($in{strAccount} eq 'aff')
  { $in{strIdType} = "A";
    $in{strLocCity} = $in{strCity};
  }
#  if($in{strLocCity} eq '' || $in{strLocCity} =~ /[^0-9a-zA-Z-. ,]/)
  if($in{strLocCity} eq '')
  { $zmsg .= "<li>[AE05]: Where you are is required and can only contain alphanumeric characters and - and . and ,.\n";
  }
  $in{strLocPhone} =~ s/\.+//g;            # remove period
  $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>[AE06]: Phone number can only contain digits 0-9.\n";
  }
  if($in{strAccount} ne 'basic' && $in{strAccount} ne 'aff')
  { if($in{strStreet}  eq ''
     ||$in{strCity}    eq ''
     ||$in{strCountry} eq '')
    { $zmsg.="<li>[AE07]: 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>[AE08]: Credit card information must be entered for VIP accounts.\n";
    }
  }
  if($in{strLocPhone} ne ''
   &&$in{strLocCity} eq '')
  { $zmsg .= "<li>[AE08]: A City must be entered if you entered a Phone Number.\n";
  }
  ###################################################################
  # check forwarding options argument
  ###################################################################
  if ($in{memberadd2} eq 'Yes')
  { $zauth_800 = 0;
    ###################################################################
    # general for all package
    ###################################################################
    if($in{strForwardTo} eq '')
      { $zmsg .= "<li>[AE09]: A 1800 GTF Number must be selected.\n";
      }
    if($in{strFollowme} eq $in{strForwardTo})
    { $zmsg .= "<li>[AE10]: The Route-to Destination Number cannot be the same as the 800 GTF Number.\n";
    }
    foreach $zlist (@zphonelist)
    { ($zznum, $zjunk) = split (/,/,$zlist,2);
      if ($in{strFollowme} eq $zznum)
      { $zmsg .= "<li>[AE11]: The Route-to Destination Number cannot be the same as any of GT's 800 GTF Number.\n";
        last;
      }
      if ($in{strForwardTo} eq $zznum)
      { $zauth_800 = 1;
      }
    }
    if ($zauth_800 != 1)
    { $zmsg .= "<li>[AE12]: The 800 GTF you entered is not one of GT's 800 GTF Number.\n";
    }
    ###################################################################
    # special for Package A & B
    ###################################################################
    if ($in{strGTFPackage} eq 'A' || $in{strGTFPackage} eq 'B')
    { if($in{strFollowme} eq '')
      { $zmsg .= "<li>[AE13]: A Route-to Destination Number must be entered.\n";
      }
    }
    ###################################################################
    # special for Package C & D
    ###################################################################
    $zextnumber = 0;
    $zextdigit = 0;
    if ($in{strGTFPackage} eq 'C' || $in{strGTFPackage} eq 'D')
    { for ($zii=1; $zii<10; $zii++)
      { $zextname = 'strGTFExtension'.$zii;
        $znumname = 'strFollowme'.$zii;
        $zext[$zii] = $in{$zextname};
        $znum = $in{$znumname};
        if(length($zext[$zii]) != $zextdigit && $zextdigit !=0 && $zext[$zii] ne '')
        { $zmsg .= "<li>[AE14]: All extension must have the same amount of digit.\n";
        }      
        for ($zjj=1; $zjj<10; $zjj++)
        { if ($zjj >= $zii)
          { last;
          }
          elsif ($zext[$zii] eq $zext[$zjj] && $zext[$zjj] ne '')
          { $zmsg .= "<li>[AE15]: Extension cannot be the same.\n";
          }
        }
        foreach $zlist (@zphonelist)
        { ($zznum, $zjunk) = split (/,/,$zlist,2);
          if ($znum eq $zznum)
          { $zmsg .= "<li>[AE16]: The Route-to Destination Number cannot be the same as any of GT's 800 GTF Number.\n";
            last;
          }
        }
        if($znum eq $in{strForwardTo})
        { $zmsg .= "<li>[AE17]: The Route-to Destination Number cannot be the same as the 800 GTF Number.\n";
        }
        if($zext[$zii] ne ''
         && $znum eq '')
        { $zmsg .= "<li>[AE18]: A Route-to Destination Number must be entered if you entered an Extension.\n";
        }
        elsif($znum ne ''
         && $zext[$zii] eq '')
        { $zmsg .= "<li>[AE19]: An Extension must be entered if you entered a Route-to Destination Number.\n";
        }
        elsif ($znum ne '' && $zext[$zii] ne '')
        { $in{strGTFExtension} .= "\#$zext[$zii]";
          $in{strFollowme} .= "\#$znum";
          if ($zextdigit == 0)
          { $zextdigit = length($zext[$zii]);
          }
          $zextnumber++;
        }
        if($zext[$zii] =~ /[^0-9-]/ || $znum =~ /[^0-9-]/) 
        { $zmsg .= "<li>[AE20]: GTF Extension or GTF Route to Destination Number can only contain numeric characters\n";
        }
      }
      if($zextnumber == 0)
      { $zmsg .= "<li>[AE21]: At least 1 Extension Number and Route-to Destination Number need to be entered.\n";
      }  
    }
    ###################################################################
    # special for Package D
    ###################################################################
    if ($in{strGTFPackage} eq 'D')
    { if ($in{strGTF6Extension} eq '')
      { $zmsg .= "<li>[AE22]: GTF Personal Outbound Call Extension is required.\n";
      }
      if ($in{strGTFPassword} eq '' || length($in{strGTFPassword}) < 8)
      { $zmsg .= "<li>[AE23]: GTF password is required and must be at least 8 digits long.\n";
      }
      if($in{strGTF6Extension} =~ /[^0-9]/ || $in{strGTFPassword} =~ /[^0-9]/)
      { $zmsg .= "<li>[AE24]: GTF Personal Outbound Call Extension or GTF Password can only contain numeric characters\n";
      }
      for ($zkk=1; $zkk<10; $zkk++)
      { if ($in{strGTF6Extension} eq $zext[$zkk] && $zext[$zkk] ne '')
        { $zmsg .= "<li>[AE25]: GTF Personal Outbound Call Extension cannot be the same as any GTF Extension Number.\n";
        }
      }
      if(length($in{strGTF6Extension})!= $zextdigit && $zextdigit !=0)
      { $zmsg .= "<li>[AE26]: All extension must have the same amount of digit.\n";
      } 
    }
  }
  $in{strGTFExtension}=substr($in{strGTFExtension},1);
  $in{strFollowme}=substr($in{strFollowme},1);
  ###################################################################
  # check if userid already used
  ###################################################################
  $zret=&member_get($in{strEmail});
  if($zret == 0)
  { close(MEMLK);
    $zmsg .= "<li>[AE27]: Email address (login id), <b>$in{strEmail}</b>, is already in use, or you have login as <b>$in{strEmail}</b>\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{memberadd2} eq 'Yes')
  {
    ###################################################################
    # 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("<li>member_add_1[02]: 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");
    ###################################################################
    # send email using the proper template
    ###################################################################
    &modify_800phone_list;     #aaron
#    if($gtuv{u_account} eq 'vip-01'
#     ||$gtuv{u_account} eq 'vip-12'
#     ||$gtuv{u_gtfpackage} ne '')
#    { $gtuv{voicemail} = $gtgv{voicemail};
#      &send_email($gt_email_to,$vars{email_signup},%gtuv);
#    }
    if ($gtuv{u_gtfpackage} ne '')
    { $ztemplate= $vars{email_followme};
      foreach $zrec (@gtGTFEmailFollowme)
      { ($zpack, $zemail, $zjunk) = split(/,/,$zrec,3);
        if($zpack eq $gtuv{u_gtfpackage})
        { $ztemplate = $vars{$zemail};
        }
      }
      &send_email('aaron2@infinex.com',$ztemplate,%gtuv); 
    } 
    &calendar_error_msg('','mytravel_html'); #by Aaron
  }
  ####################################################################
  # generate 800 number list 
  ####################################################################
  &generate_phone_num; 
  ####################################################################
  # display the correct html for the package the customer selected
  ####################################################################
  foreach $zrec (@gtGTFHtml)
  { ($zplan,$zhtml,$zjunk) = split(/,/,$zrec,3);
    if ($zplan eq $in{strGTFPackage})
    { print "\n";
      &calendar_error_msg('',"$zhtml"); #by Aaron
      exit;
    }
  }
  print "\n";
  &calendar_error_msg('','signup_html'); #by Aaron
  exit;
}
#####################################################################
# 800 number signup step 1 - select country
#####################################################################
sub vip_signup_step_1
{ my ($zmsg);
  ###################################################################
  # check arguments
  ###################################################################
#  if($in{strFirstName} eq '' || $in{strFirstName} =~ /[^0-9a-zA-Z-. ]/)
  if($in{strFirstName} eq '')
  { $zmsg .= "<li>[AF00]: Member first name is required and can only contain alphanumeric characters and - and ..\n";
  }
#  if($in{strLastName} eq '' || $in{strLastName} =~ /[^0-9a-zA-Z-. ]/)
  if($in{strLastName} eq '')
  { $zmsg .= "<li>[AF01]: 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>[AF02]: 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{strEmailAddress})
  { $zmsg .= "<li>[AF03]: 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>[AF04]: Member password, <b>$in{strPassword}</b>, does not match confirmation password, <b>$in{strPwdConfirm}</b>.\n";
  }
  if($in{strAccount} eq 'aff')
  { $in{strIdType} = "A";
    $in{strLocCity} = $in{strCity};
  }
#  if($in{strLocCity} eq '' || $in{strLocCity} =~ /[^0-9a-zA-Z-. ,]/)
#  { $zmsg .= "<li>[AF05]: Where you are is required and can only contain alphanumeric characters and - and . and ,.\n";
#  }
  $in{strLocPhone} =~ s/\.+//g;            # remove period
  $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>[AF06]: Phone number can only contain digits 0-9.\n";
  }
  if($in{strStreet}  eq ''
     ||$in{strCity}    eq ''
     ||$in{strCountry} eq '')
  { $zmsg.="<li>[AF08]: Street, City, and Country must be entered.\n";
  }
  if($in{strPayType}  eq '')
  { $zmsg.="<li>[AF09]: You have to select payment type.\n";                           
  }
  if($in{strPayType} ne 'Check')
  { if($in{strCCType} eq '' 
     ||$in{strCCNum}  eq ''
     ||$in{strCCExp}  eq '' 
     ||$in{strCCName} eq '')
    { $zmsg.="<li>[AF10]: Credit card information must be entered if pay by credit card.\n";
    }
  }  
  if($in{strLocPhone} ne ''
   &&$in{strLocCity} eq '')
  { $zmsg .= "<li>[AF11]: A City must be entered if you entered a Phone Number.\n";
  }
  if($in{countrynumber} eq '')
  { $zmsg .= "<li>[AF12]: The 800 number home country must be selected.\n";
  }
  ###################################################################
  # check if userid already used
  ###################################################################
  $zret=&member_get($in{strEmail},$in{strEmailAddress});
  if($zret == 0)
  { close(MEMLK);
    $zmsg .= "<li>[AF13]: Email address (login id), <b>$in{strEmail}</b>, is already in use, or you have login as <b>$in{strEmail}</b>\n";
  }
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  { print ("\n");
    &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  foreach $zfield (@gtMemCal)
  { $ztmp=$zfield;
    ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
    $vars{$zkeyvar}=$in{$zkeyin};
  }

  &generate_phone_num($in{countrynumber});
  $vars{countrynumber} = $in{countrynumber};
  &calendar_error_msg('','vip_signup_html');
}
#####################################################################
# 800 number signup by Affiliate step 1 - select country
#####################################################################
sub aff_signup_800_step_1
{ my ($zmsg);
  ###################################################################
  # check arguments
  ###################################################################
#  if($in{strFirstName} eq '' || $in{strFirstName} =~ /[^0-9a-zA-Z-. ]/)
  if($in{strFirstName} eq '')
  { $zmsg .= "<li>[AG00]: Member first name is required and can only contain alphanumeric characters and - and ..\n";
  }
#  if($in{strLastName} eq '' || $in{strLastName} =~ /[^0-9a-zA-Z-. ]/)
  if($in{strLastName} eq '')
  { $zmsg .= "<li>[AG01]: Member last name is required and can only contain alphanumeric characters and - and ..\n";
  }
  if($in{strEmailAddress} eq '' || $in{strEmailAddress} =~ /[^.\-\_\@0-9a-zA-Z]/)
  { $zmsg .= "<li>[AG02]: Member email address (login id) is required and must be in a valid email format.\n";
  }
  if($in{strEmail} eq '')
  { $zmsg .= "<li>[AG03]: Affiliate Account number is required.\n";
  }
  if($in{strPassword} eq '')
  { $zmsg .= "<li>[AG04]: 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{strStreet}  eq ''
     ||$in{strCity}    eq ''
     ||$in{strCountry} eq '')
  { $zmsg.="<li>[AG05]: Street, City, and Country must be entered.\n";
  }
  if ($in{strPayType} ne 'Check')
  { if($in{strCCType} eq ''
     ||$in{strCCNum}  eq ''
     ||$in{strCCExp}  eq ''
     ||$in{strCCName} eq '')
    { $zmsg.="<li>[AG06]: Credit card information must be entered.\n";
    }
  }
  if($in{countrynumber} eq '')
  { $zmsg .= "<li>[AG07]: The 800 number home country must be selected.\n";
  }
  ###################################################################
  # check if userid already used
  ###################################################################
  $zret=&affiliate_lookup($in{strAffNumber});
  if($zret == 1)
  { close(MEMLK);
    $zmsg .= "<li>[AG08]: Affiliate Account, <b>$in{strAffNumber}</b>, not found in our database!\n";
  }
  if(crypt($gtuv{aff_passwd},$in{strPassword}) ne $in{strPassword} && $gtuv{aff_passwd} ne $in{strPassword})
  { close(MEMLK);
    $zmsg.="<li>[AG09]: Affiliate Email address, (login id), <b>$in{strEmail}</b> and password not found in our database.\n";
  }
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  { print ("\n");
    &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  foreach $zfield (@gtMemCal)
  { $ztmp=$zfield;
    ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
    $vars{$zkeyvar}=$in{$zkeyin};
  }
  $vars{affnumber} = $in{strAffNumber};
  return;
}
#####################################################################
# 800 number signup by Affiliate step 1 - select country
#####################################################################
sub aff_signup_800_step_2
{ my($zmsg,$zmem);
  my($zemail,$zpassword,$zfirstname,$zlastname,$zloc,$zjunk);
  my($zfield,$ztmp,$zkeyuv,$zkeyin,$zkeyvar);

  ###################################################################
  # check 800 number and forward number
  ###################################################################
  if($in{strForwardTo} eq '')
  { $zmsg .= "<li>[AH00]: A 1800 GTF Number must be selected.\n";
  }
  if($in{strFollowme} eq '')  
  { $zmsg .= "<li>[AH01]: The Route-to Destination Number must be entered.\n";  
  } 
  if($in{strFollowme} eq $in{strForwardTo})
  { $zmsg .= "<li>[AH02]: The Route-to Destination Number cannot be the same as the 800 GTF Number.\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
  ###################################################################
  $zret=&member_get($in{strEmail},'');
  $in{strSignupDate} = $vars{'datestamp'}; #copy signup date
  &add_to_tracking;   # generate signup data
  @memdata1 = @memdata;
  $zlastentry = pop @memdata1;
  foreach $zfield (@gtMemCal)
  { $ztmp=$zfield;
    ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
    if ($vars{$zkeyvar} eq '')
    { $vars{$zkeyvar}=$in{$zkeyin};
    }
    $gtuv{$zkeyuv}=$in{$zkeyin}; 
  }
  ($gtuv{u_userid},$zjunk) = split(/,/,$zlastentry,2);
  $zinc = rand(50);
  $zinc = int ($zinc);
  $gtuv{u_userid} += $zinc;
  $gtuv{u_email} = $in{strEmailAddress};
  $gtuv{u_gtaffid} = $in{strAffNumber};
#  $in{strEmailAddress} = $in{strEmail};
#  $in{strEmail} = $gtuv{u_userid};
#  $vars{loginid} = $in{strEmail};
  $vars{strEmailAddress} = $in{strEmail};
  $vars{firstname} = $gtuv{aff_firstname};
  $vars{lastname} = $gtuv{aff_lastname};
  $vars{strCompanyName} = $gtuv{aff_companyname};
  ###################################################################
  # create random password
  ###################################################################
  if ($in{strInfMemPasswd} eq '')
  { $zpasswd = rand(9999999);
    $zpasswd = int($zpasswd);
    $gtuv{u_passwd}=crypt($zpasswd,time);
    $gtuv{newmemberpasswd} = $gtuv{u_passwd}; 
  }
  else
  { $gtuv{u_passwd} = $in{strInfMemPasswd};
    $gtuv{newmemberpasswd} = $gtuv{u_passwd}; 
  }    
  ###################################################################
  # 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("<li>aff_signup_800_step_2[01]: 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);
  $in{loginid} = $in{strEmail};
  $in{password} = $vars{password};
  ###################################################################
  # send email to new member, affiliate and officers
  ###################################################################
  $gtuv{voicemail} = $gtgv{voicemail};
  &send_email($gt_email_to,$vars{email_signup},%gtuv);
  &send_email($gtuv{u_email},$vars{email_signup_member},%gtuv);
  &send_email($in{strEmail},$vars{email_signup_affiliate},%gtuv);
  &make_payment(%gtuv);
  &create_phonebook; #Aaron
  &modify_800phone_list("$in{countrynumber}");     #aaron
  &modify_quota("$in{strAffNumber}");
  if ($vars{loginid} eq 'infinex')
  { &calendar_error_msg('','infinex_html'); 
  }
  elsif ($in{strAccount} eq 'vip_special')
  { &get_special_rate($in{strAffNumber});
    &calendar_error_msg('','signup_special_html');
  }   
  else
  { &calendar_error_msg('','aff_menu_html');
  }
}

#####################################################################
# Add a member
#####################################################################
sub member_add
{ my($zmsg,$zmem);
  my($zemail,$zpassword,$zfirstname,$zlastname,$zloc,$zjunk);
  my($zfield,$ztmp,$zkeyuv,$zkeyin,$zkeyvar);

#  print ("\n");       # do not delete.  needed to close cookie defines
  ###################################################################
  # check arguments
  ###################################################################
#  if($in{strFirstName} eq '' || $in{strFirstName} =~ /[^0-9a-zA-Z-. ]/)
  if($in{strFirstName} eq '')
  { $zmsg .= "<li>[AI00]: Member first name is required and can only contain alphanumeric characters and - and ..\n";
  }
#  if($in{strLastName} eq '' || $in{strLastName} =~ /[^0-9a-zA-Z-. ]/)
  if($in{strLastName} eq '')
  { $zmsg .= "<li>[AI01]: 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>[AI02]: Member email address 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>[AI03]: 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>[AI04]: Member password, <b>$in{strPassword}</b>, does not match confirmation password, <b>$in{strPwdConfirm}</b>.\n";
  }
  if($in{strAccount} eq 'aff')
  { $in{strIdType} = "A";
    $in{strLocCity} = $in{strCity};
    if($in{strEmail} eq '')
    { $zmsg .= "<li>[AI05]: Affiliate Email Address cannot be empty.\n";
    }
  }
#  if($in{strLocCity} eq '' || $in{strLocCity} =~ /[^0-9a-zA-Z-. ,]/)
#  { $zmsg .= "<li>[AI06]: Where you are is required and can only contain alphanumeric characters and - and . and ,.\n";
#  }
  $in{strLocPhone} =~ s/\.+//g;            # remove period
  $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>[AI07]: Phone number can only contain digits 0-9.\n";
  }
  if($in{strAccount} ne 'basic' && $in{strAccount} ne 'aff')
  { if($in{strPayType}  eq '')
    { $zmsg.="<li>[AI08]: You have to select payment type.\n";
    }
    if($in{strStreet}  eq ''
      ||$in{strCity}    eq ''
      ||$in{strCountry} eq '')
    { $zmsg.="<li>[AI09]: Street, City, and Country must be entered for VIP accounts.\n";
    }
    if($in{strPayType} ne 'Check')
    { if($in{strCCType} eq ''
       ||$in{strCCNum}  eq ''
       ||$in{strCCExp}  eq ''
       ||$in{strCCName} eq '')
      { $zmsg.="<li>[AI10]: Credit card information must be entered for VIP accounts.\n";
      }
    }
  }
  if($in{strLocPhone} ne ''
   &&$in{strLocCity} eq '')
  { $zmsg .= "<li>[AI11]: A City must be entered if you entered a Phone Number.\n";
  }
  if($in{strAffNumber} ne '')
  { $zaff=&affiliate_lookup($in{strAffNumber});
    if($zaff == 1)
    { $in{strAffNumber} = '';
    }
  }
  ###################################################################
  # check if userid already used
  ###################################################################
  $zret=&member_get($in{strEmail},$in{strEmailAddress});
  if($vars{affiliatepage} ne 'Yes' && $in{strAccount} ne 'basic')
  {#  if($zret == 0)
   # { close(MEMLK);
   #   $zmsg .= "<li>[AI12]: Email address (login id), <b>$in{strEmailAddress}</b>, is already in use, or you have login as <b>$in{strEmailAddress}</b>\n";
   # }
    ###################################################################
    # check 800 number and forward number
    ###################################################################
    if($in{strForwardTo} eq '')
    { $zmsg .= "<li>[AI13]: A 1800 GTF Number must be selected.\n";
    }
    if($in{strFollowmeCountry} =~ /\D/ || $in{strFollowmeCountry} eq '')  
    { $zmsg .= "<li>[AI14]: The 'Route To' numeric Country code must be entered.\n";  
    } 
    if($in{strFollowmeArea} =~ /\D/ || $in{strFollowmeArea} eq '')
    { $zmsg .= "<li>[AI15]: The 'Route To' numeric Area/City code must be entered.\n";  
    } 
    if($in{strFollowmeNumber} =~ /\D/ || $in{strFollowmeNumber} eq '')
    { $zmsg .= "<li>[AI16]: The 'Route To' Number code must be entered.\n";  
    } 
    $in{strFollowme}="$in{strFollowmeCountry}-$in{strFollowmeArea}-$in{strFollowmeNumber}";
    if($in{strFollowme} eq '')  
    { $zmsg .= "<li>[AI17]: The 'Route To' Destination Number must be entered.\n";  
    } 
    if($in{strFollowme} eq $in{strForwardTo})
    { $zmsg .= "<li>[AI18]: The 'Route To' Destination Number cannot be the same as the 800 GTF Number.\n";
    }
    ###################################################################
    # ensure credit line amount is nnn.nn
    ###################################################################
    $in{strCreditLine}=sprintf("%0.2f",$in{strCreditLine});
    ###################################################################
    # debit credit card
    ###################################################################
    if($zmsg eq '')                 # no error messages 
    { my($zsuccess,$zresult,$zccmsg,$zauthcode,$zavs,$zccerr,%zan);

if($ztest eq 'YY')
{ #print ("\n"); 
#xxxxx
#
      ($zsuccess,$zresult,$zccmsg,$zauthcode,$zavs,$zccerr)=
        &debit_credit_card
          ("GT VIP Signup Initial Credit Line Charge",
           $in{strCreditLine},
           $in{strCCType},
           $in{strCCNum},
           $in{strCCExp},
           "$in{strFirstName} $in{strLastName}",
           $in{strFirstName},
           $in{strLastName},
           $in{strStreet},
           $in{strCity},
           $in{strState},
           $in{strZip},
           $in{strCountry}
          );
      if($zsuccess ne 'Y')
      { $zmsg .= "<li>[AI19]: $zccmsg, AVS=$zavs, $zccerr\n";
      }

}
else
{ #print ("\n"); 
      ###############################################################
      # authorizenet credit card processing
      ###############################################################
      if($gtgv{creditprocessing} =~ /authorizenet/i)
      { %zan=();
        $zan{cc_Login}       =$gtgv{authorizenet_id};
        $zan{cc_Invoice_Num} =$gtgv{fndate};
        $zan{cc_Description} ="GT VIP Signup Initial Credit Line Charge";
        $zan{cc_Cust_ID}     =$gtgv{fndate};
        $zan{cc_First_Name}  =$in{strFirstName};
        $zan{cc_Last_Name}   =$in{strLastName};
        $zan{cc_Address}     =$in{strStreet};
        $zan{cc_City}        =$in{strCity};
        $zan{cc_State}       =$in{strState};
        $zan{cc_Zip}         =$in{strZip};
        $zan{cc_Country}     =$in{strCountry};
        $zan{cc_Amount}      =$in{strCreditLine};
        $zan{cc_Card_Num}    =$in{strCCNum};
        $zan{cc_Exp_Date}    =$in{strCCExp};

        require ($gtgv{authorizenet_code});
        ($zresult,$zccmsg,$zauthcode,$zavs,$zccerr)=&{$gtgv{authorizenet_pgm}}($gtgv{authorizenet_mode},%zan);
        if($zresult != 1)
        { $zmsg .= "<li>[AI19]: $zccmsg, AVS=$zavs, $zccerr\n";
        }
      }
      ###############################################################
      # intellipay credit card processing
      ###############################################################
      elsif($gtgv{creditprocessing} =~ /intellipay/i)
      { %zan=();
        $zan{cc_Login}       =$gtgv{intellipay_id};
        $zan{cc_Password}    =$gtgv{intellipay_pw};
        $zan{cc_Type}        =$gtgv{intellipay_type}; # AO, NA, or AI
        $zan{cc_Invoice_Num} =$gtgv{fndate};
        $zan{cc_Description} ="GT VIP Signup Initial Credit Line Charge";
        $zan{cc_Cust_ID}     =$gtgv{fndate};
        $zan{cc_Name}        ="$in{strFirstName} $in{strLastName}";
        $zan{cc_Address}     =$in{strStreet};
        $zan{cc_City}        =$in{strCity};
        $zan{cc_State}       =$in{strState};
        $zan{cc_Zip}         =$in{strZip};
        $zan{cc_Country}     =$in{strCountry};
        $zan{cc_Amount}      =$in{strCreditLine};
        $zan{cc_Method}      =$in{strCCType};
        $zan{cc_Card_Num}    =$in{strCCNum};
        $zan{cc_Exp_Date}    =$in{strCCExp};

        require ($gtgv{intellipay_code});
        ($zresult,$zccmsg,$zauthcode,$zavs,$zccerr)=&{$gtgv{intellipay_pgm}}($gtgv{intellipay_type},%zan);
        if($zresult !~ /^A$/i)
        { $zmsg .= "<li>[AI20]: $zccmsg, AVS=$zavs, $zccerr\n";
        }
      }
      ###############################################################
      # unknown credit card processing site
      ###############################################################
      else
      { $zresult='Z';
        $zccmsg="'$gtgv{creditprocessing}' is NOT a valid credit card processing site.";
      }
}
    }
  }
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  {
   print ("\n");       # do not delete.  needed to close cookie defines
    &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  ###################################################################
  # put data into gtuv, in, and vars
  ###################################################################
  $in{strSignupDate} = $vars{'datestamp'}; #copy signup date
  &add_to_tracking;
  @memdata1 = @memdata;
  $zlastentry = pop @memdata1;
  if($vars{affiliatepage} eq 'Yes')
  { foreach $zfield (@gtAffData)
    { $ztmp=$zfield;
      ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
      $vars{$zkeyvar}=$in{$zkeyin};
      $gtuv{$zkeyuv}=$in{$zkeyin};
    }
    ($gtuv{aff_number},$zjunk) = split(/,/,$zlastentry,2);
    $gtuv{aff_number} = substr ($gtuv{aff_number},1);
    $gtuv{aff_number}++;
    if ($in{strEmail} eq 'infinex')
    { $gtuv{aff_number} = "B".$gtuv{aff_number};
      $gtuv{aff_passwd} = $gt_s_password;
      $gtuv{aff_userid} = $in{strEmailAddress};
    }
    else
    { $gtuv{aff_number} = "A".$gtuv{aff_number};
    }
    $vars{affnumber} = $gtuv{aff_number};
  }
  else
  { foreach $zfield (@gtMemCal)
    { $ztmp=$zfield;
      ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
      $vars{$zkeyvar}=$in{$zkeyin};
      $gtuv{$zkeyuv}=$in{$zkeyin};
    }
    ($gtuv{u_userid},$zjunk) = split(/,/,$zlastentry,2);
    $zinc = rand(50);
    $zinc = int ($zinc);
    $gtuv{u_userid} += $zinc;
    $in{strEmailAddress} = $in{strEmail};
    $in{strEmail} = $gtuv{u_userid};
    $vars{loginid} = $in{strEmail};
    $vars{strEmailAddress} = $in{strEmailAddress};
    $gtuv{u_email} = $vars{strEmailAddress};
    $gtuv{u_currentbal} = $in{strCreditLine};
  }
  if($in{strLocCity} ne '')
  { $gtuv{u_loc}="$in{strLocCity}#$in{strLocPhone}";
  }
  else
  { $gtuv{u_loc} = '';
  }
  ###################################################################
  # encrypt passwd that is displayed on web pages
  ###################################################################
  if($vars{affiliatepage} eq 'Yes')
  { $vars{strPassword}=crypt($gtuv{aff_passwd},time); 
  }
  else
  { $vars{strPassword}=crypt($gtuv{u_passwd},time);
  }
  $vars{password}=$vars{strPassword};
  ###################################################################
  # create new member string
  ###################################################################
  $zmemstr='';
  if($vars{affiliatepage} eq 'Yes')
  { foreach $zkeyuv (@gtAffDB) 
    { $zmemstr .= "|$gtuv{$zkeyuv}";
    }
  }
  else
  { 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($vars{affiliatepage} eq 'Yes')
  { $ztmpfile = $vars{aff_file};
  }
  else
  { $ztmpfile = $vars{member_file};
  }
  if(!open(MEMFN,">$ztmpfile-tmp"))
  { close(MEMLK);
	print ("\n"); #Aaron
    &Error("<li>member_add[01]: Can't open $ztmpfile-tmp file for write!");
  }
  print MEMFN @memdata;
  close(MEMFN);
  ###################################################################
  # rename the file to the main member file name
  ###################################################################
  rename "$ztmpfile-tmp","$ztmpfile";
  close(MEMLK);
  $in{loginid} = $in{strEmail};
  $in{password} = $vars{password};
  if ($vars{affiliatepage} eq 'Yes')
  {  $vars{sc_cookie}="Set-Cookie:gtafflogin=$in{strEmail}|$in{strPassword};path=/\n";        # Aaron
  }
  else
  {    $vars{sc_cookie}="Set-Cookie:gtlogin=$in{strEmail}|$in{strPassword};path=/\n";        # Aaron
  }
  $vars{loadcookie} = 1;
  print ("$vars{sc_cookie}\n\n");
  ###################################################################
  # send email if vip 800 number
  ###################################################################
  #&add_to_tracking($in{strGTAffID},%gtuv); # write data to web store tracking file
  if($in{strAccount} eq 'aff' || $in{"ACTION"} eq 'affiliate_add')
  { &send_email($gt_email_to,$vars{email_singup_affiliate_admin},%gtuv);
    &send_email($gtuv{aff_userid},$vars{email_aff_signup},%gtuv);
    &calendar_error_msg('','aff_menu_html'); #by Aaron
  }
  else
  { $gtuv{voicemail} = $gtgv{voicemail};
    if ($gtuv{u_account} eq 'basic')
    { # send email using basic account template
      &send_email($gt_email_to,$vars{email_signup_basic},%gtuv);
      &send_email($in{strEmailAddress},$vars{email_member_basic},%gtuv);
    }
    else
    { # send email using vip account template
      &send_email($gt_email_to,$vars{email_signup},%gtuv);
      &send_email($in{strEmailAddress},$vars{email_member},%gtuv);
      &make_payment(%gtuv);
    }
    &create_phonebook; #Aaron
    &modify_800phone_list("$in{countrynumber}");     #aaron
    &calendar_error_msg('','mytravel_html'); #by Aaron
  }
}
#####################################################################
# process credit card
# input:
#   arguments are passed in the sequence shown.
#   %gtgv globals controls control usage
#
# output
#   pass or fail
#   error message
#   reference code
#
#####################################################################
#xxxxx
sub debit_credit_card
{ my($xcc_description,     # will appear on credit card statement
     $xcc_amount,          # amount as nnn.nn
     $xcc_type,            # visa, mastercard, discover, novus, etc
     $xcc_number,          # credit card number
     $xcc_expdate,         # credit card expiration date, mm/yy
     $xcc_owner,           # credit card owner name, first and last
     $xcc_firstname,       # credit card owner first name
     $xcc_lastname,        # credit card owner last name
     $xcc_address,         # avs - credit card owner street address
     $xcc_city,            # avs - credit card owner city
     $xcc_state,           # avs - credit card owner state
     $xcc_zipcode,         # avs - credit card owner zip code
     $xcc_country          # avs - credit card owner country, 2 char code
    )=@_;
  my($zsuccess,$zresult,$zccmsg,$zauthcode,$zavs,$zccerr,%zcc);
  ###################################################################
  # authorizenet credit card processing
  ###################################################################
  if($gtgv{creditprocessing} =~ /authorizenet/i)
  { %zcc=();
    $zcc{cc_Login}       =$gtgv{authorizenet_id};
    $zcc{cc_Invoice_Num} =$gtgv{fndate};
    $zcc{cc_Cust_ID}     =$gtgv{fndate};
    $zcc{cc_Description} =$xcc_description;
    $zcc{cc_First_Name}  =$xcc_firstname;
    $zcc{cc_Last_Name}   =$xcc_lastname;
    $zcc{cc_Address}     =$xcc_address;
    $zcc{cc_City}        =$xcc_city;
    $zcc{cc_State}       =$xcc_state;
    $zcc{cc_Zip}         =$xcc_zipcode;
    $zcc{cc_Country}     =$xcc_country;
    $zcc{cc_Amount}      =$xcc_amount;
    $zcc{cc_Card_Num}    =$xcc_number;
    $zcc{cc_Exp_Date}    =$xcc_expdate;

    require ($gtgv{authorizenet_code});
    ($zresult,$zccmsg,$zauthcode,$zavs,$zccerr)=&{$gtgv{authorizenet_pgm}}($gtgv{authorizenet_mode},%zcc);
    if($zresult != 1)
    { $zsuccess='N';
    }
    else
    { $zsuccess='Y';
    }
  }
  ###################################################################
  # intellipay credit card processing
  ###################################################################
  elsif($gtgv{creditprocessing} =~ /intellipay/i)
  { %zcc=();
    $zcc{cc_Login}       =$gtgv{intellipay_id};
    $zcc{cc_Password}    =$gtgv{intellipay_pw};
    $zcc{cc_Type}        =$gtgv{intellipay_type}; # AO, NA, or AI
    $zcc{cc_Invoice_Num} =$gtgv{fndate};
    $zcc{cc_Cust_ID}     =$gtgv{fndate};
    $zcc{cc_Description} =$xcc_description;
    $zcc{cc_Name}        =$xcc_owner;
    $zcc{cc_Address}     =$xcc_address;
    $zcc{cc_City}        =$xcc_city;
    $zcc{cc_State}       =$xcc_state;
    $zcc{cc_Zip}         =$xcc_zipcode;
    $zcc{cc_Country}     =$xcc_country;
    $zcc{cc_Amount}      =$xcc_amount;
    $zcc{cc_Method}      =$xcc_type;
    $zcc{cc_Card_Num}    =$xcc_number;
    $zcc{cc_Exp_Date}    =$xcc_expdate;

    require ($gtgv{intellipay_code});
    ($zresult,$zccmsg,$zauthcode,$zavs,$zccerr)=&{$gtgv{intellipay_pgm}}($gtgv{intellipay_type},%zcc);
    if($zresult !~ /^A$/i)
    { $zsuccess='N';
    }
    else
    { $zsuccess='Y';
    }
  }
  ###################################################################
  # unknown credit card processing site
  ###################################################################
  else
  { $zccmsg="'$gtgv{creditprocessing}' is NOT a valid credit card processing site.";
    $zsuccess='N';
  }
  return($zsuccess,$zresult,$zccmsg,$zauthcode,$zavs,$zccerr);
}
#####################################################################
# 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);
  if($in{"ACTION"} eq 'affiliate_login')
  { $vars{affiliatepage} eq 'Yes';
  }
  $zmsg='';
  ###################################################################
  # check arguments
  ###################################################################
  if(($in{strEmail} eq '' && $in{strEmailAddress} 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
  { if($in{"ACTION"} eq 'affiliate_login')
    { $zret=&affiliate_lookup($in{strAffNumber});
    }
    else
    { $zret=&member_get($in{strEmail},$in{strEmailAddress});
    }
    if($zret == 1)
    { close(MEMLK);
      $zmsg .= "<li>[AJ00]: Email address (login id), <b>$in{strEmailAddress}</b>, not found in our database!\n";
    }
    elsif($zret == 2)
    { close(MEMLK);
      if ($zmsg eq '')
      { 
      $vars{password}=crypt($in{strPassword},time);
      print ("\n"); #Aaron
      &calendar_error_msg('','member_choose_acctnum_html');
      exit;
      }
    }
    else
    { if($xopr eq 'Login'
       ||$xopr eq 'Update'
       ||$xopr eq 'Phonebook'        
       ||$xopr eq 'Phonebook1' #Aaron
       ||$xopr eq 'um'
       ||$xopr eq 'Locator'
       ||$xopr eq 'SMS'
       ||$xopr eq 'Main' )
      { if(crypt($gtuv{u_passwd},$in{strPassword}) ne $in{strPassword} && $gtuv{u_passwd} ne $in{strPassword})
        { close(MEMLK);
          $zmsg.="<li>[AJ01]: Email address, (login id), <b>$in{strEmailAddress},</b> and password not found in our database.\n";
        }
        if (($in{strEmailAddress} ne '' && $gtuv{u_email} ne $in{strEmailAddress})
          || ($in{strEmail} ne '' && $gtuv{u_userid} ne $in{strEmail}))
        { close(MEMLK);
          $zmsg.="<li>[AJ02]: Account Number '$in{strEmail}' and Email Address '$in{strEmailAddress}' not matched in our database.\n";
        }
      }
      elsif($xopr eq 'affiliate_sales' || $xopr eq 'AffLogin' || $xopr eq 'aff_800_signup' || $xopr eq 'aff_invite'
            || $xopr eq 'special_deal' || $xopr eq 'aff_800_signup_1' || $xopr eq 'aff_sales_tracking' 
            || $xopr eq 'aff_update' || $xopr eq 'invite_friends')
      { if(crypt($gtuv{aff_passwd},$in{strPassword}) ne $in{strPassword} && $gtuv{aff_passwd} ne $in{strPassword})
        { close(MEMLK);
          $zmsg.="<li>[AJ03]: Affiliate Email address, (login id), <b>$in{strEmail}</b> and password not found in our database.\n";
        }
      }
      elsif($zopr eq 'MoreRows')
      { close(MEMLK);
      }
      elsif($gtuv{u_passwd} ne $in{strPassword} && $gtuv{aff_passwd} ne $in{strPassword})
      { close(MEMLK);
        $zmsg .= "<li>[AJ04]: 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);
  if($in{"ACTION"} eq 'affiliate_login')
  { foreach $zfield (@gtAffData)
    { $ztmp=$zfield;
      ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
      $vars{$zkeyvar}=$gtuv{$zkeyuv};
    }
    $vars{sc_cookie}="Set-Cookie:gtafflogin=$vars{loginid}|$gtuv{aff_passwd};path=/\n";        # Aaron
    print ("$vars{sc_cookie}");
    print ("\n");
  }
  else
  {
    foreach $zfield (@gtMemCal)
    { $ztmp=$zfield;
      ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
      $vars{$zkeyvar}=$gtuv{$zkeyuv};
    }
    $vars{strCurrentBal}=sprintf("%0.2f",$vars{strCurrentBal});
    $vars{strCreditLine}=sprintf("%0.2f",$vars{strCreditLine});
    if(!($vars{strAutoCredit} =~ /[^0-9-]/))
    { $vars{strAutoCredit}='$'.sprintf("%0.2f",$vars{strAutoCredit});
    }
    if ($vars{loadcookie} == 0 && $xopr eq 'Login') { #Aaron
      $vars{sc_cookie}="Set-Cookie:gtlogin=$vars{loginid}|$gtuv{u_passwd};path=/\n";        # Aaron
      $vars{loadcookie} = 1;
      print ("$vars{sc_cookie}");
    #print ("\n");
    }
  }
  $vars{member_login}='y';
  $in{member_login}='y';
  $in{loginid}    =$in{strEmail};
  print ("\n");
  ###################################################################
  # encrypt passwd that is displayed on web pages - aaron
  ###################################################################
  if ($in{"ACTION"} eq 'affiliate_login')
  {  $vars{strPassword}=crypt($gtuv{aff_passwd},time);
  }
  else
  {  $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($in{strEmailAddress} eq 'admin' || $in{strEmail} eq '1002')
  { &calendar_error_msg('','admin_html'); 
  } 
  elsif($in{strEmailAddress} eq 'billing' || $in{strEmail} eq '1004')
  { &calendar_error_msg('','billing_html');
  }
  elsif($in{strEmailAddress} eq 'infinex' || $in{strEmail} eq '1005')
  { &calendar_error_msg('','infinex_html');
  }
  if($in{ACTION} eq 'affiliate_login')
  { $vars{rp_agent} = $in{strEmailAddress};
    if ($xopr eq "aff_800_signup")
    {#    &generate_phone_num; 
         &calendar_error_msg('','aff_800_signup_html');   
    }
    if ($xopr eq "aff_800_signup_1")
    {  &vip_signup_step_1;
       &generate_phone_num($in{countrynumber});
       $vars{countrynumber} = $in{countrynumber};
       &calendar_error_msg('','aff_800_signup_1_html');
    }
    elsif ($xopr eq 'aff_sales_tracking')
    { &calendar_error_msg('','aff_sales_tracking_html');
    }
    elsif ($xopr eq 'AffLogin')
    { &calendar_error_msg('','aff_menu_html');
    }
    elsif ($xopr eq 'aff_update')
    { &calendar_error_msg('','affiliate_update_html');
    }
    elsif ($xopr eq 'aff_invite')
    { &calendar_error_msg('','aff_invite_html');
    }
    elsif ($xopr eq 'special_deal')
    { &get_special_rate($in{strAffNumber});
      &calendar_error_msg('','signup_special_html');
    }
    elsif ($xopr eq 'invite_friends')
    {  $gtuv{emailadd} = $in{emailadd};
       &send_email($in{emailadd},$vars{email_invite},%gtuv);
       &calendar_error_msg('','aff_menu_html');
    }
    else
    {  &calendar_error_msg('','aff_menu_html');   
    }
  }
  if($xopr eq 'SMS' || $in{Page} eq 'sms_html')
  { &sms_address_list;    #aaron
    &calendar_error_msg('','sms_html'); #by Aaron
  }
  if ($in{Page} eq 'member_upgrade_html')
  { if($gtuv{u_account} =~ /^vip/
      || $gtuv{u_account} =~ /^vo/)

    {  $zmsg="You have already received a 1 800 GTF Number.<br><br>\n";
      &calendar_error_msg($zmsg,'calendar_error_html');
    }
    else #aaron
    { &generate_phone_num;
      &calendar_error_msg('',"$in{Page}"); 
    }
  }
  if($in{Page} ne '')
  { if($gtuv{u_account} =~ /^vip/
      || $gtuv{u_account} =~ /^vo/)
    {  &calendar_error_msg('',"$in{Page}"); 
    }
    elsif($gtuv{u_gtfpackage} ne '')
    { foreach $zrec (@gtGTFModify)
      { ($zplan, $zhtml, $zjunk) = split(/,/,$zrec,3);
        if ($gtuv{u_gtfpackage} eq $zplan)
        { $ztemp = $gtuv{u_gtfextension};
          $ztemp1 = $gtuv{u_followme};
          for($zii=1; $zii<10; $zii++)
          { ($zext, $ztemp) = split (/\#/,$ztemp,2);
            ($znum, $ztemp1) = split (/\#/,$ztemp1,2);
            if($zext eq '')
            { last;
            }
            $zextname = 'strExtension'.$zii;
            $znumname = 'strFollowme'.$zii;
            $vars{$zextname} = $zext;
            $vars{$znumname} = $znum;
          }
          &calendar_error_msg('',"$zhtml");
        }
      }
      $zmsg .= "<li>[AJ05]: Data Error. Please Contact GT for detail.\n";
      &calendar_error_msg($zmsg,'calendar_error_html');
    }
    else #aaron
    { $zmsg="This Feature is only for VIP Members.<br><br>\n";
      $zmsg.="Please Click here to <a href=\"https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=calendar-Latin1.cfg&ACTION=member_login&travelcookie=1&Page=member_upgrade_html\"><b>Signup</b></a> for this services.\n";
      &calendar_error_msg($zmsg,'calendar_error_html');
    }
  }
  if($xopr eq 'Login')
  { &calendar_error_msg('','mytravel_html'); #by Aaron
  }
  if($xopr eq 'Locator')
  { &DISPLAY; #by Aaron
  }
  if($xopr eq 'Update')
  { print ("\n");
    $vars{u_pcp}=$gtuv{u_pcp};            # phone cards
    $vars{u_loc}=$gtuv{u_loc};            # city/phones
    if($gtuv{u_account} =~ /^vip/
      || $gtuv{u_account} =~ /^vo/
      ||$gtuv{u_gtfpackage} ne '')
    {
      ($vars{strFollowmeCountry},$vars{strFollowmeArea},$vars{strFollowmeNumber})=split(/-/,$gtuv{u_followme},3);
      &calendar_error_msg('','member_update_html');
    }
    else
    { &calendar_error_msg('','member_update_basic_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');
  }
  else
  {  &calendar_error_msg('','mytravel_html'); #by Aaron
  }
}
#####################################################################
# Member update
#####################################################################
sub member_update
{ my(@zmemdata,$zmem,$zmsg);
  my($zloginid,$zpassword,$zfirstname,$zlastname,$zloc,$zjunk);
  my(@zmemupdi,$zmemval);
  my($zcityphone,$zcity,$zphone);
  my($ztype,$znum,$zpin);
  my($zc, $zp, $zcphone, $zctmp, $zordersim);
  my($ztmp1,$ztmp2);

  $zmsg='';
  ###################################################################
  # check new passwd
  ###################################################################
  if($in{strPassword1} ne '' || $in{strPwdConfirm1} ne '')
  { if($in{strPassword1} ne $in{strPwdConfirm1})
    { $zmsg .= "<li>[AK00]: 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>[AK01]: 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 cards
  ###################################################################
  for($zii=1; $zii<=$gtgv{max_phone_cards}; $zii++)
  { $ztype="strPhoneCardType$zii";
    $znum="strPhoneCardNum$zii";
    $zpin="strPhoneCardPin$zii";
    if($in{$ztype} eq '' && ($in{$znum} ne '' || $in{$zpin} ne ''))
    { $zmsg .= "<li>[AK02]: Phone card Type must be entered for <b>$in{$znum}</b> <b>$in{$zpin}</b>.\n";
    }
    elsif($in{$znum} eq '' && ($in{$ztype} ne '' || $in{$zpin} ne ''))
    { $zmsg .= "<li>[AK03]: Phone card Number must be entered for <b>$in{$ztype}</b> <b>$in{$zpin}</b>.\n";
    }
    elsif($in{$zpin} eq '' &&($in{$ztype} ne '' || $in{$znum} ne ''))
    { $zmsg .= "<li>[AK04]: Phone card PIN must be entered for <b>$in{$ztype}</b> <b>$in{$znum}</b>.\n";
    }
    $in{$znum} =~ s/ +//g;             #remove spaces
    $in{$znum} =~ s/\.+//g;            # remove period
    $in{$znum} =~ s/-+//g;            # remove dashes
    $in{$znum} =~ s/\(+//;           # remove left parenthesis
    $in{$znum} =~ s/\)+//;           # remove right parenthesis
    if($in{$znum} =~ /[^0-9]/)
    { $zmsg .= "<li>[AK05]: Phone card Number <b>$in{$znum}</b> can only contain numeric digits.\n";
    }
    $in{$zpin} =~ s/ //g;
    if($in{$zpin} =~ /[^0-9]/)
    { $zmsg .= "<li>[AK06]: Phone card PIN <b>$in{$zpin}</b> can only contain numeric digits.\n";
    }
  }
  ###################################################################
  # check city/phone pairs
  ###################################################################
  for($zii=1; $zii<=$gtgv{max_city_phones}; $zii++)
  { $zcity="strLocCity$zii";
    $zphone="strLocPhone$zii";
    if($in{$zcity} eq ''
     &&$in{$zphone} ne '')
    { $zmsg .= "<li>[AK07]: City must be entered for phone number <b>$in{$zphone}</b>.\n";
    }
    $in{$zphone} =~ s/ +//g;             #remove spaces
    $in{$zphone} =~ s/\.+//g;            # remove period
    $in{$zphone} =~ s/-+//g;            # remove dashes
    $in{$zphone} =~ s/\(+//;           # remove left parenthesis
    $in{$zphone} =~ s/\)+//;           # remove right parenthesis
    if($in{$zphone} =~ /[^0-9]/)
    { $zmsg .= "<li>[AK08]: Phone number <b>$in{$zphone}</b> can only contain numeric digits.\n";
    }
  }
  ###################################################################
  # check submit passwd
  ###################################################################
  if($in{strEmail} eq '' || $in{strPassword} eq '')
  { $zmsg .= "<li>[AK09]: Your current <b>Password</b> must be entered to submit updates!\n";
  }
  elsif($in{strEmail} eq '' || $in{UpdatePassword} eq '')                             
  { $zmsg .= "<li>[AK10]: Your current <b>Password</b> must be entered to submit updates!\n";
  }
  $in{strPassword} = $in{UpdatePassword};
  ###################################################################
  # check routing number and credit card for VIP members - aaronzz
  ###################################################################
  if ($in{strAccount} =~ /^vip/
      || $in{strAccount} =~ /^vo/)
  {
    if($in{strForwardTo} eq '')
    { $zmsg .= "<li>[AK11]: You have to enter a 1 800 PTF Number.\n";
    }
    if($in{strFollowmeCountry} =~ /\D/ || $in{strFollowmeCountry} eq '')  
    { $zmsg .= "<li>[AK12]: The 'Route To' numeric Country code must be entered.\n";  
    } 
    if($in{strFollowmeArea} =~ /\D/ || $in{strFollowmeArea} eq '')
    { $zmsg .= "<li>[AK13]: The 'Route To' numeric Area/City code must be entered.\n";  
    } 
    if($in{strFollowmeNumber} =~ /\D/ || $in{strFollowmeNumber} eq '')
    { $zmsg .= "<li>[AK14]: The 'Route To' Number code must be entered.\n";  
    } 
    $in{strFollowme}="$in{strFollowmeCountry}-$in{strFollowmeArea}-$in{strFollowmeNumber}";
    if($in{strFollowme} eq '')  
    { $zmsg .= "<li>[AK15]: The 'Route To' Destination Number must be entered.\n";  
    } 
    $ztmp1=$in{strForwardTo};
    $ztmp1 =~ s/-//g;
    $ztmp1 =~ s/\.//g;
    $ztmp2=$in{strFollowme};
    $ztmp2 =~ s/-//g;
    $ztmp2 =~ s/\.//g;
    if($ztmp2 =~ /$ztmp1/)
    { $zmsg.="<li>[AK16]: The Routing number cannot be the same as the 800 number.\n";
    }
    if($in{strPayType}  eq '')
    { $zmsg.="<li>[AK17]: You have to select payment type.\n";
    }
    if($in{strPayType} ne 'Check')
    { if($in{strCCType} eq ''
       ||$in{strCCNum}  eq ''   
       ||$in{strCCExp}  eq ''
       ||$in{strCCName} eq '')
      { $zmsg.="<li>[AK18]: Credit card information must be entered if pay by Credit Card.\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>[AK19]: 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>[AK20]: 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\n";
    &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  ###################################################################
  # merge phone card  data into one field
  ###################################################################
  $zii=0;
  $zpcp='';
  for($zii=1; $zii<=$gtgv{max_phone_cards}; $zii++)
  { $ztype="strPhoneCardType$zii";
    $znum ="strPhoneCardNum$zii";
    $zpin ="strPhoneCardPin$zii";
    if($in{$ztype} ne '')
    { $zpcp .= ":$in{$ztype}#$in{$znum}#$in{$zpin}";
    }
  }
  $zpcp=substr($zpcp,1);      # strip leading delimiter
  $gtuv{u_pcp}=$zpcp;
  ###################################################################
  # merge city/phone data into one field
  # check any new added cities - Aaron
  ###################################################################
  $zii=0;
  $vars{simcity} = '';
  $zcityphone='';
  for($zii=1; $zii<=$gtgv{max_city_phones}; $zii++)
  { $zcity="strLocCity$zii";
    $zphone="strLocPhone$zii";
    $zordersim = 'y';
    if($in{$zcity} ne '')
    { $zcityphone .= ":$in{$zcity}#$in{$zphone}";
      $zctmp=$gtuv{u_loc};
      while($zctmp ne '')
      { $zjj++;
        ($zcphone,$zctmp)=split(/:/,$zctmp,2);
        ($zc,$zp,$zjunk)=split(/\#/,$zcphone,3);
        if ($zc eq $in{$zcity})
        { $zordersim = 'n';
        }
      }
      if ($zordersim eq 'y')
      { $vars{simcity} .= "\,$in{$zcity}";
      }
    }
  }
  $vars{simcity}=substr($vars{simcity},1);
  $zcityphone=substr($zcityphone,1);  # strip leading delimiter
  $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};
  }
  ###################################################################
  # put data into gtuv, in, and var
  ###################################################################
  foreach $zfield (@gtMemCal)
  { $ztmp=$zfield;
    ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
    if ($in{$zkeyin} ne '')
    { $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("<li>member_add[02]: 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);
  $in{member_login} = 'y';
  $in{loginid} =$in{strEmail};
  $in{password} = $vars{password};
  ####################
  # set new cookie
  ####################
  if ($in{"ACTION"} eq 'member_update')
  {  if ($in{strPassword1} ne '')
     { $vars{sc_cookie}="Set-Cookie:gtlogin=$in{strEmail}|$in{strPassword1};path=/\n";        # Aaron
     }
     else
     { $vars{sc_cookie}="Set-Cookie:gtlogin=$in{strEmail}|$in{strPassword};path=/\n";        # Aaron
     }
     $vars{loadcookie} = 1;
     print ("$vars{sc_cookie}");
  }
  print "\n\n";
  &modify_800phone_email;
  if(($gtuv{u_account} =~ /^vip/ || $gtuv{u_account} =~ /^vo/)
   && $in{strFollowme} ne "$in{strFollowme1}")
  { $gtuv{voicemail} = $gtgv{voicemail};
    &send_email($gt_email_to,$vars{email_followme},%gtuv);
  }
  if ($vars{simcity} eq '')
  {  #&DISPLAY;
  &calendar_error_msg('','mytravel_html'); #by Aaron
  }
  else
  { &calendar_error_msg('','order_sim_html');
  }
#  &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,$zinfo,$zjunk);
  my($z6,$z7,$z8,$z9,$z10,$z11,$z12,$z13,$z14,$z15,$z16,$z17,$z18);
  my($zcity,$zcityphone,$zphone,$zcityphone1); #Aaron
  my($zwrk,$zfield);

  $zcgi="calendar-$vars{lang}.pl?config=".$vars{config}.'&ACTION=DISPLAY';
  $zmember_search='';
  $zmsg='';
  ###################################################################
  # Check for minimum char and invalid char
  ###################################################################
  if(length($in{strSearch}) < 3)
  { $zmsg="<li>[AL00]: Three (3) or more characters and/or numbers are needed to do the search.\n";
  }
  if($in{strSearch} =~ /\bcom\b/i      # \b is a word boundry
   ||$in{strSearch} =~ /\bnet\b/i
   ||$in{strSearch} =~ /\borg\b/i
   ||$in{strSearch} =~ /\bgov\b/i
    )
  { $zmsg.="<li>[AL01]: Domain suffixes, com, net, org, gov, are not valid search arguments";
  }
  $zwrk = $in{strSearch};
  $zwrk =~ s/ +//g;
  if($zwrk =~ /\W/i)          # \W is a non-alphanumeric char
  { $zmsg.="<li>[AL02]: Only alphanumeric characters, a-z, 0-9, and _ are allowed.";
  }
  ###################################################################
  # Read in the member file
  ###################################################################
  if($zmsg eq '')
  { if(-e "$vars{member_file}")
    { if(!open(MEMFN,"<$vars{member_file}"))
      { close(MEMLK);
        &Error("<li>member_search[01]: Can't open $vars{member_file} file for read!");
        exit;
      }
      @zmemdata=<MEMFN>;
      close(MEMFN);
    }
    #################################################################
    # Process each member entry
    #################################################################
    foreach $zmem(sort @zmemdata)
    { chomp($zmem);
      ###############################################################
      # Put a member's info into the member hash
      ###############################################################
      foreach $zkey (@gtMemDB)
      { ($gtuv{$zkey},$zmem)=split(/\|/,$zmem,2);
      }
      ###############################################################
      # Single match with userid email addr and search criteria
      ###############################################################
      if($gtuv{u_userid} eq $in{strSearch}
       &&($in{strPrivateKey} eq ''
        ||$in{strPrivateKey} eq $gtuv{u_privatekey}))
      { $zmsg='ok';
        $in{loginid}      =$gtuv{u_userid};    #Aaron
        $vars{loginid}    =$gtuv{u_userid};    #Aaron 
        $vars{strEmailAddress} =$gtuv{u_userid};    #Aaron 
        $vars{firstname}  =$gtuv{u_firstname}; #Aaron
        $vars{lastname}   =$gtuv{u_lastname};  #Aaron
        $vars{privatekey} =$gtuv{u_privatekey};  #Aaron
        &DISPLAY;                     #Aaron
        exit;                         #Aaron
      }
      ###############################################################
      # Check for a partial match with the search args
      ###############################################################
      else
      { $zwrk=$in{strSearch};
        #############################################################
        # Check each search arg separated by a space
        #############################################################
        while($zwrk)
        { ($zfield,$zwrk)=split(/ +/,$zwrk,2);
          ($userid_pfx, $zjunk)=split(/@/, $gtuv{u_userid},2); #Aaron search only email prefix
          ###########################################################
          # Search criteria met, build table entry
          ###########################################################
          if((($userid_pfx          =~ /$zfield/i
             ||$gtuv{u_firstname}   =~ /$zfield/i 
             ||$gtuv{u_lastname}    =~ /$zfield/i
             ||$gtuv{u_companyname} =~ /$zfield/i)
              &&($gtuv{u_privatekey} eq ''
               ||$gtuv{u_privatekey} eq $in{strPrivateKey}))
           && $zmember_search !~ /$gtuv{u_userid}/)   #Aaron Display Search Table
          { if ($vars{cookievalue} eq '')   # Aaron if not login, use mailto 
            { $zmember_search .= "<tr><td><font face=Arial size=2><a href=\"$zcgi&loginid=$gtuv{u_userid}&eventkey=$in{strEventkey}&firstname=$gtuv{u_firstname}&lastname=$gtuv{u_lastname}&privatekey=$in{strPrivateKey}&strEmailAddress=$gtuv{u_email}\"><u>$gtuv{u_firstname} $gtuv{u_lastname}</a></font></td><td><font face=Arial size=2><a href=\"mailto:$gtuv{u_email}\">$gtuv{u_email}</a></font></td>\n";
            }
            else # if login already, use um - Aaron
            { $zmember_search .= "<tr><td><font face=Arial size=2><a href=\"$zcgi&loginid=$gtuv{u_userid}&eventkey=$in{strEventkey}&firstname=$gtuv{u_firstname}&lastname=$gtuv{u_lastname}&privatekey=$in{strPrivateKey}&strEmailAddress=$gtuv{u_email}\"><u>$gtuv{u_firstname} $gtuv{u_lastname}</a></font></td><td><font face=Arial size=2><a href=\"mailto:$gtuv{u_email}\">$gtuv{u_email}</a></font></td>\n"; 
              # $zmember_search .= "<tr><td><font face=Arial size=2><a href=\"$zcgi&loginid=$gtuv{u_userid}&eventkey=$in{strEventkey}&firstname=$gtuv{u_firstname}&lastname=$gtuv{u_lastname}&privatekey=$in{strPrivateKey}\"><u>$gtuv{u_firstname} $gtuv{u_lastname}</a></font></td><td><font face=Arial size=2><a href=\"https://globaltalker.com/cgi-bin/calendar/calendar-Latin1.pl?config=calendar-Latin1.cfg&ACTION=goto_service&service=../compose.html&firstname=$in{firstname}&loginid=$vars{strEmailAddress}&password=$in{password}&sendto=$gtuv{u_userid}\">$gtuv{u_userid}</a></font></td>\n";
            }
            #########################################################
            # Check if phone number should be displayed
            #########################################################
            if($gtuv{u_info} eq 'none' || $gtuv{u_loc} eq '')
            { $zmember_search.="<td><font face=Arial size=2>N/A</font></td></tr>\n";
            } 
	    else
            { ($zcityphone,$zjunk)=split(/:/,$gtuv{u_loc},2);
              ($zcity,$zphone)=split(/#/,$zcityphone,2);
              $zmember_search.="<td><font face=Arial size=2>$zphone</font></td></tr>\n";
            }
          }
        }
      }
    }
  }
  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);
}
#####################################################################
# 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};
 
  &PerpetualCalendar($vars{month},1,$vars{year});
  
  $vars{monthname} = "$shortmonths[$vars{month}-1]";
  $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{'duration_range'} = "<select name=Duration_Range>\n";
  $zdate = $vars{date};
  $zmon = $vars{month};
  $zyear = $vars{year};
  $vars{sHour} = $in{shour};
  $vars{eHour} = $in{ehour};
  $zii = 0;
  for($zii=1; $zii<=14; $zii++) {
        if ($zdate <= $perp_eom)
        {  $vars{'duration_range'}.= "<option value=$zii>$shortmonths[$zmon - 1] $zdate, $zyear\n";
        }
        else
        {  if ($zmon == 12)
           {  $zyear++;
              $zmon = 1;
              $zdate = 1;
              $vars{'duration_range'}.= "<option value=$zii>$shortmonths[$zmon - 1] $zdate, $zyear\n";
           }
           else
           {  $zmon++;
              $zdate = 1;
              $vars{'duration_range'}.= "<option value=$zii>$shortmonths[$zmon - 1] $zdate, $zyear\n";
           }
        }
        $zdate++;
  }
 $vars{'duration_range'} .= "</select>\n";

   &get_variable;

   $vars{password} = $in{password};
   if ($vars{strLocCity1} ne '')
   { 
     $vars{'profile_location'} = "<script language=javascript>\n";
     $vars{'profile_location'} .= "function getvalue() {\n";
     for ($zii=1; $zii<=$zjj; $zii++)
     { $vars{'profile_location'} .= "if (document.form1.pro_location.options[$zii].selected) {\n";
       $zcitykey = "strLocCity$zii";
       $zphonekey = "strLocPhone$zii";
       $vars{'profile_location'} .= "  document.form1.location.value = '$vars{$zcitykey}';\n";
       $vars{'profile_location'} .= "  document.form1.phonenum.value = '$vars{$zphonekey}';}\n";
     }
       $vars{'profile_location'} .= "  }\n</script>\n\n";
    
     $vars{'profile_location'} .= "<select name=pro_location onChange=getvalue()>\n";
     for ($zii=0; $zii<=$zjj; $zii++)
     {  
      $zkey1 = "strLocCity$zii";
      $zkey2 = "strLocPhone$zii";
      $vars{'profile_location'} .= "<option value=\"$vars{$zkey1}|$vars{$zkey2}\">$vars{$zkey1} $vars{$zkey2}</option>\n";
      } 
      $vars{'profile_location'} .= "</select>\n";
    }
  if ($vars{add_country} ne '')
  { $ztemplate = &load_template("$vars{addcountry_html}");
  }
  else
  { $ztemplate = &load_template("$vars{addevent_html}");
  }
  $ztemplate = &parse_template($ztemplate, \%vars);
  print $ztemplate;
  exit;
}
####################################################################
# Read member info and pass them to $var{} - aaron
####################################################################
sub get_variable
{
  #################################################################
  # Read in the member file
  #################################################################
  if(!open(MEMFN,"<$vars{member_file}"))
  { close(MEMLK);
    &Error("<li>get_variable[01]: Can't open $vars{member_file} file for read!");
    exit;
  }
   @zmemdata=<MEMFN>;
   close(MEMFN);
             
  #################################################################
  # Process each member entry
  #################################################################
  foreach $zmem(sort @zmemdata)
  { chomp($zmem);
    $zmem1 = $zmem;
      ###############################################################
      # Get member info if loginid and password are valid
      ###############################################################
      foreach $zkey (@gtMemDB)
      { ($gtuv{$zkey},$zmem)=split(/\|/,$zmem,2);
      } 
      if (($gtuv{u_userid} eq $in{strEmail}) && (crypt($gtuv{u_passwd},$in{password}) eq $in{password}))
      {   foreach $zfield (@gtMemCal)
            { $ztmp1=$zfield;   
              ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp1,4);
               $vars{$zkeyvar} = $gtuv{$zkeyuv};
            }
        $ztmp=$gtuv{u_loc};
#        $zjj = 1;
        while($ztmp ne '')
        { $zjj++;
        ($zcityphone,$ztmp)=split(/:/,$ztmp,2);
        ($zcity,$zphone,$zjunk)=split(/\#/,$zcityphone,3);
        $zkey="strLocCity$zjj";
        $vars{$zkey}=$zcity;
        $zkey="strLocPhone$zjj";
        $vars{$zkey}=$zphone;
        }
     }
   }
}
#####################################################################
# 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");
  ###################################################################
  # Read in the member file
  ###################################################################
     if(!open(MEMFN,"<$vars{member_file}"))
      { close(MEMLK);
        &Error("goto_service[01]: Can't open $vars{member_file} file for read!");
        exit;
      }
      @zmemdata=<MEMFN>;
      close(MEMFN);
    
    #################################################################
    # Process each member entry
    #################################################################
    foreach $zmem(sort @zmemdata)
    { chomp($zmem);
      $zmem1 = $zmem;
      ###############################################################
      # Get member info if loginid and password are valid
      ###############################################################
      foreach $zkey (@gtMemDB)
      { ($gtuv{$zkey},$zmem)=split(/\|/,$zmem,2);
      }
      if (($gtuv{u_userid} eq $in{strEmailAddress}) && (crypt($gtuv{u_passwd},$in{password}) eq $in{password}))
      {   foreach $zfield (@gtMemCal)
            { $ztmp1=$zfield;
              ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp1,4);
               $vars{$zkeyvar} = $gtuv{$zkeyuv};
            }
        $ztmp=$gtuv{u_loc};
        while($ztmp ne '')
        { $zii++; 
        ($zcityphone,$ztmp)=split(/:/,$ztmp,2);
        ($zcity,$zphone,$zjunk)=split(/\#/,$zcityphone,3);
        $zkey="strLocCity$zii";
        $vars{$zkey}=$zcity;
        $zkey="strLocPhone$zii";
        $vars{$zkey}=$zphone;
        } 
     }
    } 

  $vars{cat}=$in{cat};
  $vars{service}=$in{service};
  $vars{password}=$in{password};
  $vars{sendto}=$in{sendto};
#  $vars{strLocPhone1} = $gtuv{u_loc}; 
  $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");
  if($xtemplate eq "1800-voffice-app.html")
  { &generate_phone_num; 
  }
  $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}/$vars{strEmailAddress}")
         || &Error("<li>read_phone_data[01]: Can't open $vars{phone_file}/$vars{strEmailAddress}");
	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,$zsms,$zjunk) = split(/\|/,$_,23); #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;
		${$phones{$in{loginid}}}{$total_phones}{sms} = $zsms;
		}
	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};
	}

	if($in{Copy} eq 'Yes') {
		&copy_phonebook;
	}
        $vars{flag} = $in{flag};

        if ($in{Update} eq 'Yes') {
	  &update_phonebook_delete('Update','');
#	  &read_phone_data;
        }
        if ($in{Delete} eq 'Yes') {
          &update_phonebook_delete('Delete','');
	  exit(0);
        }
	&read_phone_data;

        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{
        # Load the template and do the replace
        # ------------------------------------
       	  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} = "";
#foreach $i(sort keys %{$phones{$in{loginid}}}) {
foreach $i(sort keys %{$phones{$in{loginid}}}) {

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

$vars{phone_list} .="<tr bgcolor=#EEEEEE>";
if ($phones{$in{loginid}}{$i}{flag} eq 'B') {
$vars{phone_list} .="<td><font face=Arial size=2>$phones{$in{loginid}}{$i}{city}&nbsp;</font></td>\n";
$vars{phone_list} .="<td><font face=Arial size=2>$phones{$in{loginid}}{$i}{category}&nbsp; $phones{$in{loginid}}{$i}{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=$phones{$in{loginid}}{$i}{id}&firstname=$vars{firstname}&flag=$vars{flag}><font color=#000000>$phones{$in{loginid}}{$i}{company}</font></a></font></td>\n";
}
elsif ($phones{$in{loginid}}{$i}{flag} eq 'CB') {
$vars{phone_list} .="<td><font face=Arial size=2>$phones{$in{loginid}}{$i}{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=$phones{$in{loginid}}{$i}{id}&firstname=$vars{firstname}&flag=$phones{$in{loginid}}{$i}{flag}><font color=#000000>$phones{$in{loginid}}{$i}{lname}, $phones{$in{loginid}}{$i}{fname}</font></a></font></td>\n";
$vars{phone_list} .="<td><font face=Arial size=2><font color=#000000>$phones{$in{loginid}}{$i}{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=$phones{$in{loginid}}{$i}{id}&firstname=$vars{firstname}&flag=$vars{flag}><font color=#000000>$phones{$in{loginid}}{$i}{lname}, $phones{$in{loginid}}{$i}{fname}</font></a></font></td>\n";
$vars{phone_list} .="<td><font face=Arial size=2>$phones{$in{loginid}}{$i}{cphone}&nbsp;</font></td>\n";
}
$vars{phone_list} .="<td><font face=Arial size=2>$phones{$in{loginid}}{$i}{bphone}&nbsp;</font></td>\n";
if ($phones{$in{loginid}}{$i}{flag} eq 'P') {

        # $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=goto_service&service=../compose.html&loginid=$vars{loginid}&password=$vars{password}&firstname=$vars{firstname}&lastname=$vars{lastname}&sendto=$phones{$in{loginid}}{$i}{email}><font color=#000000>$phones{$in{loginid}}{$i}{email}</font></a>&nbsp;</font></td>\n";
        $vars{phone_list} .="<td><font face=Arial size=2><a href=mailto:$phones{$in{loginid}}{$i}{email}><font color=#000000>$phones{$in{loginid}}{$i}{email}</font></a>&nbsp;</font></td>\n";

        if ($phones{$in{loginid}}{$i}{email} ne '') {
	$zret=&member_get('',$phones{$in{loginid}}{$i}{email});
        } 
	if($zret == 1)
    	{ close(MEMLK);
	  $vars{phone_list} .="<td><div align=center><img src=/\%7Eglobalta/Latin1/cross.gif alt=$zret width=15 height=15 border=0></div></td>\n";
		}
	else {
                ($emailpfx, $zjunk) = split(/\@/, $phones{$in{loginid}}{$i}{email},2);
		$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=$emailpfx><img src=/\%7Eglobalta/Latin1/check.gif width=15 height=15 border=0></a></font></div></td>";
    	}
}
$vars{phone_list} .="</tr>\n\n";

if ($phones{$in{loginid}}{$i}{id} eq "$in{id}") {
		$vars{id} = $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;
                $vars{category} = ${$phones{$in{loginid}}}{$i}{category};
                $vars{subcat} = ${$phones{$in{loginid}}}{$i}{subcat};
                $vars{sms} = ${$phones{$in{loginid}}}{$i}{sms};
		}
	}
}

	# 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' && $in{lname} eq '')
        { $zmsg.="<li>[AM00]: Either <b>First Name</b> or <b>Last Name</b> is required.\n";
        }
        if($in{flag} eq 'B' && $in{company} eq '')
        { $zmsg.="<li>[AM01]: <b>Business Company</b> is required.\n";
        }
  	$in{hphone} =~ s/\.+//g;            # remove period     
  	$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 period     
  	$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 period       
  	$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 period     
  	$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;
        # get member email address for phonebook file name
        $zret=&member_get($in{loginid},'');
        if($zmsg ne '')
        { $zmsg="<ul>\n".$zmsg."</ul>\n";
          &calendar_error_msg($zmsg,'calendar_error_html');
          exit(0);
        }
		open(OUT,">> $vars{phone_file}/$gtuv{u_email}")
                  || &Error("<li>add_phone[01]: 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}|$in{sms}\n"; #Aaron
		close(OUT);

        open(IN,"<$vars{phone_file}/$gtuv{u_email}")
          || &Error("<li>add_phone[02]: Can't open $vars{phone_file}/$in{loginid} for read");
        @zpd=<IN>;
        @zpd=sort(@zpd);
        open(IN,">$vars{phone_file}/$gtuv{u_email}")
          || &Error("<li>add_phone[03]: 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};
        &calendar_error_msg('','phone_added_html');
#	&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 period
  $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 period
  $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 period
  $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 period
  $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("<li>update_phonebook_delete[01]: Can't lock the $vars{phone_lock} file by edit update/delete!");
    eval "flock PHONEK,2";
    if(-e "$vars{phone_file}/$vars{strEmailAddress}")
    { if(!open(PHONEF,"<$vars{phone_file}/$vars{strEmailAddress}"))
      { close(PHONEK);
        &Error("<li>update_phonebook_delete[02]: Can't open $vars{phone_file}/$vars{strEmailAddress} file for read by edit update/delete!");
        exit;
      }
      @zphonedata=<PHONEF>;
      close(PHONEF);
      if(!open(PHONEF,">$vars{phone_file}/$in{loginid}-tmp"))
      { close(PHONEK);
        &Error("<li>update_phonebook_delete[03]: 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,$zcategory,$zsubcat,$zsms,$zjunk) = split(/\|/,$zline,23); #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}|$in{category}|$in{subcat}|$in{sms}\n"; #Aaron
          }
          $zmsg='ok';
        }
        else
        { print PHONEF $zline;
        }
      }
      close(PHONEF);

      if($zmsg ne 'ok')
      { $zmsg="<li>[AN00]: 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}/$vars{strEmailAddress}";
      }
    }
    else
    { $zmsg="<li>[AN01]: $vars{phone_file}/$vars{strEmailAddress} does not exist for edit update/delete. Please reload/refresh your web browser views.";
    }
    close(PHONEK);
  }
        open(IN,"<$vars{phone_file}/$vars{strEmailAddress}")
          || &Error("<li>update_phonebook_delete[04}; Can't open $vars{phone_file}/$vars{strEmailAddress} for read");
        @zpd=<IN>;
        @zpd=sort(@zpd);
        open(IN,">$vars{phone_file}/$vars{strEmailAddress}")
          || &Error("i<li>update_phonebook_delete[05]: Can't open $vars{phone_file}/$vars{strEmailAddress} 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{strEmailAddress}"))
   {  if(open(PHONEF,">$vars{phone_file}/$in{strEmailAddress}"))
      { print PHONEF "#loginid|id|flag|lname|fname|home phone\n";
      }
   }
   else
   { return;
   }
}
#####################################################################
# 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("<li>copy_phonebook[01]: 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("<li>read_dest_data[01]: 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("<li>read_upload_outlook_file[01]: 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 period
		$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 period
  		$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 period
  		$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 period
  		$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("<li>copy_outlook_phonebook[01]: 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;
}
#####################################################################
# generate phone number
#####################################################################
sub generate_phone_num
{ my($zcountry)=@_;
  if ($zcountry eq '')
  { $zcountry = 'us';
  }
  $zfile = 'phone_list_file_' . "$zcountry";
  ###################################################################
  # Read in the phone number list file
  ###################################################################
  if(!open(PHONEL,"<$vars{$zfile}"))
  { &Error("<li>generate_phone_num[01]: Can't open $vars{$zfile} file for read!");
    exit;
  }
  @zphonelist=<PHONEL>;
  close(PHONEL);
             
  #################################################################
  # Process each member entry
  #################################################################
  $vars{phonelist} = "<option value=\"\">Select 1 800 Number\n";
  $znum =0;
  foreach $ztemp(@zphonelist)
  { chomp($ztemp);
    ($zphonenum, $zloginid, $zjunk) = split(/\,/,$ztemp,3);
    if ($zloginid eq '')
    { if ($zphonenum ne '')
      { $vars{phonelist} .= "<option value=\"$zphonenum\">$zphonenum\n";
        $znum++;
      }
    }
    if ($znum >= $gtgv{max_800_select})
    { last;
    }
  }
  if ($znum == 0)
  { $vars{phonelist} .= "<option>800 Number is currently not available.\n";
  }
}
#####################################################################
# sms address list
#####################################################################
sub sms_address_list
{  my($zloginid, $zid, $zflag, $zlname,$zfname);
   open(IN,"$vars{phone_file}/$vars{strEmailAddress}")
     || &Error("<li>sms_address_list[01]: Can't open $vars{phone_file}/$vars{strEmailAddress}");
   @sms_address = <IN>;
   close (IN);        
   $vars{sms_address} = "";
   foreach $zsms (@sms_address)
   { chomp($zsms);
     $ztemp = $zsms;
     foreach $zfield (@gtDataPhone)
     { ($smslist{$zfield}, $ztemp) = split(/\|/,$ztemp,2);
     }
     if ($smslist{p_sms} ne '')
     { $vars{sms_address} .= "<option value=\"$smslist{p_sms}\">$smslist{p_lname}\, $smslist{p_fname}";
     }
   }
}
#####################################################################
# modify 800 phone list
#####################################################################
sub modify_800phone_list
{ my ($ztemp, $zjunk, $zloginid, $zphonenum);
  $zcountry = $_;
  if ($zcountry eq '')
  {$zcountry = 'us';
  }
  $zfile = 'phone_list_file_' . "$zcountry";
  ###################################################################
  # Read in the phone number list file
  ###################################################################
  if(!open(PHONEL,"<$vars{$zfile}"))
  { &Error("<li>modify_800phone_list[01]: Can't open $vars{$zfile} $zfile $zcountry file for read!");
    exit;
  }
   @zphonelist=<PHONEL>;
   close(PHONEL);
  if(!open(PHONEL,">$vars{$zfile}"))
  { &Error("<li>modify_800phone_list[02]: Can't open $vars{$zfile} file for write!");
    exit;
  }
  #################################################################
  # Process each member entry
  #################################################################
  foreach $ztemp (@zphonelist)
  { chomp($ztemp);
    $ztemp2 = $ztemp;
    ($zphonenum, $zloginid, $zjunk) = split(/,/,$ztemp,3);
    if ($zloginid eq '' && $zphonenum eq $in{strForwardTo})
    { print PHONEL "$zphonenum,$in{strEmailAddress}\n";
    }
    else
    { print PHONEL "$ztemp2\n";
    }
  }
  close (PHONEL);
}
#####################################################################
# modify 800 phone file email address
#####################################################################
sub modify_800phone_email
{ my ($ztemp, $zjunk, $zloginid, $zphonenum);
  my($zedit, $zrec, $zfile);
  foreach $zrec (@gtGTFCountry)
  { ($zcountry, $zfile, $zjunk) = split(/,/,$zrec,3);
    $zedit=0;
    ###################################################################
    # Read in the phone number list file
    ###################################################################
    if(!open(PHONEL,"<$vars{$zfile}"))
    { &Error("<li>modify_800phone_email[01]: Can't open $vars{$zfile} $zfile $zcountry file for read!");
      exit;
    } 
    @zphonelist='';
    @zphonelist=<PHONEL>;
    close(PHONEL);
    if(!open(PHONEL,">$vars{$zfile}"))
    { &Error("<li>modify_800phone_email[02]: Can't open $vars{$zfile} file for write!");
      exit;
    }
    #################################################################
    # Process each member entry
    #################################################################
    foreach $ztemp (@zphonelist)
    { chomp($ztemp); 
      $ztemp2 = $ztemp;
      ($zphonenum, $zloginid, $zjunk) = split(/,/,$ztemp,3);
      if ($zphonenum eq $gtuv{u_forwardto})
      { print PHONEL "$zphonenum,$in{strEmailAddress}\n";
        $zedit=1;
      }
      else
      { print PHONEL "$ztemp2\n";
      }
    }
    close (PHONEL);
    if ($zedit == 1)
    { return;
    }
  }
  return;
}
#####################################################################
# Update Followme Number
#####################################################################
sub followme_num_update
{ my(@zmemdata,$zmem,$zmsg);
  my($ztmp1,$ztmp2,$zuserid,$zjunk);

  $zmsg='';
  ###################################################################
  # check submit passwd
  ###################################################################
  if($in{strEmail} eq '' || $in{strUDPassword} eq '')
  { $zmsg .= "<li>[AO00]: Your <b>Password</b> must be entered to submit updates!\n";
  }
  $in{strPassword} = $in{strUDPassword};
  ###################################################################
  # check new followme number
  ###################################################################
  if($in{strUdFollowmeCountry} =~ /\D/ || $in{strUdFollowmeCountry} eq '')  
  { $zmsg .= "<li>[AO01]: A new 'Route To' numeric Country code must be entered.\n";  
  } 
  if($in{strUdFollowmeArea} =~ /\D/ || $in{strUdFollowmeArea} eq '')
  { $zmsg .= "<li>[AO02]: A new 'Route To' numeric Area/City code must be entered.\n";  
  } 
  if($in{strUdFollowmeNumber} =~ /\D/ || $in{strUdFollowmeNumber} eq '')
  { $zmsg .= "<li>[AO03]: A new 'Route To' Number code must be entered.\n";  
  } 
  $in{strUdFollowme}="$in{strUdFollowmeCountry}-$in{strUdFollowmeArea}-$in{strUdFollowmeNumber}";

  if($in{strUdFollowme} eq '')
  { $zmsg .= "<li>[AO04]: You have to enter a new 'Route To' number to submit updates!\n";
  }
# $zmsg .= &ck_phone_fmt($in{strUdFollowme});
  $ztmp1=$in{strForwardTo};
  $ztmp1 =~ s/-//g;
  $ztmp1 =~ s/\.//g;
  $ztmp2=$in{strUdFollowme};
  $ztmp2 =~ s/-//g;
  $ztmp2 =~ s/\.//g;
  if($ztmp2 =~ /$ztmp1/)
  { $zmsg.="<li>[AO05]: The new 'Route To' number cannot be the same as your 800 number.\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>[AO06]: 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>[AO07]: 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;
  }
  ###################################################################
  # add new member to in-storage array
  ###################################################################
  @zmemdata=();
  foreach $zfield (@memdata)
  { chomp ($zfield);
    $ztmp=$zfield;
    $ztmp2=$zfield;
    ($zuserid,$zjunk)=split(/\|/,$ztmp,2);
    if($in{strEmail} eq $zuserid)
    { 
      ###################################################################
      # put data into gtuv, in, and var
      ###################################################################
      foreach $zkey1 (@gtMemDB)
      { ($gtuv{$zkey1},$ztmp2)=split(/\|/,$ztmp2,2);
      }
      $gtuv{u_followme} = $in{strUdFollowme};
      ###################################################################
      # create member string
      ###################################################################
      $zmemstr='';
      foreach $zkey (@gtMemDB)
      { $zmemstr .= "|$gtuv{$zkey}";
      }
      $zmemstr=substr($zmemstr,1);
      push(@zmemdata,"$zmemstr\n");
    }
    else
    { push(@zmemdata,"$zfield\n");
    }
  }
  @memdata=sort(@zmemdata);
  ###################################################################
  # output the new member file to a temp file
  ###################################################################
  if(!open(MEMFN,">$vars{member_file}-tmp"))
  { close(MEMLK);
    &Error("<li>followme_num_update[01]: 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);
  $in{member_login} = 'y';
  $in{loginid} =$in{strEmail};
  $in{password} = $vars{password};
#  &change_forwarding_number;
  &send_email($gt_email_to,$vars{email_followme},%gtuv);
  &calendar_error_msg('','mytravel_html'); #by Aaron
  return;
}
#####################################################################
# Update Callback Forwarding Number
#####################################################################
sub callback_num_update
{ my(@zmemdata,$zmem,$zmsg);
  my($zuserid,$zjunk);
  my($ztmp1,$ztmp2);

  $zmsg='';
  ###################################################################
  # check submit passwd
  ###################################################################
  if($in{strEmail} eq '' || $in{strUDPassword} eq '')
  { $zmsg .= "<li>[AP00]: Your <b>Password</b> must be entered to submit updates!\n";
  }
  $in{strPassword} = $in{strUDPassword};
  ###################################################################
  # check new followme number
  ###################################################################
  if($in{strCallbackDestNum} eq '')
  { $zmsg .= "<li>[AP01]: You have to enter a new Callback Accessing Number for update!\n";
  }
  $zmsg .= &ck_phone_fmt($in{strCallbackDestNum});
  $ztmp1=$in{strForwardTo};
  $ztmp1 =~ s/-//g;
  $ztmp1 =~ s/\.//g;
  $ztmp2=$in{strCallbackDestNum};
  $ztmp2 =~ s/-//g;
  $ztmp2 =~ s/\.//g;
  if($ztmp2 =~ /$ztmp1/)
  { $zmsg.="<li>[AP02]: The Callback Accessing Number cannot be the same as the 800 number.\n";
  }
  ###################################################################
  # check if userid and passwd match an existing user
  ###################################################################
  if($zmsg eq '')
  { $zret=&member_get($in{strEmail}, $in{strEmailAddress});
    if($zret == 1)
    { close(MEMLK);
      $zmsg .= "<li>[AP03]: Account Number, <b>$in{strEmail}</b>, not found in our database.\n";
    }
    else
    { if($gtuv{u_passwd} ne $in{strPassword})
      { close(MEMLK);
        $zmsg .= "<li>[AP04]: Email address, <b>$in{strEmailAddress}</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;
  }
  ###################################################################
  # add new member to in-storage array
  ###################################################################
  @zmemdata=();
  foreach $zfield (@memdata)
  { chomp ($zfield);
    $ztmp=$zfield;
    $ztmp2=$zfield;
    ($zuserid,$zjunk)=split(/\|/,$ztmp,2);
    if($in{strEmail} eq $zuserid)
    { 
      ###################################################################
      # put data into gtuv, in, and var
      ###################################################################
      foreach $zkey1 (@gtMemDB)
      { ($gtuv{$zkey1},$ztmp2)=split(/\|/,$ztmp2,2);
      }
      $gtuv{u_callbackdestnum} = $in{strCallbackDestNum};
      ###################################################################
      # create member string
      ###################################################################
      $zmemstr='';
      foreach $zkey (@gtMemDB)
      { $zmemstr .= "|$gtuv{$zkey}";
      }
      $zmemstr=substr($zmemstr,1);
      push(@zmemdata,"$zmemstr\n");
    }
    else
    { push(@zmemdata,"$zfield\n");
    }
  }
  @memdata=sort(@zmemdata);
  ###################################################################
  # output the new member file to a temp file
  ###################################################################
  if(!open(MEMFN,">$vars{member_file}-tmp"))
  { close(MEMLK);
    &Error("<li>callback_num_update[01]: 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);
  $in{member_login} = 'y';
  $vars{loginid} = $gtuv{u_userid};
  $vars{password}=crypt($gtuv{u_passwd},time);
  $vars{firstname} = $gtuv{u_firstname};
  $vars{lastname} = $gtuv{u_lastname};
  $vars{strEmailAddress} = $gtuv{u_email};
  &send_email($gt_email_to,$vars{email_callbackdestnum},%gtuv);
  &calendar_error_msg('','mytravel_html'); #by Aaron
  return;
}
#####################################################################
# New Update Followme Number for different Package
#####################################################################
sub followme_num_update_1
{ my(@zmemdata,$zmem,$zmsg);
  my($zloginid,$zpassword,$zfirstname,$zlastname,$zloc,$zjunk);
  my(@zmemupdi,$zmemval);
  my($z800num, $z800id, $z800owner);
  my($zextname,$znumname,@zext,$zextdigit);
  my($ztmp1,$ztmp2);

  $zmsg='';
  ###################################################################
  # check submit passwd
  ###################################################################
  if($in{strEmail} eq '' || $in{strUDPassword} eq '')
  { $zmsg .= "<li>[AQ00]: Your <b>Password</b> must be entered to submit updates!\n";
  }
  $in{strPassword} = $in{strUDPassword};
  ###################################################################
  # check if userid and passwd match an existing user
  ###################################################################
  if($zmsg eq '')
  { $zret=&member_get($in{strEmail});
    if($zret == 1)
    { close(MEMLK);
      $zmsg .= "<li>[AQ01]: 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>[AQ02]: <b>Password</b> is incorrect.\n";
      }
    }
  }
  ###################################################################
  # check if userid and 800Number match and exist
  ###################################################################
  $z800owner = 0;
  if ($in{strForwardTo} ne '')
  { if(!open(PHONEL,"<$vars{phone_list_file}"))
    { &Error("<li>followme_num_update_1[01]: Can't open $vars{phone_list_file} file for read!");
      exit;
    }
    @zphonelist=<PHONEL>;
    close(PHONEL);
    foreach $zrec (@zphonelist)
    { chomp ($zrec);
      ($z800num, $z800id, $zjunk) = split(/,/,$zrec,3);
      if ($z800num eq $in{strForwardTo} && $z800id eq $in{strEmail})
      { $z800owner = 1;
        last;
      }
    }
    if ($z800owner == 0)
    { $zmsg .= "<li>[AQ03]: You are not the owner of the 1 800 GTF number you entered.\n";
    }
  }
  else
  { $zmsg .= "<li>[AQ04]: You have to enter a 1800 GTF Number.\n";
  }
  ###################################################################
  # get member info from member database
  ###################################################################
  @zmemdata=@memdata;
  foreach $zfield (@memdata)
  { chomp ($zfield);
    $ztmp=$zfield;
    $ztmp2=$zfield;
    ($zuserid,$zjunk)=split(/\|/,$ztmp,2);
    if($in{strEmail} eq $zuserid)
    { 
      ###################################################################
      # put data into gtuv, in, and var
      ###################################################################
      foreach $zkey1 (@gtMemDB)
      { ($gtuv{$zkey1},$ztmp2)=split(/\|/,$ztmp2,2);
      }
    }
  }
  ###################################################################
  # Check new modified data
  ###################################################################
  if ($gtuv{u_gtfpackage} eq 'A' || $gtuv{u_gtfpackage} eq 'B')
  { if($in{strFollowme} eq '')
    { $zmsg .= "<li>[AQ05]: A Route-to Destination Number must be entered.\n";
    }
    $in{strFollowme} = '|'.$in{strFollowme};
  }
  $zextnumber = 0;
  $zextdigit = 0;
  if ($gtuv{u_gtfpackage} eq 'C' || $gtuv{u_gtfpackage} eq 'D')
  { for ($zii=1; $zii<10; $zii++)
    { $zextname = 'strGTFExtension'.$zii;
      $znumname = 'strFollowme'.$zii;
      $zext[$zii] = $in{$zextname};
      $zext[$zii] =~ s/-//g;
      $zext[$zii] =~ s/\.//g;
      $znum = $in{$znumname};
      $znum =~ s/-//g;
      $znum =~ s/\.//g;
      $gtuv{$zextname} = $zext[$zii];
      $gtuv{$znumname} = $znum;
      if($znum =~ /$in{strForwardTo}/)
      { $zmsg.="<li>[AQ06]: The Routing number cannot be the same as the 800 number.\n";
      }
      if(length($zext[$zii]) != $zextdigit && $zextdigit !=0 && $zext[$zii] ne '')
      { $zmsg .= "<li>[AQ07]: All extension must have the same amount of digit.\n";
      }      
      for ($zjj=1; $zjj<10; $zjj++)
      { if ($zjj >= $zii)
        { last;
        }
        elsif ($zext[$zii] eq $zext[$zjj] && $zext[$zjj] ne '')
        { $zmsg .= "<li>[AQ08]: Extension cannot be the same.\n";
        }
      }
      if($zext[$zii] ne ''
       && $znum eq '')
      { $zmsg .= "<li>[AQ09]: A Route-to Destination Number must be entered if you entered an Extension.\n";
      }
      elsif($znum ne ''
       && $zext[$zii] eq '')
      { $zmsg .= "<li>[AQ10]: An Extension must be entered if you entered a Route-to Destination Number.\n";
      }
      elsif ($znum ne '' && $zext[$zii] ne '')
      { $in{strGTFExtension} .= "\#$zext[$zii]";
        $in{strFollowme} .= "\#$znum";
        if ($zextdigit == 0)
        { $zextdigit = length($zext[$zii]);
        }
        $zextnumber++;
      }
      if($zext[$zii] =~ /[^0-9]/ || $znum =~ /[^0-9]/) 
      { $zmsg .= "<li>[AQ11]: GTF Extension or GTF Route to Destination Number can only contain numeric characters\n";
      }
    }
    if($zextnumber == 0)
    { $zmsg .= "<li>[AQ12]: At least 1 Extension Number and Route-to Destination Number need to be entered.\n";
    }  
  }
  if ($gtuv{u_gtfpackage} eq 'D')
  { if ($in{strGTF6Extension} eq '')
    { $zmsg .= "<li>[AQ13]: GTF Personal Outbound Call Extension is required.\n";
    }
    if ($in{strGTFPassword} eq '' || length($in{strGTFPassword}) < 8)
    { $zmsg .= "<li>[AQ14]: GTF password is required and must be at least 8 digits long.\n";
    }
    if($in{strGTF6Extension} =~ /[^0-9]/ || $in{strGTFPassword} =~ /[^0-9]/)
    { $zmsg .= "<li>[AQ15]: GTF Personal Outbound Call Extension or GTF Password can only contain numeric characters\n";
    }
    for ($zkk=1; $zkk<10; $zkk++)
    { if ($in{strGTF6Extension} eq $zext[$zkk] && $zext[$zkk] ne '')
      { $zmsg .= "<li>[AQ16]: GTF Personal Outbound Call Extension cannot be the same as any GTF Extension Number.\n";
      }
    }
    if(length($in{strGTF6Extension})!= $zextdigit && $zextdigit !=0)
    { $zmsg .= "<li>[AQ17]: All extension must have the same amount of digit.\n";
    } 
  }
  $in{strGTFExtension}=substr($in{strGTFExtension},1);
  $in{strFollowme}=substr($in{strFollowme},1);

  # Copy new values to gtuv
  $gtuv{u_gtfextension} = $in{strGTFExtension};
  $gtuv{u_followme} = $in{strFollowme};
  $gtuv{u_gtf6extension} = $in{strGTF6Extension};
  $gtuv{u_gtfpassword} = $in{strGTFPassword};
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  { &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  ###################################################################
  # add new member to in-storage array
  ###################################################################
  @zmemdata1=();
  foreach $zfield (@zmemdata)
  { chomp($zfield); #aaronzzz
    $ztmp=$zfield;
    $ztmp2=$zfield;
    ($zuserid,$zjunk)=split(/\|/,$ztmp,2);
    if($in{strEmail} eq $zuserid)
    { ###################################################################
      # create member string
      ###################################################################
      $zmemstr='';
      foreach $zkey (@gtMemDB)
      { $zmemstr .= "|$gtuv{$zkey}";
      }
      $zmemstr=substr($zmemstr,1);
      push(@zmemdata1,"$zmemstr\n");
    }
    else
    { push(@zmemdata1,"$zfield\n");
    }
  }
  @memdata=sort(@zmemdata1);
  ###################################################################
  # output the new member file to a temp file
  ###################################################################
  if(!open(MEMFN,">$vars{member_file}-tmp"))
  { close(MEMLK);
    &Error("<li>followme_num_update_1[02]: 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);
  $in{member_login} = 'y';
  $in{loginid} =$in{strEmail};
  $in{password} = $vars{password};
  ###################################################################
  # sent out email with the proper template
  ###################################################################
  $ztemplate= $vars{email_followme};
  foreach $zrec (@gtGTFEmailFollowme)
  { ($zpack, $zemail, $zjunk) = split(/,/,$zrec,3);
    if($zpack eq $gtuv{u_gtfpackage})
    { $ztemplate = $vars{$zemail};
    }
  }
  &send_email('aaron2@infinex.com',$ztemplate,%gtuv);
#  &calendar_error_msg('','update_gtf_html'); #by Aaron
  ###################################################################
  # display the proper html page
  ###################################################################
  foreach $zfield (@gtMemCal)
  { $ztmp=$zfield;
    ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
    $vars{$zkeyvar}=$gtuv{$zkeyuv};
  }
  if($gtuv{u_account} =~ /^vip/
      || $gtuv{u_account} =~ /^vo/)
  {  &calendar_error_msg('',"$in{Page}"); 
  }
  elsif($gtuv{u_gtfpackage} ne '')
  { foreach $zrec (@gtGTFModify)
    { ($zplan, $zhtml, $zjunk) = split(/,/,$zrec,3);
      if ($gtuv{u_gtfpackage} eq $zplan)
      { $ztemp = $gtuv{u_gtfextension};
        $ztemp1 = $gtuv{u_followme};
        for($zii=1; $zii<10; $zii++)
        { ($zext, $ztemp) = split (/\#/,$ztemp,2);
          ($znum, $ztemp1) = split (/\#/,$ztemp1,2);
          if($zext eq '')
          { last;
          }
          $zextname = 'strExtension'.$zii;
          $znumname = 'strFollowme'.$zii;
          $vars{$zextname} = $zext;
          $vars{$znumname} = $znum;
        }
        &calendar_error_msg('',"$zhtml");
      }
    }
    &calendar_error_msg('','mytravel_html');
  }
  return;
}

#####################################################################
# add calling time
#####################################################################
sub add_calling_time
{
  my($zsuccess,$zresult,$zccmsg,$zauthcode,$zavs,$zccerr,%zan);

  ###################################################################
  # check submit passwd
  ###################################################################
  if($in{strEmail} eq '' || $in{AddPassword} eq '')
  { $zmsg .= "<li>[AR00]: Your <b>Password</b> must be entered to submit updates!\n";
  }
  $in{strPassword} = $in{AddPassword};
  ###################################################################
  # check new followme number
  ###################################################################
  if($in{strCCType} eq ''
     ||$in{strCCNum}  eq ''
     ||$in{strCCExp}  eq ''
     ||$in{strCCName} eq '')
  { $zmsg.="<li>[AR01]: Credit card information must be entered for Adding Calling Time.\n";
  }
  if($in{aa_airtime} eq '')
  { $zmsg.="<li>[AR02]: You must select an airtime package.\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>[AR03]: 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>[AR04]: Email address (login id), <b>$in{strEmail}</b>, and password, <b>$in{strPassword}</b>, not found in our database.";
      }
    }
  }
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  { &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  ###################################################################
  # debit credit card
  ###################################################################
#xxxxx
  ($zsuccess,$zresult,$zccmsg,$zauthcode,$zavs,$zccerr)=
    &debit_credit_card
      ("GT Add Calling Time",
       sprintf("%0.2f",$in{aa_airtime}),
       $in{strCCType},
       $in{strCCNum},
       $in{strCCExp},
       $in{strCCName},
       $in{strFirstName},
       $in{strLastName},
       $in{strStreet},
       $in{strCity},
       $in{strState},
       $in{strZip},
       $in{strCountry}
      );
  if($zsuccess ne 'Y')
  { $zmsg .= "<li>[AI19]: $zccmsg, AVS=$zavs, $zccerr\n";
  }
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  { &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  ###################################################################
  # 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};
  }
  $gtuv{aa_airtime} = $in{aa_airtime};
  &send_email($gt_email_to,$vars{email_airtime},%gtuv);
  &send_email($gt_email_billing_to,$vars{email_airtime_billing},%gtuv);
  &calendar_error_msg('','mytravel_html'); #by Aaron
  return;
}
#####################################################################
# ck phone number format
#####################################################################
sub ck_phone_fmt
{ my($xnum)=@_;
  my($znum,$zmsg,$zext,@znumlist,$znumrec);
  my($zpcntry,$zparea,$zpnum,$zpnum2,$zjunk);
  
  $zmsg='';
  @znumlist=split(/,/,$xnum);
  foreach $znumrec (@znumlist)
  { ($znum,$zext)=split(/#/,$znumrec,2);
    if($znum =~ /[^\d.-]/)
    { $zmsg .= "<li>[AS00]: <b>$znum</b> can only contain digits 0-9, - and .\n";
    }
    if($zext ne ''
     &&$zext !~ /[^0-9]/)
    { $zmsg .= "<li>[AS01]: <b>$zext,/b> can only contain digits 0-9.\n";
    }
    $znum =~ s/\./-/g;        # change all . to -
    $znum =~ s/-\(/-/g;       # change all -( to -
    $znum =~ s/\)-/-/g;       # change all )- to -
    $znum =~ s/\(/-/g;        # change all ( to -
    $znum =~ s/\)/-/g;        # change all ) to -
    ($zpcntry,$zparea,$zpnum,$zpnum2,$zpjunk)=split(/-/,$znum,5);
    if($zpjunk eq ''
     &&$zpnum2 ne '')
    { $zpnum .= $zpnum2;      # concat last two digit fields
      $zpnum2 = '';
    }
# Default by aaron to make life easier for user
#    if($zpcntry eq ''
#     ||$zparea  eq ''
#     ||$zpnum   eq ''
#     ||$zpjunk  ne '')
#    { $zmsg .= "<li>[AS02]: <b>$znum</b> must be in the <b>Country-City-Number</b> format.\n";
#    }
  }
  return($zmsg);
}
#####################################################################
# 800 number member upgrade from basic to vip step 1 - personal info
#####################################################################
sub member_upgrade_step_1
{ my ($zmsg);
  ###################################################################
  # check if userid existing
  ###################################################################
  $zret=&member_get($in{strEmail},'');
    if($zret == 1)
    { close(MEMLK);
      $zmsg .= "<li>[AT00]: Account Number, <b>$in{strEmail}</b>, not found in our database!\n";
    }
    else
    { if(crypt($gtuv{u_passwd},$in{strPassword}) ne $in{strPassword} && $gtuv{u_passwd} ne $in{strPassword})
      { close(MEMLK);
        $zmsg.="<li>[AT01]: Account Number, <b>$in{strEmail}</b> and password not found in our database.\n";
      }
    }
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  { print ("\n");
    &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }  
  foreach $zfield (@gtMemCal)
  { $ztmp=$zfield;
    ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
    if ($in{$zkeyin} eq '')
    { $vars{$zkeyvar}=$gtuv{$zkeyuv};
    }
    else
    { $vars{$zkeyvar}=$in{$zkeyin};
    }
  }
  $vars{password}=crypt($gtuv{u_passwd},time);
}
#####################################################################
# 800 number member upgrade from basic to vip step 1 - personal info
#####################################################################
sub member_upgrade_step_2
{ my ($zmsg);
  ###################################################################
  # check arguments
  ###################################################################
  if($in{strPayType}  eq '')
  { $zmsg.="<li>[AU00]: You have to select payment type.\n";
  }
  if($in{strPayType} ne 'Check')
  { if($in{strCCType} eq ''
     ||$in{strCCNum}  eq ''   
     ||$in{strCCExp}  eq ''
     ||$in{strCCName} eq '')
    { $zmsg.="<li>[AU01]: Credit card information must be entered if paying by credit card.\n";
    }
  }
  if($in{countrynumber} eq '')
  { $zmsg .= "<li>[AU02]: The 800 number home country must be selected.\n";
  }
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  { print ("\n");
    &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  $vars{countrynumber} = $in{countrynumber};
  &calendar_error_msg('','member_upgrade_step2_html');
}
#####################################################################
# Upgrade member from Basic to Vip
#####################################################################
sub member_upgrade
{ my(@zmemdata,$zmem,$zmsg);
  my($zloginid,$zpassword,$zfirstname,$zlastname,$zloc,$zjunk);
  my($ztmp1,$ztmp2);

  $zmsg='';
  ###################################################################
  # check submit passwd
  ###################################################################
  if($in{strEmail} eq '' || $in{AddPassword} eq '')
  { $zmsg .= "<li>[AV00]: Your <b>Password</b> must be entered to submit updates!\n";
  }
  $in{strPassword} = $in{AddPassword};
  ###################################################################
  # check new followme number
  ###################################################################
  if($in{strForwardTo} eq '')
  { $zmsg .= "<li>[AV01]: You have to select a 1 800 PTF Number.\n";
  }
  if($in{strFollowme} eq '')
  { $zmsg .= "<li>[AV02]: You have to enter a Routing Number.\n";
  }
  if($in{strFollowme} =~ /[^\d-.,]/)
  { $zmsg .= "<li>[AV03]: The Routing Number can only contain 0-9, - and ...\n";
  }
  $ztmp1=$in{strForwardTo};
  $ztmp1 =~ s/-//g;
  $ztmp1 =~ s/\.//g;
  $ztmp2=$in{strFollowme};
  $ztmp2 =~ s/-//g;
  $ztmp2 =~ s/\.//g;
  if($ztmp2 =~ /$ztmp1/)
  { $zmsg.="<li>[AV04]: The Routing number cannot be the same as the 800 number.\n";
  }
  if($in{strCCType} eq ''
     ||$in{strCCNum}  eq ''
     ||$in{strCCExp}  eq ''
     ||$in{strCCName} eq '')
  { $zmsg.="<li>[AV05]: Credit card information must be entered for upgrade to VIP accounts.\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>[AV06]: 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>[AV07]: 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;
  }
  ###################################################################
  # add new member to in-storage array
  ###################################################################
  @zmemdata=();
  foreach $zfield (@memdata)
  { $ztmp=$zfield;
    $ztmp2=$zfield;
    ($zuserid,$zjunk)=split(/\|/,$ztmp,2);
    if($in{strEmail} eq $zuserid)
    { 
      $in{strSignupDate} = $vars{'datestamp'}; #copy signup date
      &add_to_tracking;
      ###################################################################
      # put data into gtuv, in, and var
      ###################################################################
      foreach $zkey (@gtMemDB)
      { ($gtuv{$zkey},$ztmp2)=split(/\|/,$ztmp2,2);
      }
      foreach $zfield1 (@gtMemCal)
      { $ztemp=$zfield1;
        ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztemp,4);
        if ($in{$zkeyin} ne '')
        { $gtuv{$zkeyuv} = $in{$zkeyin};
          $vars{$zkeyvar}=$in{$zkeyin};
        }
      }
      ###################################################################
      # create member string
      ###################################################################
      $zmemstr='';
      foreach $zkey1 (@gtMemDB)
      { $zmemstr .= "|$gtuv{$zkey1}";
      }
      $zmemstr=substr($zmemstr,1);
      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("<li>member_upgrade[01]: 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);
  $in{member_login} = 'y';
  $in{loginid} =$in{strEmail};
  $vars{loginid} = $in{loginid};
  $in{password} = $vars{password};
  &modify_800phone_list;     #aaron
  $gtuv{voicemail} = $gtgv{voicemail};
  &send_email($gt_email_to,$vars{email_signup},%gtuv);
  &calendar_error_msg('','mytravel_html'); #by Aaron
  return;
}
#####################################################################
# parse_rows
# 
# parse_rows( $tag , $template_string , \%value_array )
# $template = &parse_output( "EVENTS" , $template , $rows );
# Loop through values array and replace <%OUTPUT $tag%> </%OUTPUT%>
# 
#####################################################################
sub parse_rows {
	my ($tag) = shift;
	my ($template) = shift;
	my ($rows) = shift;

	# Parse the <%OUTPUT%> <%/OUTPUT%> tags for record format
	my ($format) = ($template =~ m|<%ROW $tag%>(.+?)<%/ROW%>|si);
	my($output) = "";
	my($key,$tmp,$tmp2);
	# Loop through data and create output data
	for ($zii=1; $zii<=$rows; $zii++) {
		$tmp = $format;
     		$tmp =~ s|<%=zii%>|$zii|sg;                
		$output .= $tmp;
		}

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

	return $template;
	}
#####################################################################
# Check 800 number status # aaron
#####################################################################
sub check_800_num 
{ my ($ztemp, $zjunk, $zloginid, $zphonenum);
  $vars{loginid} = $in{strEmail};
  $vars{password} = $in{strPassword};
  if ($vars{loginid} eq 'admin' || $vars{loginid} eq '1002')
  { &calendar_error_msg('','admin_800_num_html'); #by Aaron
  }
  elsif ($vars{loginid} eq 'billing' || $vars{loginid} eq '1004')
  { if($vars{billingdetail} eq 'Yes')
    { &calendar_error_msg('','billing_800_num_detail_html'); #by Aaron
    }
    else
    { &calendar_error_msg('','billing_800_num_html'); #by Aaron
    }
  }
  elsif ($vars{loginid} eq 'infinex' || $vars{loginid} eq '1005')
  { if($vars{billingdetail} eq 'Yes')   
    { &calendar_error_msg('','infinex_800_num_detail_html'); #by Aaron
    }
    else
    { &calendar_error_msg('','infinex_800_num_html'); #by Aaron
    }
  }
  else
  { $zmsg .= "<li>[AW00]: Page not found.\n";
    &calendar_error_msg($zmsg,'calendar_error_html');
  }
  exit;
}
#####################################################################
# modify 800 phone list by admin
#####################################################################
sub modify_800_num
{ my ($ztemp, $zjunk, $zloginid, $zphonenum);
  ###################################################################
  # Read in the phone number list file
  ###################################################################
  if(!open(PHONEL,"<$vars{phone_list_file}"))
  { &Error("<li>modify_800_num[01]: Can't open $vars{phone_list_file} file for read!");
    exit;
  }
  @zphonelist=<PHONEL>;
  close(PHONEL);
  if(!open(PHONEL,">$vars{phone_list_file}"))
  { &Error("<li>modify_800_num[02]: Can't open $vars{phone_list_file} file for write!");
    exit;
  }
  #################################################################
  # Process each member entry
  #################################################################
  foreach $ztemp (@zphonelist)
  { chomp($ztemp);
    $ztemp2 = $ztemp;
    ($zphonenum, $zloginid, $zjunk) = split(/,/,$ztemp,3);
    if ($zphonenum eq $in{str800number} && $in{Remove} eq '')
    { print PHONEL "$zphonenum,$in{str800owner}\n";
    }
    elsif ($zphonenum eq $in{str800number} && $in{Remove} ne '')
    { next;
    }
    else
    { print PHONEL "$ztemp2\n";
    }
  }
  close (PHONEL);
  $vars{loginid} = $in{strEmail};
  $vars{password} = $in{strPassword};
  &calendar_error_msg('','admin_800_num_html'); #by Aaron
}
#####################################################################
# edit 800 phone list, move used number to the bottom of the list
#####################################################################
sub remove_800_num
{ my ($ztemp, $zjunk, $zloginid, $zphonenum);
  ###################################################################
  # Read in the phone number list file
  ###################################################################
  if(!open(PHONEL,"<$vars{phone_list_file}"))
  { &Error("<li>modify_800_num[01]: Can't open $vars{phone_list_file} file for read!");
    exit;
  }
  @zphonelist=<PHONEL>;
  close(PHONEL);
  if(!open(PHONEL,">$vars{phone_list_file}"))
  { &Error("<li>modify_800_num[02]: Can't open $vars{phone_list_file} file for write!");
    exit;
  }
  #################################################################
  # Process each member entry
  #################################################################
  foreach $ztemp (@zphonelist)
  { chomp($ztemp);
    $ztemp2 = $ztemp;
    ($zphonenum, $zloginid, $zjunk) = split(/,/,$ztemp,3);
    if ($zphonenum eq $in{strForwardTo})
    { $znum = $zphonenum;  
    }
    else
    { print PHONEL "$ztemp2\n";
    }
  }
  if ($znum ne '')
  { print PHONEL "$znum,\n";
  }
  close (PHONEL);
  $vars{loginid} = $in{strEmail};
  $vars{password} = $in{strPassword};
  return;
}
#####################################################################
# modify 800 phone list
#####################################################################
sub add_800_num
{ my ($ztemp, $zjunk, $znewnum, $znumstr);
  ###################################################################
  # Read in the phone number list file
  ###################################################################
  if(!open(PHONEL,"<$vars{phone_list_file}"))
  { &Error("<li>add_800_num[01]: Can't open $vars{phone_list_file} file for read!");
    exit;
  }
  @zphonelist=<PHONEL>;
  close(PHONEL);
  if(!open(PHONEL,">$vars{phone_list_file}"))
  { &Error("<li>add_800_num[02]: Can't open $vars{phone_list_file} file for write!");
    exit;
  }
  #################################################################
  # Process each member entry
  #################################################################
  $ztemp = $in{new800num};
  while ($ztemp ne '')
  { ($znewnum, $ztemp) = split(/,/,$ztemp,2);
    if ($znewnum =~ /[^0-9-]/)
    { $zmsg .= "<li>[AX00]: 800 Numbers can only contain numeric characters\n";
       last;
    }
    else
    { $znumstr = "$znewnum,";
      push(@zphonelist,"$znumstr\n");
    }
  }
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  { &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  #Write to file
  foreach $ztemp (@zphonelist)
  { print PHONEL "$ztemp";
  }
  close (PHONEL);
  $vars{loginid} = $in{strEmail};
  $vars{password} = $in{strPassword};
  &calendar_error_msg('','admin_800_num_html'); #by Aaron
}
#####################################################################
# Read 800 Numbers for other purpose # aaron
#####################################################################
sub read_800number
{ my (@zphonelist);
  if(!open(PHONEL,"<$vars{phone_list_file}"))
  { &Error("<li>read_800number[01]: Can't open $vars{phone_list_file} file for read!");
    exit;
  }
  @zphonelist=<PHONEL>;
  close(PHONEL);
}

#####################################################################
# Write 800 signup data to web store tracking file
#####################################################################
sub add_to_tracking
{ my($zt, $zpack, $zfee);
  my($zedate, $zeyear, $zemonth);
        
  ###############################################
  # create additional variable for member d/b
  ############################################### 
  $in{strLastPayDate} = $vars{datestamp};
  ($in{strAccount},$in{strPayPeriod},$zjunk) = split (/\-/,$in{strAccount},3);

#  if($in{strPayPeriod} eq '' || $in{strPayPeriod} < 0 || $in{strPayPeriod} > 13)
#  { $zmsg .= "<LI>Account type is not a valid selection.\n";
#  }
  ##############################
  # define commission package
  ##############################
  $zaccttype=substr($in{gtaffid},0,1);
  if ($in{strAffNumber} ne '')
  { $zaccttype=substr($in{strAffNumber},0,1);
  }

  if ($in{gtaffid} ne '' || $in{strAffNumber} ne '')
  { if ($zaccttype eq '')
    { $in{strCommPackage} = 'A';
    }
    else
    { $in{strCommPackage} = $zaccttype;
    }
  }
  ########################
  # look up Service fee
  ########################
  if ($in{ACTION} eq 'aff_signup_800_step_2')
  { if ($in{strEmail} eq $in{strEmailAddress})
    { $in{strAccount} = $in{strAccount} . '_dis';
      $in{strCommPackage} = '';
      $in{gtaffid} = '';
      $vars{affnumber} = $in{strAffNumber};
      $in{strAffNumber} = '';
    }
  }
  foreach $zt (@gtPackagePrice)
  { ($zpack, $zfee, $zjunk) = split (/,/,$zt,3);
    if ($in{strAccount} eq $zpack)
    { $in{strFee} = $zfee;
    }
  }
  if ($in{strAccount} eq 'vip_special')
  { &get_special_rate($in{strAffNumber});
    $in{strFee} = $vars{special_price1};
  }

#  if($in{strFee} eq '')
#  { $zmsg .= "<LI>Account type is not a valid selection.\n";
#  }
  $in{strCurrentMonth} = 1; # num of month after activation
  $in{strPaidMonth} = $in{strPayPeriod}; #num of months actually paid
  ############################
  # create next payment date
  ############################
  $zedate = $mday;
  $zeyear = $year;
  $zemonth = $month + $in{strPayPeriod};
  if ($zemonth > 12)
  { $zemonth -= 12;
    $zeyear++;
  }
  @eofday = (31,28,31,30,31,30,31,31,30,31,30,31);
  if ($eofday[$zemonth-1] < $zedate)
  { $zedate = $eofday[$zemonth-1];
  }
  $in{strNextPayDate} = sprintf("%4.4d%2.2d%2.2d",$zeyear,$zemonth,$zedate);
  ###################################################################
  # exit if any errors   
  ###################################################################
  if($zmsg ne '')
  { &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  return;
}
#####################################################################
# 
#####################################################################
sub add_to_comm_tracking
{ if ($in{strGTAffID} ne '')
  {
  ##########################################
  # add to commission file and cal commission
  ##########################################
  open(IN,"<$vars{aff_file_dir}/comm-$year-$month") || open(IN,">$vars{aff_file_dir}/comm-$year-$month");
  @commlist=<IN>;
  close(IN);

  foreach $zgp (@gtCommissionPackage)
  { chomp($zgp);
    ($zgpackage, $zyr1, $zjunk) = split (/,/,$zgp,3);
    if ($gtgv{gtcomm} eq $zgpackage)
    { $vars{zcommission} = $vars{zfee} * $zyr1;
      last;
    }
  }
  $vars{zpfmonth} = $months[$month-1];

  foreach $zrec2 (@gtAffComm)
  { ($z1, $z2, $zjunk) = split (/,/,$zrec2,3);
    $zcommstring .= "|$vars{$z2}";
  }
  $zcommstring=substr($zcommstring,1);
  push(@commlist,"$zcommstring\n");
  
  #write to Affiliate file
  open(OUT,">$vars{aff_file_dir}/comm-$year-$month")
    || &Error("<li>add_to_comm_tracking[01]: Can't open $vars{aff_file_dir}/comm-$year-$month for write");
  print OUT @commlist;
  close(OUT);
  }
}
#####################################################################
# Billing function to display 800 number list - Aaronzzz
# template lines from parse_template routine.
#####################################################################
sub billing_800_numbers
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zrec, $z1, $z2, $zjunk, $zg);
  my(@afflist);
  undef %zhash;
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables

  $zresult='';                                  # reset output
  if(!open(AFF,"<$xhash{member_file}"))
  { &Error("<li>billing_800_numbers[01]: Can't open $xhash{member_file} file for read!");
    exit;
  }
  @afflist=<AFF>;
  @afflist1=@afflist;
  close(AFF);
  $xhash{ii}=0;                                 # start at 1
  foreach $zrec (@afflist)
  { chomp ($zrec);
    foreach $zg (@gtMemDB)
    {  ($zhash{$zg},$zrec)=split(/\|/,$zrec,2);
    }
    if (($in{searchAccount} eq '' || $zhash{u_userid} =~ /^$in{searchAccount}/g)
     && ($in{searchEmail} eq '' || $zhash{u_email} =~ /^$in{searchEmail}/g)
     && ($in{searchAffiliate} eq '' || $zhash{u_gtaffid} =~ /^$in{searchAffiliate}/g) 
     && ($in{search800num} eq '' || $zhash{u_forwardto} =~ /^$in{search800num}/g) 
     && ($in{searchLName} eq '' || $zhash{u_lastname} =~ /^$in{searchLName}/g)
     && ($in{searchFName} eq '' || $zhash{u_firstname} =~ /^$in{searchFName}/g)
     && ($in{searchSignupDate} eq '' || $zhash{u_signupdate} =~ /^$in{searchSignupDate}/g)
     && ($in{searchLastPayDate} eq '' || $zhash{u_lastpaydate} =~ /^$in{searchLastPayDate}/g )
     && $zhash{u_forwardto} ne '')

    { $zresult.=$xtemplate;                       # concat template to result
      foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
      { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
        if ($zhash{$zkey} ne '')
        { $zresult =~ s/<%=$zkey%>/$zhash{$zkey}/g; # replace with value
        }
        else
        { $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
        }
      }
      $xhash{ii}++;
    }
  }
  return($zresult);                             # return result
}
#####################################################################
# Affiliate function to display referal status - Aaronzzz
# template lines from parse_template routine.
#####################################################################
sub affiliate_signup_numbers
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zrec, $z1, $z2, $zjunk, $zg);
  my($zcomm,$zkey);
  my($zo,$zrate1,$zrate2,$zrate3);
  my(@afflist);
  undef %zhash;
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables
  my($zdate,$zaccount,$zcomm);
  $vars{thismonthvipsignup} = 0;
  $vars{totalvipsignup} = 0;
  $vars{thismonthvosignup} = 0;
  $vars{totalvosignup} = 0;
  $vars{thismonthcomm} = 0;
  $vars{totalcomm} = 0;
  $vars{ii} =0;
  $zresult='';                                  # reset output
  if(!open(AFF,"<$xhash{member_file}"))
  { &Error("<li>affiliate_signup_numbers[01]: Can't open $xhash{member_file} file for read!");
    exit;
  }
  @afflist=<AFF>;
  @afflist1=@afflist;
  close(AFF);
  if ($in{searchMonth} eq 'thismonth')
  { $zdate = sprintf("%4.4d%2.2d",$vars{year},$vars{month});
    $vars{cyear} = $year;
    $vars{cmonth} = $months[$month-1];
  }
  else
  { $zdate = $in{searchMonth};
    $vars{cyear} = substr($in{searchMonth},0,4);
    $zzmonth = substr($in{searchMonth},4,2);
    $vars{cmonth} =$months[$zzmonth-1];
  }
  foreach $zrec (@afflist)
  { chomp ($zrec);

    foreach $zg (@gtMemDB)
    {  ($zhash{$zg},$zrec)=split(/\|/,$zrec,2);
    }
    if ($zhash{u_gtaffid} =~ /^$in{strAffNumber}/g 
    && ($zhash{u_account} =~ /^vip/
      || $zhash{u_account} =~ /^vo/))
    { $vars{ii}++;
      ###################################
      # count total for different product
      ###################################
      if ($zhash{u_account} =~ /^vip/)
      { $zaccount = 1;
        $vars{totalvipsignup}++;
      }
      elsif ($zhash{u_account} =~ /^vo/)
      { $zaccount = 2;
        $vars{totalvosignup}++;
      }
      ################################
      # commission rate lookup
      ################################
      foreach $zco (@gtCommissionPackage)
      { ($zcomname, $zrate1, $zrate2, $zrate3, $zjunk) = split (/,/, $zco, 5);
        if ($zcomname eq $zhash{u_commpackage})
        { $vars{commpercent} = $zrate1;
          last;
        }
      }
#      $vars{totalcomm} += $zhash{u_fee};
      #########################################
      #calculate number of months after signup
      #########################################
      $zsignupyear= substr($zhash{u_signupdate},0,4);
      $zsignupmonth = substr($zhash{u_signupdate},4,2);
      $zsignupdate = substr($zhash{u_signupdate}, 6,2);
#      if ($mday > $zsignupdate)
#      { $zzdate++;
#      }
      $zzyear = $year - $zsignupyear;
      $zmonthnum = $zzyear *12 + $month - $zsignupmonth + 1;
      ######################
      # calculate commision
      ######################
      if ($zmonthnum <= 12)
      {  $zcomm = $zhash{u_fee} * $zrate1 *$zmonthnum;
      }
      elsif ($zmonthnum >12 && $zmonthnum <=24)
      {  $zcomm = $zhash{u_fee} * 12 *$zrate1;
         $zcomm += ($zhash{u_fee} * ($zmonthnum-12) * $zrate2); 
      }
      else
      {  $zcomm = $zhash{u_fee} * 12 *$zrate1;
         $zcomm += $zhash{u_fee} * 12 * $zrate2;
         $zcomm += $zhash{u_fee} * ($zmonthnum-24)* $zrate3; 
      }
      int($zcomm);
      $vars{totalcomm} += $zcomm/100;
      ######################################
      # display data for a particular month
      ######################################
      if ($zdate eq '' || $zhash{u_signupdate} =~ /^$zdate/g)
      { if ($zaccount == 1)
        { $vars{thismonthvipsignup}++;
        }
        elsif ($zaccount == 2)
        { $vars{thismonthvosignup}++;
        }
        $vars{thismonthcomm} += ($zcomm/100);
        $zresult.=$xtemplate;                       # concat template to result
        foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
        { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
          if ($zhash{$zkey} ne '')
          {  $zresult =~ s/<%=$zkey%>/$zhash{$zkey}/g; # replace with value
          }
          else
          { $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
          }
        }
      }
    }
  }
  if ($vars{ii} == 0)
  { foreach $zco (@gtCommissionPackage)
    { ($zcomname, $zrate1, $zjunk) = split (/,/, $zco, 3);
      if ($zcomname eq $gtgv{gtcomm})
      { $vars{commpercent} = $zrate1;
        last;
      }
    }
  }
  return($zresult);                             # return result
}
#####################################################################
# Affiliate update
#####################################################################
sub affiliate_update
{ my(@zmemdata,$zmem,$zmsg);
  my($zloginid,$zpassword,$zfirstname,$zlastname,$zloc,$zjunk);
  my(@zmemupdi,$zmemval);
  my($ztmp1,$ztmp2);

  $zmsg='';
  ###################################################################
  # check new passwd
  ###################################################################
  if($in{strPassword1} ne '' || $in{strPwdConfirm1} ne '')
  { if($in{strPassword1} ne $in{strPwdConfirm1})
    { $zmsg .= "<li>[AY00]: 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>[AY01]: 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 submit passwd
  ###################################################################
  if($in{strAffNumber} eq '' || $in{UpdatePassword} eq '')                             
  { $zmsg .= "<li>[AY02]: Your current <b>Password</b> must be entered to submit updates!\n";
  }
  $in{strPassword} = $in{UpdatePassword};
  ###################################################################
  # check if userid and passwd match an existing user
  ###################################################################
  if($zmsg eq '')
  { $zret=&affiliate_lookup($in{strAffNumber});
    if($zret == 1)
    { close(MEMLK);
      $zmsg .= "<li>[AY03]: Email address (login id), <b>$in{strEmail}</b>, not found in our database.\n";
    }
    else
    { if($gtuv{aff_passwd} ne $in{strPassword})
      { close(MEMLK);
        $zmsg .= "<li>[AY04]: 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;
  }
  ###################################################################
  # put data into gtuv, in, and var
  ###################################################################
  $in{strStatus} = 'affiliate';
  foreach $zfield (@gtAffData)
  { $ztmp=$zfield;
    ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
    $vars{$zkeyvar}=$in{$zkeyin};
    $gtuv{$zkeyuv}=$in{$zkeyin};
  }
  ###################################################################
  # ck for new passwd 
  ###################################################################
  if($in{strPassword1} ne ''
   &&$in{strPassword1} eq $in{strPwdConfirm1})
  { $gtuv{aff_passwd}=$in{strPassword1};
    $in{strPassword}=$in{strPassword1};
  }
  ###################################################################
  # create member string
  ###################################################################
  $zmemstr='';
  foreach $zkey (@gtAffDB)
  { $zmemstr .= "|$gtuv{$zkey}";
  }
  $zmemstr=substr($zmemstr,1);
  ###################################################################
  # encrypt passwd that is displayed on web pages
  ###################################################################
  $vars{strPassword}=crypt($gtuv{aff_passwd},time);
  $vars{password}=$vars{strPassword};
  ###################################################################
  # add new member to in-storage array
  ###################################################################
  @zmemdata=();
  foreach $zfield (@affdata)
  { $ztmp=$zfield;
    ($znumber,$zjunk)=split(/\|/,$ztmp,2);
    if($gtuv{aff_number} eq $znumber)
    { push(@zmemdata,"$zmemstr\n");
    }
    else
    { push(@zmemdata,$zfield);
    }
  }
  @affdata=@zmemdata;
  ###################################################################
  # output the new member file to a temp file
  ###################################################################
  if(!open(MEMFN,">$vars{aff_file}-tmp"))
  { close(MEMLK);
    &Error("<li>affiliate_update[01]: Can't open $vars{aff_file}-tmp file for write!");
  }
  print MEMFN @affdata;
  close(MEMFN);
  ###################################################################
  # rename the file to the main member file name
  ###################################################################
  rename "$vars{aff_file}-tmp","$vars{aff_file}";
  close(MEMLK);
  $in{loginid} =$in{strEmail};
  $in{password} = $vars{password};
  &calendar_error_msg('','aff_menu_html'); #Aaron
  return;
}

#####################################################################
# Billing update
#####################################################################
sub billing_update
{ my(@zmemdata,$zmem,$zmsg);
  my($zloginid,$zpassword,$zfirstname,$zlastname,$zloc,$zjunk);
  my(@zmemupdi,$zmemval);
  my($ztmp1,$ztmp2);

  $zmsg='';
  ###################################################################
  # check require field
  ###################################################################
  if($in{strPayType} eq 'Credit Card')
  { if($in{strCCType} eq ''
      ||$in{strCCNum}  eq ''
      ||$in{strCCExp}  eq ''
      ||$in{strCCName} eq '')
   { $zmsg.="<li>[AZ00]: Credit card information must be entered.\n";
   }
  }
  ###################################################################
  # check if userid and passwd match an existing user
  ###################################################################
  if($zmsg eq '')
  { $zret=&member_get('1004','');
    $zret1=&member_get($in{strMemberEmail},'');
    if($zret1 == 1)
    { close(MEMLK);
      $zmsg .= "<li>[AZ01]: Email address (login id), <b>$in{strMemberEmail}</b>, not found in our database.\n";
    }
  }
  if ($in{strForwardTo} ne $gtuv{u_forwardto})
  { $zmsg .= "<li>[AZ02]: 800 Number submiited ($in{strForwardto}) does not match the number in our database.\n";
  }
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  { &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
  ###################################################################
  # put data into gtuv, in, and var
  ###################################################################
  if ($in{strNewMemo} ne '')
  { $in{strNewMemo} =~ s|[\r\n]+|<br>|gs;
    $gtuv{u_memo} .= "$shortmonths[$month-1] $mday, $year: $in{strNewMemo}\<br\>";
  }
  if ($in{strNewStatus} ne '')
  { $in{strStatus} = $in{strNewStatus};
  }
  else
  { $in{strStatus} = $gtuv{u_status};
  }
  foreach $zfield (@gtBillDB)
  { $ztmp=$zfield;
    ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
    $vars{$zkeyvar}=$in{$zkeyin};
    $gtuv{$zkeyuv}=$in{$zkeyin};
  }
  if ($in{strPayment} ne '')
  { &make_payment(%gtuv);
    $gtuv{u_nextpaydate} = $vars{strNextPayDate};
    $gtuv{u_lastpaydate} = $vars{strLastPayDate};
    $gtuv{u_paidmonth} += $gtuv{u_payperiod};
  }
  if ($in{downgrade} ne '')
  { $gtuv{u_account} = 'basic';
    $gtuv{u_forwardto} = '';
    &remove_800_num;
  }
  ###################################################################
  # 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("<li>billing_update[01]: 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);
  $in{member_login} = 'y';
  $in{loginid} =$in{strEmail};
  $in{password} = $vars{password};
  return;
}
#####################################################################
# Get payment history data from db
#####################################################################
sub payment_history
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zrec, $z1, $z2, $zjunk, $zg);
  my(@afflist);
  undef %zhash;
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables

  $zresult='';                                  # reset output
  if(!open(PAYHIST,"<$xhash{payment_history_file}"))
  { &Error("<li>payment_history[01]: Can't open $xhash{payment_history_file} file for read!");
    exit;
  }
  @paylist=<PAYHIST>;
  @paylist1=@paylist;
  close(PAYHIST);
  $xhash{ii}=0;                                 # start at 1
  foreach $zrec (@paylist)
  { chomp ($zrec);
    foreach $zg (@gtPayDB)
    { ($zg,$zjunk) = split (/,/,$zg,2);
       ($zhash{$zg},$zrec)=split(/\|/,$zrec,2);
    }
    if ($zhash{pay_loginid} =~ /^$in{strMemberEmail}/g)
    { $zresult.=$xtemplate;                       # concat template to result
      foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
      { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
        if ($zhash{$zkey} ne '')
        { $zresult =~ s/<%=$zkey%>/$zhash{$zkey}/g; # replace with value
        }
        else
        { $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
        }
      }
      $xhash{ii}++;
    }
  }
  return($zresult);                             # return result
}
#####################################################################
# Read forwarding history data from db
#####################################################################
sub read_forwarding_history
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zrec, $z1, $z2, $zjunk, $zg);
  my(@numlist);
  undef %zhash;
  my($zkey,$zresult);       # internal variables

  $zresult='';                                  # reset output
  if(!open(NUMHIST,"<$xhash{forwarding_history_file}"))
  { &Error("<li>read_forwarding_history[01]: Can't open $xhash{forwarding_history_file} file for read!");
    exit;
  }
  @numlist=<NUMHIST>;
  @numlist1=@numlist;
  close(PAYHIST);
  $xhash{ii}=0;                                 # start at 1
  foreach $zrec (@numlist)
  { chomp ($zrec);
    foreach $zg (@gt800histDB)
    { ($zg,$zjunk) = split (/,/,$zg,2);
       ($zhash{$zg},$zrec)=split(/\|/,$zrec,2);
    }
    if ($zhash{his_acctnum} =~ /^$in{strEmail}/g)
    { $zresult.=$xtemplate;                       # concat template to result
      foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
      { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
        if ($zhash{$zkey} ne '')
        { $zresult =~ s/<%=$zkey%>/$zhash{$zkey}/g; # replace with value
        }
        else
        { $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
        }
      }
      $xhash{ii}++;
    }
  }
  return($zresult);                             # return result
}
#####################################################################   
# Add change forwaring number info to forwarding history file
#####################################################################
sub change_forwarding_number
{   my(%xgtuv)=@_;
    if(!open(NUMHIST,"<$vars{forarding_history_file}"))
    { close(NUMHIST);
      &Error("<li>change_forwarding_number[01]: Can't open $vars{forwarding_history_file} file for read!");
      exit;
    }
    @nhist=<NUMHIST>;
    close(NUMHIST);    
    foreach $zfield (@gt800histDB)
    { $ztmp=$zfield;
      ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
      if ($zkeyin ne '')
      { $znum{$zkeyuv}=$xgtuv{$zkeyin};
      }
    }    
    ###################################################################
    # create payment history string
    ###################################################################
    $zpaystr='';
    foreach $zfield1 (@gt800histDB)
    { ($zkey,$zjunk)=split(/,/,$zfield1,2);
      $znumstr .= "|$znum{$zkey}";
    }
    $znumstr=substr($znumstr,1);

    foreach $zrec (@nhist)
    { chomp ($zrec);
      $zrec1 = $zrec;
      ($z800num, $zacctnum, $zjunk) = split(/,/,$zrec,3);
      if ($z800num eq $in{strForwardTo} && $zacctnum eq $in{strEmail})
      { foreach $zfield1 (@gt800histDB)
        { ($zkey,$zjunk)=split(/,/,$zfield1,2);
          if ($zkey eq 'his_enddate')
          { $znumstr1 .= "|$datestamp";
          }
          else
          { $znumstr1 .= "|$zkey";
          }
        }
        $znumstr1 = substr($znumstr1,1);
        push(@nhist1,"$znumstr1\n");
      }
      else
      { push(@nhist1,"$zrec1\n");
      }
    }
    push(@nhist1,"$znumstr\n");
    ###################################################################
    # output the new payment file to a temp file
    ###################################################################
    if(!open(NUMHIST,">$vars{forwarding_history_file}-tmp"))
    { close(NUMHIST);
      &Error("<li>change_forwarding_number[02]: Can't open $vars{forwarding_history_file}-tmp file for write!");
    }
    print NUMHIST @nhist1;
    close(NUMHIST);
    ###################################################################
    # rename the file to the main payment history file name
    ###################################################################
    rename "$vars{forwarding_history_file}-tmp","$vars{forwarding_history_file}";
    return;   
}
#####################################################################   
# Add payment info to payment history file
#####################################################################
sub make_payment
{   my(%xgtuv)=@_;
    $znpyear = substr($xgtuv{u_nextpaydate},0,4);
    $znpmonth = substr($xgtuv{u_nextpaydate},4,2);
    $znpdate = substr($xgtuv{u_nextpaydate},6);
    $znpmonth += $xgtuv{u_payperiod};
    if ($znpmonth >12)
    { $znpmonth -= 12;
      $znpyear += 1;
    }
    $zpay{pay_spayperiod} = $xgtuv{u_nextpaydate};
    $xgtuv{u_nextpaydate} = sprintf("%4.4d%2.2d%2.2d",$znpyear,$znpmonth,$znpdate);
    $zpay{pay_epayperiod} = $xgtuv{u_nextpaydate};
    $xgtuv{u_lastpaydate} = sprintf("%4.4d%2.2d%2.2d",$year,$month,$mday);
    $zpay{pay_totalfee} = $xgtuv{u_fee} * $xgtuv{u_payperiod};

    $vars{strNextPayDate} = $xgtuv{u_nextpaydate};
    $vars{strLastPayDate} = $xgtuv{u_lastpaydate};

    if(!open(PAYHIST,"<$vars{payment_history_file}"))
    { close(PAYHIST);
      &Error("<li>make_payment[01]: Can't open $vars{payment_history_file} file for read!");
      exit;
    }
    @phist=<PAYHIST>;
    close(PAYHIST);    
    foreach $zfield (@gtPayDB)
    { $ztmp=$zfield;
      ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
      if ($zkeyin ne '')
      { $zpay{$zkeyuv}=$xgtuv{$zkeyin};
      }
    }    
    ###################################################################
    # create payment history string
    ###################################################################
    $zpaystr='';
    foreach $zfield1 (@gtPayDB)
    { ($zkey,$zjunk)=split(/,/,$zfield1,2);
      $zpaystr .= "|$zpay{$zkey}";
    }
    $zpaystr=substr($zpaystr,1);
    push(@phist,"$zpaystr\n");
    ###################################################################
    # output the new payment file to a temp file
    ###################################################################
    if(!open(PAYHIST,">$vars{payment_history_file}-tmp"))
    { close(PAYHIST);
      &Error("<li>make_payment[02]: Can't open $vars{payment_history_file}-tmp file for write!");
    }
    print PAYHIST @phist;
    close(PAYHIST);
    ###################################################################
    # rename the file to the main payment history file name
    ###################################################################
    rename "$vars{payment_history_file}-tmp","$vars{payment_history_file}";
}
#####################################################################   
# Add payment entry to the payment history file
#####################################################################
sub fail_payment
{   my($zmsg,%xgtuv)=@_;
    open(FAILPAY,"$vars{fail_payment_file}-$vars{currentdatestamp}.txt");
#   || &Error("<li>fail_payment[01]: Can't open $vars{fail_payment_file}-$vars{currentdatestamp}.txt file for read!");
    my(@faillist) ='';
    @faillist=<FAILPAY>;
    close(FAILPAY);
    foreach $zfield (@gtFailPayDB)
    { $ztmp=$zfield;
      ($zkeyuv,$zkeyin,$zkeyvar,$zjunk)=split(/,/,$ztmp,4);
      if ($zkeyin ne '')
      { $zpay{$zkeyuv}=$xgtuv{$zkeyin};
      }
    }    
    $zpay{fa_failmessage} = $zmsg;
    $zpay{fa_totalfee} = $zpay{fa_fee} * $xgtuv{u_payperiod};
    ###################################################################
    # create payment history string
    ###################################################################
    $zpaystr='';
    foreach $zfield1 (@gtFailPayDB)
    { ($zkey,$zjunk)=split(/,/,$zfield1,2);
      $zpaystr .= "|$zpay{$zkey}";
    }
    $zpaystr=substr($zpaystr,1);
    push(@faillist,"$zpaystr\n");
    ###################################################################
    # output the new payment file to a temp file
    ###################################################################
    if(!open(FAILPAY,">$vars{fail_payment_file}-tmp"))
    { close(FAILPAY);
      &Error("<li>fail_payment[02]: Can't open $vars{fail_payment_file}-tmp file for write!");
    }
    print FAILPAY @faillist;
    close(FAILPAY);
    ###################################################################
    # rename the file to the main payment history file name
    ###################################################################
    rename "$vars{fail_payment_file}-tmp","$vars{fail_payment_file}-$vars{currentdatestamp}.txt";
}
#####################################################################
# Billing function to display 800 number list - Aaronzzz
# template lines from parse_template routine.
#####################################################################
sub send_info_to_cybercash
{  my($zcode,$zstatus,$zauthcode,$zavs,$zmsg,$zjunk);
   my($zfail);
   print "<!--  sc_cybercash_code ne ''  -->\n";
   if($sc_cybercash_code ne '')
   {  open(MEMLK,">$vars{member_lock}")
      || &Error("<li>send_info_to_cybercash[01]: 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("<li>send_info_to_cybercash[02]: Can't open $vars{member_file} file for read!");
          exit;
        }
        @memdata=<MEMFN>;
        close(MEMFN);
      }
      else
      { @memdata=();
      }
      foreach $zrec (sort @memdata)
      { $ztmp=$zrec;
        chomp($ztmp);
        foreach $zkey (@gtMemDB)
        { ($gtuv{$zkey},$ztmp)=split(/\|/,$ztmp,2);
        }
        if ($gtuv{u_nextpaydate} eq $vars{currentdatestamp})
        {  
          if($gtuv{$sc_cc_exp} ne ''
           &&$gtuv{$sc_cc_exp_mt} eq ''
           &&$gtuv{$sc_cc_exp_yr} eq '')
          { ($gtuv{$sc_cc_exp_mt},$gtuv{$sc_cc_exp_yr},$zjunk)=split(/\//,$gtuv{$sc_cc_exp},3);
          }
          $ztotalfee = $gtuv{u_fee} * $gtuv{u_payperiod};
          require($sc_cybercash_code);
          open(ONUM,"<$vars{order_num}")
           || &Error("<li>send_info_to_cybercash[03]: Can't open $vars{order_num} file for read!");
          $gtuv{order_num} = <ONUM>;          
          close (ONUM);
          ($zcode,$zstatus,$zauthcode,$zavs,$zmsg)=&$sc_cybercash_pgm
             (
              $gtuv{order_num},  # order number
              $sc_cc_currency,
#              $gtuv{$sc_cc_total},
              $ztotalfee,
              $gtuv{$sc_cc_number},
              $gtuv{$sc_cc_owner},
              $gtuv{$sc_cc_street},
              $gtuv{$sc_cc_city},
              $gtuv{$sc_cc_state},
              $gtuv{$sc_cc_zip},
              $gtuv{$sc_cc_country},
              $gtuv{$sc_cc_exp_mt}, 
              $gtuv{$sc_cc_exp_yr}
             );
          if($zcode =~ /000/
           &&$zstatus =~ /success/i)
          { $gtuv{$sc_cc_vdate}=$gtuv{$sc_order_date};
            if($zavs eq '')
            { $zavs='Y';
            }
            &make_payment(%gtuv);
#            $gtuv{$sc_cc_status}="OK,AVS=$zavs $zauthcode";
#            print "<!-- payment success -->\n";
#            print "<tr><td>$gtuv{u_userid}</td>\n";
#            print "<td><b>SUCCESS</b></td></tr>\n";
#           print "<br>Authorization code: $zauthcode\n";
            open(ONUM,">$vars{order_num}")
             || &Error("<li>send_info_to_cybercash[04]: Can't open $vars{order_num} file for read!");
            $gtuv{order_num}++;
            print ONUM "$gtuv{order_num}\n";   
            close (ONUM);
          }
          else
          { 
# print "<!-- payment fail -->\n";
#            print "<tr><td>$gtuv{u_userid}</td>\n";
#            print "<td><b>FAIL</b> - $zmsg</td></tr>\n";
            &fail_payment($zmsg,%gtuv);
            $zfail = "Yes";
          }
        }
      }
      if ($zfail ne '')
      { &calendar_error_msg('','cybercash_fail_html');
      }
      else
      { &calendar_error_msg('','cybercash_pass_html');
      }
   }
}
#####################################################################
# Billing function to display 800 number list that fail cybercash- Aaronzzz
# template lines from parse_template routine.
#####################################################################
sub billing_cybercash_fail
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zrec, $z1, $z2, $zjunk, $zg);
  my(@afflist);
  undef %zhash;
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables

  $zresult='';                                  # reset output
  if(!open(AFF,"<$xhash{fail_payment_file}-$vars{currentdatestamp}.txt"))
  { &Error("<li>billing_cybercash_fail[01]: Can't open $xhash{member_file}-$vars{currentdatestamp}.txt file for read!");
    exit;
  }
  @afflist=<AFF>;
  @afflist1=@afflist;
  close(AFF);
  $xhash{ii}=0;                                 # start at 1
  foreach $zrec (@afflist)
  { chomp ($zrec);
    foreach $zg (@gtFailPayDB)
    { ($zfa, $zu, $zjunk) = split(/,/,$zg,3);
      if ($zu ne '')
      { ($zhash{$zu},$zrec)=split(/\|/,$zrec,2);
      }
      else
      { ($zhash{$zfa},$zrec)=split(/\|/,$zrec,2);
      }
    }
    $zresult.=$xtemplate;                       # concat template to result
    foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
    { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
      if ($zhash{$zkey} ne '')
      { $zresult =~ s/<%=$zkey%>/$zhash{$zkey}/g; # replace with value
      }
      else
      { $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
      }
    }
    $xhash{ii}++;
  }
  return($zresult);                             # return result
}
#####################################################################
# Display for billing - 800 grand total activity
#   show summary for each month
#####################################################################
sub billing_800_grand_total
{ my($xtemplate,%xhash)=@_;                     # input args
  my($ztotmin,$zresult,@zcalls);
  my($zrec,$zkey);

  ###################################################################
  # init values
  ###################################################################
  $vars{ptf_code}   =$in{ptf_code};
  $vars{member_id}  =$in{member_id};
  $vars{totcharge}  =0;
  $vars{totcost}    =0;
  $vars{totABNDN}   =0;
  $vars{totBUSY}    =0;
  $vars{totERR}     =0;
  $vars{totNOANS}   =0;
  $vars{totNODT}    =0;
  $vars{totNOOUT}   =0;
  $vars{totNORB}    =0;
  $vars{totOPINT}   =0;
  $vars{totCNCT}    =0;
  $vars{totminutes} =0;
  $vars{totnoCNCT}  =0;
  $vars{totnocharge}=0;
  $vars{totcalls}   =0;

  $xhash{ptf_code}  =$in{ptf_code};
  $xhash{member_id} =$in{member_id};
  $xhash{nbsp}      ='&nbsp;';
  $xhash{ii}        =0;

  $zresult          ='';
  ###################################################################
  # get gt-switch log directory contents.
  #  log directory has one file per month.
  #  file name is yyyy-mm
  ###################################################################
  if(!opendir(DIR,"$vars{gt_switch_cdr_log}"))
  { $zmsg="<li>ck_calling_record_summary[01]: Unable to open <b>$vars{gt_switch_cdr_log}</b> directory for read.\n";
    &Error($zmsg);
    exit;
  }
  @zdirfns=readdir(DIR);
  closedir(DIR);
  ###################################################################
  # process each month's gt-switch log file
  ###################################################################
  foreach $zfn(sort @zdirfns)
  { next if(substr($zfn,0,1) ne '2');
    @zcalls =`grep -h "|logged|" $vars{gt_switch_cdr_log}/$zfn`;
    $xhash{bs_charge}=0;
    $xhash{bs_cost}=0;
    $xhash{bs_timein}=0;
    $xhash{bs_timeout}=0;
    $xhash{bs_timetot}=0;
    $xhash{bs_ABNDN}=0;
    $xhash{bs_BUSY} =0;
    $xhash{bs_ERR}  =0;
    $xhash{bs_NOANS}=0;
    $xhash{bs_NODT} =0;
    $xhash{bs_NOOUT}=0;
    $xhash{bs_NORB} =0;
    $xhash{bs_OPINT}=0;
    $xhash{bs_CNCT} =0;
    $xhash{bs_noCNCT}=0;
    $xhash{bs_nocharge}=0;
    $xhash{bs_calls}=0;
    ($xhash{bs_year},$xhash{bs_month})=split(/-/,$zfn,2);
    $xhash{bs_date}="$xhash{bs_month}-$xhash{bs_year}";
    $xhash{bs_date}="$shortmonths[$xhash{bs_month}-1] $xhash{bs_year}";
    $xhash{bs_date}="$xhash{bs_month}/$xhash{bs_year}";
    foreach $zrec (@zcalls)
    { chomp($zrec);
      ###############################################################
      # put rec info into log hash
      ###############################################################
      foreach $zkey (@gtLogDB)
      { ($xhash{$zkey},$zrec)=split(/\|/,$zrec,2);
      }
      next if($xhash{b_opr} ne 'logged');
      ###############################################################
      # check for specific account and ptf code
      ###############################################################
      next if($in{member_id} ne '' && $in{member_id} ne $xhash{b_id});
      next if($in{ptf_code} !~ /all/i && $in{ptf_code} ne $xhash{b_code});
      ###############################################################
      # increment call status totals
      ###############################################################
      $xhash{bs_calls}++;
      if   ($xhash{b_code} eq 'ABNDN') {$xhash{bs_ABNDN}++;}
      elsif($xhash{b_code} eq 'BUSY')  {$xhash{bs_BUSY}++;} 
      elsif($xhash{b_code} eq 'NOANS'
         || $xhash{b_code} eq 'RNA')   {$xhash{bs_NOANS}++;}
      elsif($xhash{b_code} eq 'NODT')  {$xhash{bs_NODT}++;}
      elsif($xhash{b_code} eq 'NOOUT') {$xhash{bs_NOOUT}++;}
      elsif($xhash{b_code} eq 'NORB')  {$xhash{bs_NORB}++;}
      elsif($xhash{b_code} eq 'OPINT') {$xhash{bs_OPINT}++;}
      elsif($xhash{b_code} eq 'CNCT')  {$xhash{bs_CNCT}++;}
      else                             {$xhash{bs_ERR}++;} 
      ###############################################################
      # calc call min and amount for CNCT calls
      ###############################################################
      if($xhash{b_code} eq 'CNCT')
      { if($xhash{b_timetot} ne '')
        { $ztotmin=$xhash{b_timetot};
        }
        else
        { $ztotmin=sprintf("%d",($xhash{b_timein}+$xhash{b_timeout}+59)/60);
        }
        $xhash{bs_timetot}+=$ztotmin;
        $xhash{bs_charge}+=$xhash{b_charge};
        $xhash{bs_cost}+=$xhash{b_charge_om};
        $xhash{bs_timein}+=$xhash{b_timein};
        $xhash{bs_timeout}+=$xhash{b_timeout};
      }
      ###############################################################
      # calc call min and amount for non-CNCT calls
      ###############################################################
      else
      { if($xhash{b_timetot} ne '')
        { $ztotmin=$xhash{b_timetot};
        }
        else
        { $ztotmin=sprintf("%d",($xhash{b_timein}+$xhash{b_timeout}+59)/60);
        }
        $xhash{bs_noCNCT}+=$ztotmin;
        $xhash{bs_nocharge}+=$xhash{b_charge};
        $xhash{bs_notimein}+=$xhash{b_timein};
        $xhash{bs_notimeout}+=$xhash{b_timeout};
      }
    }
    #################################################################
    # accumulate totals
    #################################################################
    next if($xhash{bs_calls} == 0);
    $xhash{ii}++;
    $vars{totABNDN}+=$xhash{bs_ABNDN};
    $vars{totBUSY} +=$xhash{bs_BUSY};
    $vars{totERR}  +=$xhash{bs_ERR};
    $vars{totNOANS}+=$xhash{bs_NOANS};
    $vars{totNODT} +=$xhash{bs_NODT};
    $vars{totNOOUT}+=$xhash{bs_NOOUT};
    $vars{totNORB} +=$xhash{bs_NORB};
    $vars{totOPINT}+=$xhash{bs_OPINT};
    $vars{totCNCT} +=$xhash{bs_CNCT};
    $xhash{bs_charge}=sprintf("%0.2f",$xhash{bs_charge});
    $vars{totcharge}+=$xhash{bs_charge};
    $vars{totcost}+=$xhash{bs_cost};
    $vars{totminutes}+=$xhash{bs_timetot};
    $vars{totnocharge}+=$xhash{bs_nocharge};
    $vars{totnoCNCT}+=$xhash{bs_noCNCT};
    $vars{totcalls}+=$xhash{bs_calls};
    #################################################################
    # fill in template with data for each month of gt-switch log file
    #################################################################
    $ztemplate=$xtemplate;                          # get copy of template
    foreach $zkey($ztemplate =~ /<%=.*?%>/g)        # <%=key%> in template
    { $zkey=substr($zkey,3,length($zkey)-5);        # get actual key
      if ($xhash{$zkey} ne '')
      { $ztemplate =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
      }
      else
      { $ztemplate =~ s/=<%=$zkey%>/=$xhash{$zkey}/g; # replace with value
        $ztemplate =~ s/<%=$zkey%>/$xhash{nbsp}/g;  # replace with space
      }
    }
    $zresult.=$ztemplate;                           # append processed template
  }
  ###################################################################
  # ensure only two decimal points in total charge
  ###################################################################
  $vars{totcharge}=sprintf("%0.2f",$vars{totcharge});
  return($zresult);                                 # return result
}
#####################################################################
# Display for billing - 800 month total activity
#   show all users that used 800 services for the specified month
#####################################################################
sub billing_800_month_total
{ my($xtemplate,%xhash)=@_;                     # input args
  my($ztotmin,$zresult,@zcalls);
  my($zrec,$zkey);

  ###################################################################
  # init values
  ###################################################################
  $vars{ptf_code}   =$in{ptf_code};
  $vars{member_id}  =$in{member_id};
  $vars{bs_date}    =$in{bs_date};
  $vars{Month}      =$in{Month};
  $vars{Year}       =$in{Year};
  $vars{totcharge}  =0;
  $vars{totABNDN}   =0;
  $vars{totBUSY}    =0;
  $vars{totERR}     =0;
  $vars{totNOANS}   =0;
  $vars{totNODT}    =0;
  $vars{totNOOUT}   =0;
  $vars{totNORB}    =0;
  $vars{totOPINT}   =0;
  $vars{totCNCT}    =0;
  $vars{totminutes} =0;
  $vars{totnoCNCT}  =0;
  $vars{totnocharge}=0;
  $vars{totcalls}   =0;

  $xhash{ptf_code}  =$in{ptf_code};
  $xhash{member_id} =$in{member_id};
  $xhash{nbsp}      ='&nbsp;';
  $xhash{ii}        =0;
  $zresult          ='';
  ###################################################################
  # get gt-switch log directory contents for one month.
  #  log directory has one file per month.
  #  file name is yyyy-mm
  ###################################################################
  $zfn="$vars{gt_switch_cdr_log}/$in{'Year'}-$in{'Month'}";
  open(FN,"<$zfn");
  @zmtdb=<FN>;
  close(FN);
  ###################################################################
  # accumulate list of all gt vip members who were called during the month
  ###################################################################
  @zmtdbtmp=@zmtdb;
  @zmtmemdb=();
  foreach $zrec (@zmtdbtmp)
  { chomp $zrec;
    #################################################################
    # put rec info into log hash
    #################################################################
    foreach $zkey (@gtLogDB)
    { ($xhash{$zkey},$zrec)=split(/\|/,$zrec,2);
    }
    next if($xhash{b_opr} ne 'logged');
    ###############################################################
    # check for specific account and ptf code
    ###############################################################
    next if($in{member_id} ne '' && $in{member_id} ne $xhash{b_id});
    next if($in{ptf_code} !~ /all/i && $in{ptf_code} ne $xhash{b_code});
    push(@zmtmemdb,$xhash{b_id}) unless(grep (/^$xhash{b_id}$/,@zmtmemdb));
  }
  ###################################################################
  # process each vip member who was called during this month
  ###################################################################
  foreach $zuid (sort @zmtmemdb)
  { @zcalls=@zmtdb;
    $xhash{bs_calls}=0;
    $xhash{bs_charge}=0;
    $xhash{bs_timein}=0;
    $xhash{bs_timeout}=0;
    $xhash{bs_timetot}=0;
    $xhash{bs_ABNDN}=0;
    $xhash{bs_BUSY} =0;
    $xhash{bs_ERR}  =0;
    $xhash{bs_NOANS}=0;
    $xhash{bs_NODT} =0;
    $xhash{bs_NOOUT}=0;
    $xhash{bs_NORB} =0;
    $xhash{bs_OPINT}=0;
    $xhash{bs_CNCT} =0;
    $xhash{bs_noCNCT}=0;
    $xhash{bs_nocharge}=0;
    $xhash{bs_year}=$in{Year};
    $xhash{bs_month}=$in{Month};
    $xhash{bs_date}="$xhash{bs_month}-$xhash{bs_year}";
    $xhash{bs_date}="$shortmonths[$xhash{bs_month}-1] $xhash{bs_year}";
    $xhash{bs_date}="$xhash{bs_month}/$xhash{bs_year}";
    foreach $zrec (@zcalls)
    { chomp($zrec);
      ###############################################################
      # put rec info into log hash
      ###############################################################
      foreach $zkey (@gtLogDB)
      { ($xhash{$zkey},$zrec)=split(/\|/,$zrec,2);
      }
      next if($xhash{b_opr} ne 'logged');
      next if($xhash{b_id} ne $zuid);
      next if($in{ptf_code} !~ /all/i && $in{ptf_code} ne $xhash{b_code});
      $xhash{bs_id}=$xhash{b_id};
      ###############################################################
      # increment call status totals
      ###############################################################
      $xhash{bs_calls}++;                    # total calls
      if   ($xhash{b_code} eq 'ABNDN') {$xhash{bs_ABNDN}++;}
      elsif($xhash{b_code} eq 'BUSY')  {$xhash{bs_BUSY}++;} 
      elsif($xhash{b_code} eq 'NOANS'
         || $xhash{b_code} eq 'RNA')   {$xhash{bs_NOANS}++;}
      elsif($xhash{b_code} eq 'NODT')  {$xhash{bs_NODT}++;}
      elsif($xhash{b_code} eq 'NOOUT') {$xhash{bs_NOOUT}++;}
      elsif($xhash{b_code} eq 'NORB')  {$xhash{bs_NORB}++;}
      elsif($xhash{b_code} eq 'OPINT') {$xhash{bs_OPINT}++;}
      elsif($xhash{b_code} eq 'CNCT')  {$xhash{bs_CNCT}++;}
      else                             {$xhash{bs_ERR}++;} 
      ###############################################################
      # calc call min and amount for CNCT calls
      ###############################################################
      if($xhash{b_code} eq 'CNCT')
      { if($xhash{b_timetot} ne '')
        { $ztotmin=$xhash{b_timetot};
        }
        else
        { $ztotmin=sprintf("%d",($xhash{b_timein}+$xhash{b_timeout}+59)/60);
        }
        $xhash{bs_timetot}+=$ztotmin;
        $xhash{bs_charge}+=$xhash{b_charge};
        $xhash{bs_timein}+=$xhash{b_timein};
        $xhash{bs_timeout}+=$xhash{b_timeout};
      }
      ###############################################################
      # calc call min and amount for non-CNCT calls
      ###############################################################
      else
      { if($xhash{b_timetot} ne '')
        { $ztotmin=$xhash{b_timetot};
        }
        else
        { $ztotmin=sprintf("%d",($xhash{b_timein}+$xhash{b_timeout}+59)/60);
        }
        $xhash{bs_noCNCT}+=$ztotmin;
        $xhash{bs_nocharge}+=$xhash{b_charge};
        $xhash{bs_notimein}+=$xhash{b_timein};
        $xhash{bs_notimeout}+=$xhash{b_timeout};
      }
    }
    #################################################################
    # accumulate totals
    #################################################################
    next if($xhash{bs_calls} == 0);
    $xhash{ii}++;
    $vars{totABNDN}+=$xhash{bs_ABNDN};
    $vars{totBUSY} +=$xhash{bs_BUSY};
    $vars{totERR}  +=$xhash{bs_ERR};
    $vars{totNOANS}+=$xhash{bs_NOANS};
    $vars{totNODT} +=$xhash{bs_NODT};
    $vars{totNOOUT}+=$xhash{bs_NOOUT};
    $vars{totNORB} +=$xhash{bs_NORB};
    $vars{totOPINT}+=$xhash{bs_OPINT};
    $vars{totCNCT} +=$xhash{bs_CNCT};
    $xhash{bs_charge}=sprintf("%0.2f",$xhash{bs_charge});
    $vars{totcharge}+=$xhash{bs_charge};
    $vars{totminutes}+=$xhash{bs_timetot};
    $vars{totnocharge}+=$xhash{bs_nocharge};
    $vars{totnoCNCT}+=$xhash{bs_noCNCT};
    $vars{totcalls}+=$xhash{bs_calls};
    #################################################################
    # fill in template with data for each month of gt-switch log file
    #################################################################
    $ztemplate=$xtemplate;                          # get copy of template
    foreach $zkey($ztemplate =~ /<%=.*?%>/g)        # <%=key%> in template
    { $zkey=substr($zkey,3,length($zkey)-5);        # get actual key
      if ($xhash{$zkey} ne '')
      { $ztemplate =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
      }
      else
      { $ztemplate =~ s/=<%=$zkey%>/=$xhash{$zkey}/g; # replace with value
        $ztemplate =~ s/<%=$zkey%>/$xhash{nbsp}/g;  # replace with space
      }
    }
    $zresult.=$ztemplate;                           # append processed template
  }
  ###################################################################
  # ensure only two decimal points in total charge
  ###################################################################
  $vars{totcharge}=sprintf("%0.2f",$vars{totcharge});
  return($zresult);                                 # return result
}
#####################################################################
# Display for billing - 800 month member activity
#   show one user that used 800 services for the specified month
#####################################################################
sub billing_800_month_member
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zrec, $z1, $z2, $zjunk, $zg);
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables
  my($zdate,$zaccount,$zcomm);
  my($zfn,@zmtdb);
  my(@zmemdb,%zuv);

  ###################################################################
  # initialize variables
  ###################################################################
  $xhash{ii} = 0;
  $vars{ptf_code}   =$in{ptf_code};
  $vars{member_id}  =$in{member_id};
  $vars{totalamount} = 0;
  $vars{totalmin} = 0;
  $zresult='';
  ###################################################################
  # read member data base
  ###################################################################
  if(!open(MEMFN,"<$vars{member_file}"))
  { &Error("<li>billing_800_month_member[01]: Can't open $vars{member_file} file for read!");
    exit;
  }
  @zmemdb=<MEMFN>;
  close(MEMFN);
  ###################################################################
  # search for member
  ###################################################################
  foreach $zrec (@zmemdb)
  { chomp($zrec);
    #################################################################
    # put member data into gtuv hash
    #################################################################
    foreach $zkey (@gtMemDB)
    { ($zuv{$zkey},$zrec)=split(/\|/,$zrec,2);
    }
    last if($zuv{u_userid} eq $in{member_id});
  }
  ###################################################################
  # get member data for display
  ###################################################################
  $vars{us_companyname}=$zuv{u_companyname};
  $vars{us_firstname}  =$zuv{u_firstname};
  $vars{us_lastname}   =$zuv{u_lastname};
  $vars{us_street}     =$zuv{u_street};
  $vars{us_city}       =$zuv{u_city};
  $vars{us_state}      =$zuv{u_state};
  $vars{us_zip}        =$zuv{u_zip};
  $vars{us_country}    =$zuv{u_country};
  $vars{us_email}      =$zuv{u_email};
  $vars{us_autocredit} =$zuv{u_autocredit};
  $vars{us_creditline} =$zuv{u_creditline};
  $vars{us_currentbal} =$zuv{u_currentbal};
  $vars{us_account}    =$zuv{u_account};
  ###################################################################
  # get gt-switch log directory contents for one month.
  #  log directory has one file per month.
  #  file name is yyyy-mm
  ###################################################################
  $zfn="$vars{gt_switch_cdr_log}/$in{'Year'}-$in{'Month'}";
  open(FN,"<$zfn");
  @zmtdb=<FN>;
  close(FN);
  ###################################################################
  # search and display member id data for the month
  ###################################################################
  $xhash{nbsp}='&nbsp;';
  $in{member_id}='' if(length($in{member_id})==1);
  foreach $zrec (sort @zmtdb)
  { chomp ($zrec);
    foreach $zkey (@gtLogDB)
    { ($xhash{$zkey},$zrec)=split(/\|/,$zrec,2);
    }
    next if($xhash{b_opr} ne 'logged');
    next if($xhash{b_id} ne $in{member_id});
    next if($in{ptf_code} !~ /all/i && $in{ptf_code} ne $xhash{b_code});
    if($xhash{b_timetot} eq '')
    { $xhash{b_timetot}=sprintf("%d",($xhash{b_timein}+$xhash{b_timeout}+59)/60);
    }
    $vars{bs_fwdto}=$xhash{b_fwdto};
    $vars{totalmin}+=$xhash{b_timetot};
    $xhash{b_charge}=sprintf("%0.2f",$xhash{b_charge});
    $vars{totalamount}+=$xhash{b_charge};
    $xhash{ii}++;
    $ztemplate=$xtemplate;                      # get copy of template
    foreach $zkey($ztemplate =~ /<%=.*?%>/g)      # <%=key%> in template
    { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
      if ($xhash{$zkey} ne '')
      { $ztemplate =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
      }
      else
      { $ztemplate =~ s/<%=$zkey%>/$xhash{nbsp}/g; # replace with space
      }
    }
    $zresult.=$ztemplate;                        # append processed template
  }
  $vars{totalamount}=sprintf("%0.2f",$vars{totalamount});
  return($zresult);                             # return result
}
#####################################################################
# Display calling record summary from gt switch's billing data file
#####################################################################
sub check_calling_record_summary
{ my($xtemplate,%xhash)=@_;                     # input args
  my($ztotmin,%zhash,$zresult,@zcalls);
  my($zrec,$zkey);

  $vars{totalamount}=0;
  $xhash{nbsp}='&nbsp;';
  $xhash{ii}=0;
  $zresult='';

  if(!opendir(DIR,"$vars{gt_switch_cdr_log}"))
  { $zmsg="<li>ck_calling_record_summary[01]: Unable to open <b>$vars{gt_switch_cdr_log}</b> directory for read.\n";
    &Error($zmsg);
    exit;
  }
  @zdirfns=readdir(DIR);
  closedir(DIR);
  foreach $zfn(sort @zdirfns)
  { next if(substr($zfn,0,1) ne '2');
    @zcalls =`grep -h "|$xhash{loginid}|" $vars{gt_switch_cdr_log}/$zfn`;
    $xhash{bs_charge}=0;
    $xhash{bs_timein}=0;
    $xhash{bs_timeout}=0;
    $xhash{bs_timetot}=0;
    $xhash{bs_calls}=0;
    ($xhash{bs_year},$xhash{bs_month})=split(/-/,$zfn,2);
    $xhash{bs_date}="$xhash{bs_month}-$xhash{bs_year}";
    $xhash{bs_date}="$months[$xhash{bs_month}-1] $xhash{bs_year}";
    foreach $zrec (@zcalls)
    { chomp($zrec);
      foreach $zkey (@gtLogDB)
      { ($xhash{$zkey},$zrec)=split(/\|/,$zrec,2);
      }
      next if($xhash{b_opr} ne 'logged');
      next if($xhash{b_id} ne $xhash{loginid});
      if($xhash{b_timetot} ne '')
      { $ztotmin=$xhash{b_timetot};
      }
      else
      { $ztotmin=sprintf("%d",($xhash{b_timein}+$xhash{b_timeout}+59)/60);
      }
      $xhash{bs_timetot}+=$ztotmin;
      $xhash{bs_charge}+=$xhash{b_charge};
      $xhash{bs_timein}+=$xhash{b_timein};
      $xhash{bs_timeout}+=$xhash{b_timeout};
      $xhash{bs_calls}++;
    }
    #################################################################
    # fill in template when calls have been made
    #################################################################
    if($xhash{bs_calls} > 0
     ||$xhash{ii} > 0 
     ||($xhash{bs_month} == $month
      &&$xhash{bs_year}  == $year))
    { $xhash{ii}++;
      $vars{totalamount}+=$xhash{bs_charge};
      $xhash{bs_charge}=sprintf("%0.2f",$xhash{bs_charge});
      $ztemplate=$xtemplate;                      # get copy of template
      foreach $zkey($ztemplate =~ /<%=.*?%>/g)      # <%=key%> in template
      { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
        if ($xhash{$zkey} ne '')
        { $ztemplate =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
        }
        else
        { $ztemplate =~ s/<%=$zkey%>/$xhash{nbsp}/g; # replace with space
        }
      }
      $zresult.=$ztemplate;                        # append processed template
    }
  }
  $vars{totalamount}=sprintf("%0.2f",$vars{totalamount});
  return($zresult);                             # return result
}
#####################################################################
# Display calling record from gt switch's billing data file
#####################################################################
sub billing_report
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zrec, $z1, $z2, $zjunk, $zg);
  my(@calllist);
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables
  my($zdate,$zaccount,$zcomm);
  my(@ztzdb,@zrdb);

  ###################################################################
  # read time zone table so that it is read in only once
  ###################################################################
  if(!open(FN,"<$vars{time_zone_table}"))
  { &Error("<li>billing_report[01]: Unable to open $vars{time_zone_table} for read!");
    exit;
  }
  @ztzdb=<FN>;
  close(FN);
  ###################################################################
  # read the rate table so that it is read in only once
  ###################################################################
  if(!open(FN,"<$gtgv{ratetbl}"))
  { &Error("<li>billing_report[02]: Unable to open $vars{rate_table} for read!");
    print $zmsg;
    exit(3);
  }
  @zrdb=<FN>;
  close(FN);
  ###################################################################
  # init values
  ###################################################################
  $vars{ptf_code}   =$in{ptf_code};
  $vars{time_zone}  =$in{time_zone};
  $xhash{ii} = 0;
  $vars{totalamount} = 0;
  $vars{totalmin} = 0;
  $zresult='';
  ###################################################################
  # extract gt vip member data from gt-switch cdr log
  ###################################################################
  $zmonth=sprintf("%02d",$vars{month});
  @calllist = `grep -h "|$xhash{loginid}|" $vars{gt_switch_cdr_log}/$vars{year}-$zmonth`;
  ###################################################################
  # process extracted gt-switch cdr log data
  ###################################################################
  $xhash{nbsp}='&nbsp;';
  foreach $zrec (sort @calllist)
  { chomp ($zrec);
    #################################################################
    # separate log record into its fields
    #################################################################
    foreach $zkey (@gtLogDB)
    { ($xhash{$zkey},$zrec)=split(/\|/,$zrec,2);
    }
    #################################################################
    # skip non-applicable data
    #################################################################
    next if($xhash{b_opr} ne 'logged');
    next if($xhash{b_id} ne $xhash{loginid});
    next if($in{ptf_code} !~ /all/i && $in{ptf_code} ne $xhash{b_code});
    #################################################################
    # calc total time in rounded up minutes if not done already
    #################################################################
    if($xhash{b_timetot} eq '')
    { $xhash{b_timetot}=sprintf("%d",($xhash{b_timein}+$xhash{b_timeout}+59)/60);
    }
    #################################################################
    # accumulate totals
    #################################################################
    $vars{totalmin}+=$xhash{b_timetot};
    $xhash{b_charge}=sprintf("%0.2f",$xhash{b_charge});
    $vars{totalamount}+=$xhash{b_charge};
    #################################################################
    # adjust date and time to start time of the call
    #################################################################
    
    #################################################################
    # adjust date and time based on time zone specified
    #################################################################
    ($xhash{b_date},                      # adj date of call in time zone
     $xhash{b_time},                      # adj time of call in time zone
     $xhash{time_code}                    # time zone code
    )=&time_zone_time($xhash{b_date},     # mm/dd/yy at end of call
                      $xhash{b_time},     # hh:mm:ss at end of call
                      $in{time_zone},     # requested time zone
                      $xhash{b_followme}, # phone number called
                      \@zrdb,             # ptr to rate table
                      \@ztzdb);           # ptr to time zone table
    #################################################################
    # fill in the template for this entry in the gt-switch cdr log
    #################################################################
    $xhash{ii}++;
    $ztemplate=$xtemplate;                      # get copy of template
    foreach $zkey($ztemplate =~ /<%=.*?%>/g)    # <%=key%> in template
    { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
      if ($xhash{$zkey} ne '')
      { $ztemplate =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
      }
      else
      { $ztemplate =~ s/<%=$zkey%>/$xhash{nbsp}/g; # replace with space
      }
    }
    $zresult.=$ztemplate;                        # append processed template
  }
  ###################################################################
  # format total amount in nnn.nn format
  ###################################################################
  $vars{totalamount}=sprintf("%0.2f",$vars{totalamount});
  return($zresult);                             # return result
}
#####################################################################
# calc 800 charges
# when a call is completed, all of the current charge rate values
# are collected and put into the log record.
# this routine does the actual call charge calculations based on
# the rate values.
#
# invocation:  (zcharge,ztime)=&billing_800_calc_charge
#                (xseconds,xperiod,xcpm,xminsec);
# where:
#  zcharge       nn.nn     charge for the call with usa 800 number
#  ztime         hh:mm:ss  hour, minutes, seconds for the call
#  xseconds      nn        length of call in seconds
#  xcpm          nn.nn     charge per minute for the call
#  xminsec       nn        minimun number of seconds for the call
#
# the algorithm is:
#  (int((seconds + PERIOD -1)/PERIOD)*PERIOD*CPM/60) +.005
#####################################################################
sub billing_800_calc_charge
{ my($xseconds,$xperiod,$xcpm,$xminsec)=@_;
  my($ztotsec,$ztime,$zcharge);

  ###################################################################
  # calc the charge for the call
  ###################################################################
  $ztotsec=int(($xseconds+$xperiod-1)/$xperiod) * $xperiod;
  $ztotsec=$xminsec if($ztotsec < $xminsec);
  $zcharge= sprintf("%0.2f",($ztotsec * $xcpm/60) + .005);
  ###################################################################
  # format the time of the call
  ###################################################################
  $zss=$ztotsec % 60;              # remainder is the seconds
  $zmm=int($ztotsec / 60);         # number of minutes
  $zhh=int($ztotsec / (60 * 60));  # number of hours
  $zss=sprintf("%02d",$zss);       # format seconds with leading zero
  $zmm=sprintf("%02d",$zmm);       # format minutes with leading zero
  $zhh=sprintf("%02d",$zhh);       # format hours with leading zero
  $ztime="$zhh:$zmm:$zss";         # build time string
  ###################################################################
  # return the results
  ###################################################################
  return($zcharge,$ztime);
}
#####################################################################
# calc time in a specific time zone
# inputs:
#  xdate      mm/dd/yy at end of call
#  xtime      hh:mm:ss at end of call
#  xzone      requested time zone or 'called'
#  xphonenum  phone number called (used to determine 'called' time zone)
#  xrate      pointer to rate table
#  xtimezone  pointer to time zone table
#
# outputs:
#  zdate      mm/dd/yy at end of call based on time zone
#  ztime      hh:mm:ss at end of call based on time zone
#  ztimezone  time zone code
#####################################################################
sub time_zone_time
{ local($xdate,$xtime,$xzone,$xphonenum,*xrate,*xtimezone)=@_;
  my($zmt,$zda,$zyr,$zhr,$zmin,$zsec);
  my(@zmtdays,%ztz,%zrz);

  ($zmt,$zda,$zyr)=split(/\//,$xdate,3);
  ($zhr,$zmin,$zsec)=split(/:/,$xtime,3);

  ###################################################################
  # adjust date and time input to gmt time
  ###################################################################
  ($zmt,$zda,$zyr,$zhr)=&date_time($zmt,$zda,$zyr,$zhr,$gtgv{adjtogmt});
  ###################################################################
  # get time zone of called number
  ###################################################################
  if($xzone =~ /called/i)
  { $xphonenum =~ s/-//g;
    $xphonenum =~ s/\.//g;
    foreach $zrec (@xrate)
    { chomp($zrec);
      my($zrectmp)=$zrec;
      foreach $zfield (@merged_rates)
      { ($zkey,$zjunk)=split(/,/,$zfield,2);
        ($zrz{$zkey},$zrectmp)=split(/,/,$zrectmp,2);
      }
      $zcclng=length($zrz{r_country_code});
      $zcc=substr($xphonenum,0,$zcclng);
      next if ($zcc < $zrz{r_country_code});
      if($zcc > $zrz{r_country_code})
      {
      }
      last if($zrz{r_city_code} eq '');
      $zaclng=length($zrz{r_city_code});
      if($zrz{r_city_code} eq '*')
      { next;
      }
      last if($zrz{r_city_code} eq $zac);
    }
    $xzone=$zrz{r_time_zone};
  }
  ###################################################################
  # adjust date and time to specified time zone
  ###################################################################
  foreach $zrec (@xtimezone)
  { chomp($zrec);
    my($zrectmp)=$zrec;
    foreach $zkey (@gtTimeZoneTbl)
    { chomp($zkey);
      my($zkeytmp)=$zkey;
      ($ztz{$zkeytmp},$zrectmp)=split(/\|/,$zrectmp,2);
    }
    last if($xzone eq $ztz{t_code});
    last if($xzone =~ /called/i && $ztz{t_adjustment} == -$gtgv{adjtogmt});
  }
  ($zmt,$zda,$zyr,$zhr)=&date_time($zmt,$zda,$zyr,$zhr,$ztz{t_adjustment});
  $zmt=sprintf("%02d",$zmt);
  $zda=sprintf("%02d",$zda);
  $zdate="$zmt/$zda/$zyr";
  $ztime="$zhr:$zmin:$zsec";
  return($zdate,$ztime,$ztz{t_code});
}
#####################################################################
# recalc date and time
#####################################################################
sub date_time
{ my($xmt,$xday,$xyr,$xhr,$xadjhr)=@_;
  my(@zmtdays);

  ###################################################################
  # days in each month and adjust for leap year
  ###################################################################
  @zmtdays=(31,28,31,30,31,30,31,31,30,31,30,31);
  $zmtdays[1]++ if($xyr%4 == 0); # this year is a leap year
  ###################################################################
  # days in each month and adjust for leap year
  ###################################################################
  $xhr += $xadjhr;               # adj hour
  if($xhr >= 24)                 # ck if 24 hrs or greater
  { $xday++;                     # next day
    $xhr-=24;                    # subtract 24 hours
    if($xday > $zmtdays[$xmt-1]) # ck if past end of month
    { $xmt++;                    # next month
      $xday=1;                   # set 1st day of next month
      if($xmt > 12)              # ck if past end of year
      { $xyr++;                  # next year
        $xmt=1;                  # set 1st month of year
        $zmtdays[1]++ if($xyr%4 == 0); # this year is a leap year
      }
    }
  }
  elsif($xhr < 0)
  { $xday--;                     # previous day
    $xhr += 24;                  # add 24 hours
    if($xday < 1)                # ck if end of last month
    { $xmt--;                    # last month
      if($xmt < 1)               # ck if past start of year
      { $xyr--;                  # last year
        $xmt=12;                 # last month in year
        $zmtdays[1]++ if($xyr%4 == 0); # this year is a leap year
      }
      $xday=$zmtdays[$xmt-1];    # last day of month
    }
  }
  $xmt=sprintf("%02d",$xmt);
  $xday=sprintf("%02d",$xday);
  $xhr=sprintf("%02d",$xhr);
  return($xmt,$xday,$xyr,$xhr);
}
#####################################################################
# Display time zone information
#####################################################################
sub time_zone
{ my($xtemplate,%xhash)=@_;
  my(@ztimezonedb);
  my($zrec,$zkey,$zresult,$ztemplate);

  ###################################################################
  # read time zone table
  ###################################################################
  if(!open(FN,"<$vars{time_zone_table}"))
  { &Error("<li>time_zone[01]: Can't open $vars{time_zone_table} file for read!");
    exit;
  }
  @ztimezonedb=<FN>;
  close(FN);
  ###################################################################
  # read time zone file
  ###################################################################
  $xhash{nbsp}='&nbsp;';
  foreach $zrec (@ztimezonedb)
  { next if($zrec =~/^#/);                        # skip comments
    chomp($zrec);
    reset(zkey);
    foreach $zkey (@gtTimeZoneTbl)
    { ($xhash{$zkey},$zrec)=split(/\|/,$zrec,2);
    }
    continue
    { reset(zkey);
    }
    $ztemplate=$xtemplate;
    foreach $zkey($ztemplate =~ /<%=.*?%>/g)      # <%=key%> in template
    { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
      if ($xhash{$zkey} ne '')
      { $ztemplate =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
      }
      else
      { $ztemplate =~ s/<%=$zkey%>/$xhash{nbsp}/g; # replace with space
      }
    }
    $zresult.=$ztemplate;                        # append processed template
  }
  return($zresult);                             # return result
}
#####################################################################
# Display 800 PTF charge rates
#####################################################################
sub charge_rates
{ my($xtemplate,%xhash)=@_;
  my(@zchargeratesdb,@ztmpdb);
  my($zall,$zrec,$zkey,$zresult,$ztemplate);

  ###################################################################
  # get charge rates table
  ###################################################################
  if(!open(FN,"<$vars{charge_rates_table}"))
  { &Error("<li>charge_rates[01]: Can't open $vars{charge_rates_table} file for read!");
    exit;
  }
  @zchargeratesdb=<FN>;
  close(FN);
  ###################################################################
  # read charge rates file
  ###################################################################
  $vars{strChargeRatesView}=$in{r_charge_rates_view};
  $xhash{nbsp}='&nbsp;';
  $xhash{ii}=0;
  $zall='';
  foreach $zrec (@zchargeratesdb)
  { if($zrec =~ /^#/)
    { next if($zrec !~ / = /);
      next;
    }
    next if($zrec =~ /^#/);                        # skip comments
    chomp($zrec);
    @ztmpdb=@merged_rates;
    foreach $zfield (@ztmpdb)
    { ($zkey,$zjunk)=split(/,/,$zfield,2);
      ($xhash{$zkey},$zrec)=split(/,/,$zrec,2);
    }
    if($xhash{r_country_code} eq '1')
    { if($zall eq 'done'
       &&$xhash{r_country} =~/^USA/)
      { next;
      }
      if($in{r_charge_rates_view} ne 'expand'
       &&$xhash{r_country} =~ /^USA/)
      { $xhash{r_city_code}='*';
        $xhash{r_country}='USA STATES';
        $xhash{r_time_zone}='UNKN';
        $zall='done';
      }
    }
    $xhash{ii}++;
    $ztemplate=$xtemplate;
    foreach $zkey($ztemplate =~ /<%=.*?%>/g)      # <%=key%> in template
    { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
      if ($xhash{$zkey} ne '')
      { $ztemplate =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
      }
      else
      { $ztemplate =~ s/<%=$zkey%>/$xhash{nbsp}/g; # replace with space
      }
    }
    $zresult.=$ztemplate;                        # append processed template
  }
  return($zresult);                             # return result
}
#####################################################################
# Display calling record from Glen Chow switch's billing data file
#####################################################################
sub check_calling_record2
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zrec, $z1, $z2, $zjunk, $zg);
  my(@calllist);
  undef %zhash;
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables
  my($zdate,$zaccount,$zcomm);

  $xhash{ii} = 0;
  $vars{totalamount} = 0;
  $zresult='';
  if ($in{searchMonth} eq 'thismonth')
  { $zdate = $vars{currentmonthstamp};
    $vars{cyear} = $year;
    $vars{cmonth} = $months[$month-1];
    $vars{cdate} = $mday;
  }
  else
  { $zdate = $in{searchMonth};
    $vars{cyear} = substr($in{searchMonth},0,4);
    $zzmonth = substr($in{searchMonth},4,2);
    $vars{cmonth} =$months[$zzmonth-1];
  }
  @calllist = `grep -h $xhash{strForwardTo} $vars{call_info_gc_file}*`;                          
  foreach $zrec (@calllist)
  { chomp ($zrec);
    foreach $zg (@gtBillGCDB)
    { ($zg1, $zdesc, $zstart, $zend, $zjunk)=split(/,/,$zg,5);
      $zstart--;
      $zhash{$zg1}= substr($zrec,$zstart,$zend);
    }
    $zhash{gc_year}= substr($zhash{gc_datecallmadel},0,4);
    $zhash{gc_month}= substr($zhash{gc_datecallmadel},4,2);
    $zhash{gc_date}= substr($zhash{gc_datecallmadel},6,2);
    $zdate1 = sprintf("%4.4d%2.2d",$zhash{gc_year},$zhash{gc_month});
    $zhash{gc_accessnum} =~ s/ +//g; 
    if ($zhash{gc_accessnum} eq $vars{strForwardTo}
         && $zdate eq $zdate1)
    { 
      $zhash{gc_month} = $months[$zhash{gc_month}-1];
      $zhash{gc_hour}= substr($zhash{gc_timecallmadel},0,2);
      $zhash{gc_min}= substr($zhash{gc_timecallmadel},2,2);
      $zhash{gc_originnum} =~ s/\"+//g;            # remove quote
      $zhash{gc_termcity} =~ s/\"+//g;            # remove quote
      $zhash{gc_termcity} =~ s/ +//g;            # remove space

      $vars{totalamount} += $zhash{gc_callcharge};
      $xhash{ii}++;
      $zresult.=$xtemplate;                       # concat template to result
      foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
      { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
        if ($zhash{$zkey} ne '')
        { $zresult =~ s/<%=$zkey%>/$zhash{$zkey}/g; # replace with value
        }
        else
        { $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
        }
      }
    }
  }
  return($zresult);                             # return result
}
#####################################################################
# Get affiliate data and put it into the %gtuv hash
#####################################################################
sub affiliate_lookup
{ my($xaffnumber)=@_;
  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("<li>affiliate_lookup[01]: Can't lock $vars{member_lock} file!");
  eval "flock MEMLK,2";
  if(-e "$vars{aff_file}")
  { if(!open(MEMFN,"<$vars{aff_file}"))
    { close(MEMLK);
      &Error("<li>affiliate_lookup[02]: Can't open $vars{aff_file} file for read!");
      exit;
    }
    @affdata=<MEMFN>;
    close(MEMFN);
  }
  else
  { @affdata=();
  }
  ###################################################################
  # search for the userid
  ###################################################################
  foreach $zrec (sort @affdata)
  { $ztmp=$zrec;
    chomp($ztmp);
    #################################################################
    # put member data into gtuv hash
    #################################################################
    foreach $zkey (@gtAffDB)
    { ($gtuv{$zkey},$ztmp)=split(/\|/,$ztmp,2);
    }
    #################################################################
    # match with requested userid
    #################################################################
    if($gtuv{aff_number} eq $xaffnumber)
    { $in{strGTAffID}=$gtuv{aff_number};
      return(0);
    }
  }
  return(1);                            # not found
}
#####################################################################
# Display affiliate record
#####################################################################
sub affiliate_record
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zrec, $z1, $z2, $zjunk, $zg);
  my(@afflist);
  undef %zhash;
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables
  $xhash{loginid} = $in{strEmail};
  $xhash{password} = $in{strPassword};

  $zresult='';                                  # reset output
  if(!open(AFFLIST,"<$xhash{aff_file}"))
  { &Error("<li>affiliate_record[01]: Can't open $xhash{aff_file} file for read!");
    exit;
  }
  @afflist=<AFFLIST>;
  @afflist1=@afflist;
  close(AFFLIST);

  if(!open(AFF,"<$xhash{member_file}"))
  { &Error("<li>affiliate_record[02]: Can't open $xhash{member_file} file for read!");
    exit;
  }
  @commlist=<AFF>;
  @commlist1=@commlist;
  close(AFF);
  $zdate = sprintf("%4.4d%2.2d",$vars{year},$vars{month});

  $xhash{ii}=0;                                 # start at 1
  foreach $zrec (@afflist)
  { chomp ($zrec);
    foreach $zg (@gtAffDB)
    { ($zhash{$zg},$zrec)=split(/\|/,$zrec,2);
    }
    $zhash{totalvipsignup}= 0;
    $zhash{totalvosignup}= 0;
    $zhash{thismonthvipsignup}= 0;
    $zhash{thismonthvosignup}= 0;
    $zhash{thismonthcomm} = 0;
    $zhash{totalcomm} = 0;
    if ($zhash{aff_number} eq "$in{strAffNumber}" || $in{strAffNumber} eq '')
    { 

      foreach $zrec (@commlist1)
      { chomp ($zrec);

        foreach $zg (@gtMemDB)
        {  ($zhash{$zg},$zrec)=split(/\|/,$zrec,2);
        }
        if ($zhash{u_gtaffid} eq "$zhash{aff_number}" 
        && ($zhash{u_account} =~ /^vip/
            || $zhash{u_account} =~ /^vo/))
        { $vars{ii}++;
          ###################################
          # count total for different product
          ###################################
          if ($zhash{u_account} =~ /^vip/)
          { $zaccount = 1;
            $zhash{totalvipsignup}++;
          }
          elsif ($zhash{u_account} =~ /^vo/)
          { $zaccount = 2;
            $zhash{totalvosignup}++;
          }
          ################################
          # commission rate lookup
          ################################
          foreach $zco (@gtCommissionPackage)
          { ($zcomname, $zrate1, $zrate2, $zrate3, $zjunk) = split (/,/, $zco, 5);
            if ($zcomname eq $zhash{u_commpackage})
            { $zhash{commpercent} = $zrate1;
              last;
            }
          }
#         $vars{totalcomm} += $zhash{u_fee};
          #########################################
          #calculate number of months after signup
          #########################################
          $zsignupyear= substr($zhash{u_signupdate},0,4);
          $zsignupmonth = substr($zhash{u_signupdate},4,2);
          $zsignupdate = substr($zhash{u_signupdate}, 6,2);
          $zzyear = $year - $zsignupyear;
          $zmonthnum = $zzyear *12 + $month - $zsignupmonth + 1;
          ######################
          # calculate commision
          ######################
          if ($zmonthnum <= 12)
          {  $zcomm = $zhash{u_fee} * $zrate1 *$zmonthnum;
          }
          elsif ($zmonthnum >12 && $zmonthnum <=24)
          {  $zcomm = $zhash{u_fee} * 12 *$zrate1;
             $zcomm += ($zhash{u_fee} * ($zmonthnum-12) * $zrate2); 
          }
          else
          {  $zcomm = $zhash{u_fee} * 12 *$zrate1;
             $zcomm += $zhash{u_fee} * 12 * $zrate2;
             $zcomm += $zhash{u_fee} * ($zmonthnum-24)* $zrate3; 
          }
          $zcomm = int($zcomm);
          $zhash{totalcomm} += $zcomm/100;
          ######################################
          # display data for a particular month
          ######################################
          if ($zdate eq '' || $zhash{u_signupdate} =~ /^$zdate/g)
          { if ($zaccount == 1)
            { $zhash{thismonthvipsignup}++;
            }
            elsif ($zaccount == 2)
            { $zhash{thismonthvosignup}++;
            }
            $zhash{thismonthcomm} += ($zcomm/100);
          }
        }
      }
      @commlist1=@commlist;
      $zresult.=$xtemplate;                       # concat template to result
      foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
      { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
        if ($zhash{$zkey} ne '')
        { $zresult =~ s/<%=$zkey%>/$zhash{$zkey}/g; # replace with value
        }
        else
        { $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
        }
      }
    }
  }
  return($zresult);                             # return result
}
#####################################################################
# check officer password
#####################################################################
sub check_officer_password
{ my ($ztemp, $zjunk, $zloginid, $zphonenum);
  ##################################################################
  # Check admin password
  ##################################################################
  if($in{strEmail} eq '' || $in{strPassword} eq '')
  { $zmsg="A <b>login id</b> and <b>Password</b> must be entered!\n";
  }
  if($in{strEmail} ne 'admin' && $in{strEmail} ne 'billing' && $in{strEmail} ne '1005'
&& $in{strEmail} ne '1002' && $in{strEmail} ne 'infinex' && $in{strEmail} ne '1004')
  { $zmsg.="This Function is for Globaltalker Officers only!\n";
  }
  ###################################################################
  # check if userid and passwd match an existing user
  ###################################################################
  else
  { $zret=&member_get($in{strEmail});
    if($zret == 1)
    { close(MEMLK);
      $zmsg .= "[BA00]: <li>Email address (login id), <b>$in{strEmail}</b>, not found in our database.\n";
    }
    else
    { if(crypt($gtuv{u_passwd},$in{strPassword}) ne $in{strPassword} && $gtuv{u_passwd} ne $in{strPassword})
      { close(MEMLK);
        $zmsg.="<li>[BA01]: Email address, (login id), <b>$in{strEmail}</b> and password not found in our database.\n";
      }
    }
  }
  ###################################################################
  # exit if any errors
  ###################################################################
  if($zmsg ne '')
  { &calendar_error_msg($zmsg,'calendar_error_html');
    exit;
  }
}
#####################################################################
# Output to a billing file
#####################################################################
sub print_to_billing_file
{ my($xmsg,$xtemplate,%zhash)=@_; 
  my($ztemplate); 
  $vars{error_msg}=$xmsg;
  $ztemplate = &load_template("$vars{$xtemplate}");
  $ztemplate = &parse_template($ztemplate, \%vars);
  if(!open(BILL,">$vars{monthly_bills_dir}/$zhash{u_email}\|$vars{currentdatestamp}"))
  { &Error("<li>print_to_billing_file[01]: Can't open $vars{monthly_bills_dir}/$zhash{u_email}\|$vars{currentdatestamp} file for write!");
    exit;
  }
  print BILL $ztemplate;
  close(BILL);
  return; 
}
#####################################################################
# 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 bill_member
{ my($xloginid)=@_;
# my($zmemgrp);
  my($ztmp,$zrec,$zkey,$zii);
  my($zcityphone,$zcity,$zphone);

# $zmemgrp=substr($xloginid,0,3);
  $in{searchMonth} = "thismonth";
  ###################################################################
  # lock and read the member db
  ###################################################################
  open(MEMLK,">$vars{member_lock}")
   || &Error("<li>bill_member[01]: 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("<li>bill_member[02]: 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($ztmp);
    #################################################################
    # put member data into gtuv hash
    #################################################################
    foreach $zkey (@gtMemDB)
    { ($gtuv{$zkey},$ztmp)=split(/\|/,$ztmp,2);
    }
    #################################################################
    # match with requested userid
    #################################################################
    if($gtuv{u_forwardto} ne '')
    { $vars{strForwardTo} = $gtuv{u_forwardto};
      $vars{memberid} = $gtuv{u_userid};
      &print_to_billing_file('','billing_statement_html',%gtuv);
    }
  }
  &calendar_error_msg('','billing_html');                       
}
#####################################################################
# Member check their billing online
#####################################################################
sub check_monthly_bill
{  my($zemail,$zdate);
   my($zbyear,$zbmonth,$zbdate,$zbstring);
    opendir(DIR, $vars{monthly_bills_dir}) || die "can't opendir $vars{monthly_bills_dir}: $!";
    @file = readdir(DIR);
    closedir DIR;
    foreach $zrec (@file)
    { chomp ($zrec);
      ($zemail,$zdate) = split (/\|/,$zrec,2);
      if ($zemail eq $in{strStatementEmail})
      { $zbyear= substr($zdate,0,4);
        $zbmonth = substr($zdate,4,2);
        $zbmonth = $months[$zbmonth-1];
        $zbdate = substr($zdate,6,2);
        $zbstring = "$zbmonth $zbdate, $zbyear";
#        push (@billdate, "$zbstring\n");
        $vars{billdate} .= "<option value=$zdate>$zbstring";
      }
    }
    $vars{strStatementEmail} = $in{strStatementEmail};
    &calendar_error_msg('','member_check_monthly_bill_html');
}
#####################################################################
# Member check their detail billing statement online
#####################################################################
sub check_monthly_bill_detail
{
  $zfile = "$in{strStatementEmail}".'|'."$in{strStatementDate}";
  $ztemplate = &load_template("$vars{monthly_bills_dir}/$zfile");
  $ztemplate = &parse_template($ztemplate, \%vars);
  print $ztemplate;
  exit;
}  
#####################################################################
# Display different account num to choose to login
#####################################################################
sub login_account
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zrec, $z1, $z2, $zjunk, $zg);
  undef %zhash;
  my($zu_loc,$zcityphone,$zkey,$zresult);       # internal variables
  $xhash{loginid} = $in{strEmail};

  $zresult='';                                  # reset output
  foreach $zrec (@gtuvlist)
  {
    ($zhash{u_userid}, $zhash{u_email}, $zjunk) = split(/\|/,$zrec,3);
    if ($zhash{u_userid} ne '') 
    { $zresult.=$xtemplate;                       # concat template to result
      foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
      { $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
        if ($zhash{$zkey} ne '')
        { $zresult =~ s/<%=$zkey%>/$zhash{$zkey}/g; # replace with value
        }
        else
        { $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
        }
      }
    }
  }
  return($zresult);                             # return result
}
#####################################################################
# Get the speical deal rate from db
#####################################################################
sub get_special_rate
{ my($xaffnumber)=@_;
  my($ztmp,$zrec);
  my($zmonthly, $zquarterly, $zannually);
# $zmemgrp=substr($xloginid,0,3);

  ###################################################################
  # lock and read the member db
  ###################################################################
  if(!open(AFFLIST,"<$vars{special_file}"))
  { &Error("<li>get_special_rate[01]: Can't open $vars{special_file} file for read!");
    exit;
  }
  @affdata=<AFFLIST>;
  close (AFFLIST);
  ###################################################################
  # search for the userid
  ###################################################################
  foreach $zrec (sort @affdata)
  { chomp($zrec);
    $ztmp=$zrec;
    foreach $zrec1 (@gtSpecialDeal)
    { chomp ($zrec1);
      ($zgtuv,$zvars,$zjunk) = split (/,/,$zrec1,3);
      ($gtuv{$zgtuv}, $zrec) = split (/\|/,$zrec,2);
      $vars{$zvars} = $gtuv{$zgtuv};
    }
    #################################################################
    # match with requested userid
    #################################################################
    if($gtuv{u_affid} eq $xaffnumber)
    { if ($gtuv{u_maxquota} > $gtuv{u_currentquota})
      { return;
      }
      else
      { $zmsg .= "<li>[BB00]: You have used up all your quota. Please contact Global Talker for more details.\n";               
        &calendar_error_msg($zmsg,'calendar_error_html');
        exit;
      }
    }
  }
  $zmsg .= "<li>[BB01]: You are not eligible for the speical deal. Please contact Global Talker for more details.\n";
  &calendar_error_msg($zmsg,'calendar_error_html');
  exit;
}
#####################################################################
# Modify Quota from special deal db
#####################################################################
sub modify_quota
{ my($xaffnumber)=@_;
  my($ztmp,$zrec);
# $zmemgrp=substr($xloginid,0,3);

  ###################################################################
  # lock and read the member db
  ###################################################################
  if(!open(AFFLIST,"<$vars{special_file}"))
  { &Error("<li>modify_quota[01]: Can't open $vars{special_file} file for read!");
    exit;
  }
  @affdata=<AFFLIST>;
  close (AFFLIST);
  @zdeal = @gtSpecialDeal;
  ###################################################################
  # search for the userid
  ###################################################################
  foreach $zrec (sort @affdata)
  { chomp($zrec);
    $ztmp=$zrec;
    foreach $zrec1 (@gtSpecialDeal)
    { chomp ($zrec1);
      ($zgtuv,$zvars,$zjunk) = split (/,/,$zrec1,3);
      ($gtuv{$zgtuv}, $zrec) = split (/\|/,$zrec,2);
      $vars{$zvars} = $gtuv{$zgtuv};
    }
    #################################################################
    # match with requested userid
    #################################################################
    if($gtuv{u_affid} eq $xaffnumber)
    { $gtuv{u_currentquota}++;
      foreach $zrec2 (@zdeal)
      { ($zgtuv,$zvars,$zjunk) = split (/,/,$zrec2,3);
        $memstring .= "|$gtuv{$zgtuv}";
      }
      $memstring = substr($memstring,1);
      push (@affdata1,"$memstring\n");
    }
    else
    { push (@affdata1,"$ztmp\n");
    }
  }
  ###################################################################
  # output the new member file to a temp file
  ###################################################################
  if(!open(MEMFN,">$vars{special_file}"))
  { close(MEMLK);
        print ("\n"); #Aaron
    &Error("<li>modify_quota[02]: Can't open $ztmpfile-tmp file for write!");
  }
  print MEMFN @affdata1;
  close(MEMFN);
  return;
}

