#==============================================================================
#
#            webcal --- a web based calendar program
#
#          Copyright (C) 2000, 2001, 2002, 2003, 2004  Maorong Zou
#
#
#  This file is part of webcal.
#
#  webcal is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# webcal is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with webcal; see the file COPYING.  If not, write to
# the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
#
#
# $Header: /home/cvs/webCal/webCal2/webcalSupport.pm,v 1.557 2005/02/17 17:48:43 mzou Exp $
#
#==============================================================================
#
#  Special thanks to
#    Rob Janssen <r.janssen@uw-werk.nl>
#  for his numerous enhancements.
#
#==============================================================================
package webcalSupport;
use webcalConfig;
use webcalVirtual;
use webcalAuth;
use webcalContactDB;
use webcalLock;
if ($webcalConfig::r{'moonphase'}) { use webcalMoon; }
if ($webcalConfig::r{'smtpto'} and $webcalConfig::r{'smtpfrom'}) { use smtplib; }
use Fcntl ':flock';
use Fcntl ':DEFAULT';
use Symbol;
use strict;
use POSIX;
use Carp;
local $SIG{__WARN__}=\&Carp::cluck;
#==============================================================================
my $webCalVersion="2.9";
my $patchlevel="3";
my $cvsversion='$Id: webcalSupport.pm,v 1.557 2005/02/17 17:48:43 mzou Exp $';
$webcalSupport::VERSION = 2.9;
#==============================================================================
# Constants and global vars
#

if(1) {
  # for each occurence type: code#, modulo, wdaymask.
  # when wdaymask: number of occurrences this week for each weekday sun..sat
  %::occurenceHash = (
		      'OneTime'			=> [1,	0,  0x00],
		      'Daily'			=> [2,	1,  0x00],
		      'Weekly'			=> [3,	7,  0x00],
		      'Every2Weeks'		=> [4,	14, 0x00],
		      'MonthlyByDate'		=> [5,	0,  0x00],
		      'MonthlyByWeekday'	=> [6,	0,  0x00],
		      'Yearly'			=> [7,	0,  0x00],
		      'MTWThF'			=> [8,	0,  0x3e, 0,1,2,3,4,5,5],
		      'MWF'			=> [9,	0,  0x2a, 0,1,1,2,2,3,3],
		      'TTh'			=> [10,	0,  0x14, 0,0,1,1,2,2,2],
		      'YearlyByMonthWeekday'	=> [11,	0,  0x00],
		      'EveryOtherDay'		=> [12,	2,  0x00],
		      'Every3rdDay'		=> [13,	3,  0x00],
		      'Every4thDay'		=> [14,	4,  0x00],
		      'Every5thDay'		=> [15,	5,  0x00],
		      'Every6thDay'		=> [16,	6,  0x00],
		      'Custom'  		=> [17,	0,  0x00],
		     );

  %::privacyTable= ( 'osn' => 1, 'osti' => 2, 'ostt' => 3, 'ostxti' => 4, 'public' => 5,);
  @::mdays = (31,28,31,30,31,30,31,31,30,31,30,31);
  %::opnames = (
		'dview'=>1, 'tzone'=>1, 'hourE'=>1, 'name'=>1, 'email'=>1, 'clist'=>1, 'clist[]'=>1,
		'homepage'=>1, 'hourB'=>1, 'interval'=>1, 'privacy'=>1, 'ulist'=>1,
		'editors'=>1, 'dformat'=>1, 'tformat'=>1, 'weekstart'=>1,'estyle'=>1,
		'eweekend'=>1, 'afg'=>1, 'abg'=>1, 'tfg'=>1, 'tbg'=>1,'toffset'=>1,
		'mfg'=>1, 'mbg'=>1, 'sfg'=>1, 'sbg'=>1, 'slanguage'=>1, 'cfilter'=>1,'dmode'=>1,'ccode'=>1,
		'editors[]'=>1, 'ol'=>1, 'ctype'=>1, 'dlist'=>1, 'hdr'=> 1, 'ftr'=>1,
		'autostart'=>0, 'readers'=>1, 'readers[]'=>1, 'vcal'=>1, 'dr'=>1,
                'dformat2'=>1, 'themecolor'=>1, 'hourB0'=>1,'hourE0'=>1,
		'hourB1'=>1,'hourE1'=>1,'hourB2'=>1,'hourE2'=>1,'hourB3'=>1,'hourE3'=>1,
		'hourB4'=>1,'hourE4'=>1,'hourB5'=>1,'hourE5'=>1,'hourB6'=>1,'hourE6'=>1,
		'minuB0'=>1,'minuE0'=>1,
		'minuB1'=>1,'minuE1'=>1,'minuB2'=>1,'minuE2'=>1,'minuB3'=>1,'minuE3'=>1,
		'minuB4'=>1,'minuE4'=>1,'minuB5'=>1,'minuE5'=>1,'minuB6'=>1,'minuE6'=>1,
		'tarf'=>1, 'dctoc'=>1, 'delay'=>1, 'dayview' => 1, 'aname'=>1,'weekview'=>1,
		'pnotes'=>1, 'pdiary'=>1, 'paddress'=>1, 'dname'=>1, 'dei'=>1, 'resrc'=>1,'aap'=>1,
		'apair'=>1,'tpair'=>1,'mpair'=>1,'spair'=>1,  'dcs'=>1,'dcs[]'=>1, 'dcsf'=>1, 'nap'=>1,
		'authors'=>1, 'authors[]'=>1, 'css1'=>1,'css2'=>1,'css3'=>1,'css4'=>1,
	       );

  #------------------------------------------------------------------------------------------------------------------------
  #  date format, short form
  @::sdateformat =( 0,       'mm/dd/yyyy',
                    1,       'dd/mm/yyyy',
                    2,       'yyyy-mm-dd',
                    3,       'dd-mm-yyyy',
                    4,       'dd.mm.yyyy',
                    5,       'dd/mm-yyyy',
                    6,       'yyyy.mm.dd',
                    7,       'yyyy/mm/dd',
		    8,       'dd-mm-yyyy.',
		    9,       'yyyy.mm.dd.',
                    );

  @::toNativeDate =(
    sub {my($m_,$d_,$y_)=split(/\//,(@_)[0]); return sprintf("%02d/%02d/%04d",$m_,$d_,$y_);},  # 0
    sub {my($m_,$d_,$y_)=split(/\//,(@_)[0]); return sprintf("%02d/%02d/%04d",$d_,$m_,$y_);},  # 1
    sub {my($m_,$d_,$y_)=split(/\//,(@_)[0]); return sprintf("%04d-%02d-%02d",$y_,$m_,$d_);},  # 2
    sub {my($m_,$d_,$y_)=split(/\//,(@_)[0]); return sprintf("%02d-%02d-%04d",$d_,$m_,$y_);},  # 3
    sub {my($m_,$d_,$y_)=split(/\//,(@_)[0]); return sprintf("%02d.%02d.%04d",$d_,$m_,$y_);},  # 4
    sub {my($m_,$d_,$y_)=split(/\//,(@_)[0]); return sprintf("%02d/%02d-%04d",$d_,$m_,$y_);},  # 5
    sub {my($m_,$d_,$y_)=split(/\//,(@_)[0]); return sprintf("%04d.%02d.%02d",$y_,$m_,$d_);},  # 6
    sub {my($m_,$d_,$y_)=split(/\//,(@_)[0]); return sprintf("%04d/%02d/%02d",$y_,$m_,$d_);},  # 7
    sub {my($m_,$d_,$y_)=split(/\//,(@_)[0]); return sprintf("%02d-%02d-%04d.",$d_,$m_,$y_);}, # 8
    sub {my($m_,$d_,$y_)=split(/\//,(@_)[0]); return sprintf("%04d.%02d.%02d.",$y_,$m_,$d_);}, # 9
    );
  @::toWcalDate =( 
    sub {my($m_,$d_,$y_)=split(/\//,(@_)[0]);$m_+=0;$d_+=0; return "$m_/$d_/$y_";},  # 0
    sub {my($d_,$m_,$y_)=split(/\//,(@_)[0]);$m_+=0;$d_+=0; return "$m_/$d_/$y_";},  # 1
    sub {my($y_,$m_,$d_)=split(/\-/,(@_)[0]);$m_+=0;$d_+=0; return "$m_/$d_/$y_";},  # 2
    sub {my($d_,$m_,$y_)=split(/\-/,(@_)[0]);$m_+=0;$d_+=0; return "$m_/$d_/$y_";},  # 3
    sub {my($d_,$m_,$y_)=split(/\./,(@_)[0]);$m_+=0;$d_+=0; return "$m_/$d_/$y_";},  # 4
    sub {my($d_,$my_)=split(/\//,(@_)[0]); my ($m_, $y_)=split(/\-/,$my_); $m_+=0;$d_+=0; return "$m_/$d_/$y_";},  # 5
    sub {my($y_,$m_,$d_)=split(/\./,(@_)[0]);$m_+=0;$d_+=0; return "$m_/$d_/$y_";},  # 6
    sub {my($y_,$m_,$d_)=split(/\//,(@_)[0]);$m_+=0;$d_+=0;return "$m_/$d_/$y_";},  # 7
    sub {my($d_,$m_,$y_)=split(/\-/,(@_)[0]);$m_+=0;$d_+=0; return "$m_/$d_/$y_";},  # 8
    sub {my($y_,$m_,$d_)=split(/\./,(@_)[0]);$m_+=0;$d_+=0; return "$m_/$d_/$y_";},  # 9
    );
  @::to_md_nstring =(
    sub {my($m_,$d_)=(@_); return sprintf("%02d/%02d",$m_,$d_);},  # 0
    sub {my($m_,$d_)=(@_); return sprintf("%02d/%02d",$d_,$m_);},  # 1
    sub {my($m_,$d_)=(@_); return sprintf("%02d-%02d",$m_,$d_);},  # 2
    sub {my($m_,$d_)=(@_); return sprintf("%02d-%02d",$d_,$m_);},  # 3
    sub {my($m_,$d_)=(@_); return sprintf("%02d.%02d",$d_,$m_);},  # 4
    sub {my($m_,$d_)=(@_); return sprintf("%02d/%02d",$d_,$m_);},  # 5
    sub {my($m_,$d_)=(@_); return sprintf("%02d.%02d",$m_,$d_);},  # 6
    sub {my($m_,$d_)=(@_); return sprintf("%02d/%02d",$m_,$d_);},  # 7
    sub {my($m_,$d_)=(@_); return sprintf("%02d-%02d",$d_,$m_);},  # 8
    sub {my($m_,$d_)=(@_); return sprintf("%02d.%02d",$m_,$d_);},  # 9
    );

  #------------------------------------------------------------------------------------------------------------------------
  # date format, long form

  @::ldateformat=(0,   'Dayname Monthname dd yyyy',
                  1,   'Dayname dd Monthname yyyy',
                  2,   'Dayname dd.Monthname yyyy',
                  3,   'Dayname dd-mm-yyyy',
                  4,   'Dayname, dd Monthname yyyy',
                  5,   'Dayname, dd Monthname, yyyy',
                  6,   'yyyy-Monthname-dd',
                  7,   'dd Monthname, yyyy',
                  8,   'dd. Monthname yyyy',
                  9,   'yyyy Monthname dd Dayname',
                  10,  'yyyy m. Monthname dd d.',      
                 );

   @::to_mdyw_string=( # month: 0--11
     sub { my($m_,$d_,$y_,$w_)=(@_); return "$w_ $::mname[$m_] $d_ $y_";}, # 0
     sub { my($m_,$d_,$y_,$w_)=(@_); return "$w_ $d_ $::mname[$m_] $y_";}, # 1
     sub { my($m_,$d_,$y_,$w_)=(@_); return "$w_ $d_.$::mname[$m_] $y_";}, # 2
     sub { my($m_,$d_,$y_,$w_)=(@_); $m_++; return "$w_ $d_-$m_-$y_";}, # 3
     sub { my($m_,$d_,$y_,$w_)=(@_); return "$w_ $d_ $::mname[$m_] $y_";}, # 4
     sub { my($m_,$d_,$y_,$w_)=(@_); return "$w_ $d_ $::mname[$m_], $y_";}, # 5
     sub { my($m_,$d_,$y_,$w_)=(@_); return "$y_-$::mname[$m_]-$d_";}, # 6
     sub { my($m_,$d_,$y_,$w_)=(@_); return "$d_ $::mname[$m_], $y_";}, # 7
     sub { my($m_,$d_,$y_,$w_)=(@_); return "$d_. $::mname[$m_] $y_";}, # 8
     sub { my($m_,$d_,$y_,$w_)=(@_); return "$y_ $::mname[$m_] $d_ $w_";}, # 9
     sub { my($m_,$d_,$y_,$w_)=(@_); return "$y_ m. $::mname[$m_] $d_ d.";}, # 10
    );

   @::to_mdy_string=( # month: 0--11
     sub { my($m_,$d_,$y_)=(@_); return "$::mname[$m_] $d_ $y_";}, # 0
     sub { my($m_,$d_,$y_)=(@_); return "$d_ $::mname[$m_] $y_";}, # 1
     sub { my($m_,$d_,$y_)=(@_); return "$d_.$::mname[$m_] $y_";}, # 2
     sub { my($m_,$d_,$y_)=(@_); $m_++; return "$d_-$m_-$y_";}, # 3
     sub { my($m_,$d_,$y_)=(@_); return "$d_ $::mname[$m_] $y_";}, # 4
     sub { my($m_,$d_,$y_)=(@_); return "$d_ $::mname[$m_], $y_";}, # 5
     sub { my($m_,$d_,$y_)=(@_); return "$y_-$::mname[$m_]-$d_";}, # 6
     sub { my($m_,$d_,$y_)=(@_); return "$d_ $::mname[$m_], $y_";}, # 7
     sub { my($m_,$d_,$y_)=(@_); return "$d_. $::mname[$m_] $y_";}, # 8
     sub { my($m_,$d_,$y_)=(@_); return "$y_ $::mname[$m_] $d_";}, # 9
     sub { my($m_,$d_,$y_)=(@_); return "$y_ m. $::mname[$m_] $d_ d.";}, # 10
    );

   @::to_md_string=(  # month: 0--11
     sub {my($m_, $d_)=(@_); $d_="0$d_" if $d_<10; return "$::mNames[$m_] $d_";}, # 0
     sub {my($m_, $d_)=(@_); $d_="0$d_" if $d_<10; return "$d_ $::mNames[$m_]";}, # 1 
     sub {my($m_, $d_)=(@_); $d_="0$d_" if $d_<10; return "$d_.$::mNames[$m_]";}, # 2
     sub {my($m_, $d_)=(@_); $d_="0$d_" if $d_<10; $m_++; return "$d_-$m_";}, # 3
     sub {my($m_, $d_)=(@_); $d_="0$d_" if $d_<10; return "$d_ $::mNames[$m_]";}, # 4
     sub {my($m_, $d_)=(@_); $d_="0$d_" if $d_<10; return "$d_ $::mNames[$m_]";}, # 5
     sub {my($m_, $d_)=(@_); $d_="0$d_" if $d_<10; return "$::mNames[$m_]-$d_";}, # 6
     sub {my($m_, $d_)=(@_); $d_="0$d_" if $d_<10; return "$d_ $::mNames[$m_]";}, # 7
     sub {my($m_, $d_)=(@_); $d_="0$d_" if $d_<10; return "$d_. $::mNames[$m_]";},# 8
     sub {my($m_, $d_)=(@_); $d_="0$d_" if $d_<10; return "$::mNames[$m_] $d_";}, # 9
     sub {my($m_, $d_)=(@_); $d_="0$d_" if $d_<10; return "$::mNames[$m_] $d_";}, # 10
    );

%::sixteenColors = (
    'black'  =>      '#000000',
    'silver' =>      '#c0c0c0',
    'gray'   =>      '#808080',
    'white'  =>      '#ffffff',
    'maroon' =>      '#800000',
    'red'    =>      '#ff0000',
    'purple' =>      '#800080',
    'fuchsia'=>      '#ff00ff',
    'green'  =>      '#008000',
    'lime'   =>      '#00ff00',
    'olive'  =>      '#808000',
    'yellow' =>      '#ffff00',
    'navy'   =>      '#000080',
    'blue'   =>      '#0000ff',
    'teal'   =>      '#008080',
    'aqua'   =>      '#00ffff',
    );

  # a toy
  @::themeColors=(  "#dfa62f", "#c41bc4", "#24935a", "#281cce", "#8e2477", "#e25809", "#1f75b7");

}
#=====================================================================================================
#
sub initVars {
  %::scntr=();$::scntr=0;
  %::now = ();
  %::oneDayEvents=();
  %::popupEvents=(); %::blinkEvents=(); %::chimeEvents=();
  @::yeartable=();
  %::warnEvents =();
  %::meetingGroups = ();
  %::GlobalMeetingGroups=();
  @::caldata=();
  @::addressbook=();
  %::namehash = ();
  $::oneDayDetails = 0;
  %::oneDayDetails = ();
  %::allTips = ();    
  $::allTipcnt=0;
  %::ctasks =();
  %::ctasksDetails =();
  %::ptasks =();
  %::ptasksDetails =();
  %::oneDayMisc = ();  
  %::oneDayCats = ();
  %::oneDaySpkrs = ();
  %::oneDayRooms = ();
  %::oneDayEventRefs = ();
  $::year_special_cached=0;
  $::diaryContent = "";

  # display options
  $::vm=0; 
  $::vmc="";
  $::vmg="";
  $::vmp="";
  $::mnbar="";
  $::vnbar="";
  %::calinfo= (
	       w		=> '',
	       c		=> 'get',
	       v		=> 0,
	       ls		=> 255, #mark unset
	       hourB		=> 7,
	       hourE		=> 18,
	       interval		=> 30,
	       mg               => '',
	      );
  %::d =      (
	       'doChimeCount'	=> 0,
	       'eventCounter'	=> 1,
	       'remote_user'	=> "",
	       'authResult'	=> 0,
	       'ispublic'	=> 0,
	       'megaCal'	=> "",
	       'editorState'	=> "",
	       'namecounter'	=> 0,
	       'validuser'	=> 2,
	       'multilingual'	=> 1,
	       'ceditor'	=> "",
	      );

  %::o =      ();
  my ($k, $v); foreach $k (keys %webcalConfig::c) {$::o{$k} = $webcalConfig::c{$k};}
  if(!$::o{'tclra'}){$::o{'tclra'}="#ff0000"; $::o{'tclrt'}="#009900";$::o{'tclrm'}="#990099";$::o{'tclrs'}="#0066ff";}
  %::banner = ();
  $::banner{'this'}= 0;
  $::banner{'headseg'}= ""; 
  $::banner{'prolog'}= ""; 
  $::banner{'postscript'}="";
  $::style_sheet =""; $::style_sheet_self =""; $::style_sheet_self_default =""; 
  $::style_sheet_system ="";  %::css = (); 
  %::authors=();
  $::is_authorized_author=0;
  %::moderated=();
  %::debugInfo = ();    
  $::catfilterpattern="";
  $::catfiltersub=sub{1};
  $::srchftrptn="";
  $::srchi=$::srchn="";
  @::srchwords=();
  $::authCookie="";
}

#=====================================================================================================
# A few supporting subs.
# return weekday 0=sun 1=mon .. 6=sat
sub wday {
    use integer;
    my ($ce, $code, $month, $day, $year, @mcode);
    @mcode=(0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4);
    ($month, $day, $year) = (@_);
    if($month < 2) { $year -= 1;}
    $ce = $year/100; $year= $year % 100;
    $code = $mcode[$month] + ($ce * 5) + $year + ($year >>2)+ ($ce >>2);
    $code = ($day + $code) % 7;
    return $code;
}
# According to ISO 8601, weeks are 7 days counting from Monday
# The first week is the week contain the first Thursday of the year,
# it is the week containing Jan 4.
# In the US, week starts on Sundays, sigh--
#
sub weekNum {
  use integer;
  my($ndays, $wcode);
  my($m,$d,$y,$start)=(@_);
  $ndays = ndays($m, $d, $y, 0, 4, $y);	# number of days from Jan 4 inclusive, may be negative
  $wcode = wday(0,4,$y);	# weekday of Jan 4.
  if($wcode == 0) {$wcode = 7;}
  if($ndays <= 0) {		# Jan 1,2,3
    if($wcode <= 3 and $wcode + $d < 4+$start) {
	# return the last week number of last year
	my ($nn, $wc);
	$nn = ndays(11, 31, $y-1, 0, 4, $y-1);
	$wc = wday(0,4,$y-1);	# weekday of Jan 4.
	if($wc == 0) { $wc = 7;}
	return(($nn - 1 - $start + $wc)/7 + 1);
    }
    return(1);
  } else {
    return( ($ndays - 1 - $start + $wcode)/7 + 1);
  }
}

sub isleap {
    use integer;
    my $year = (@_)[0];
    if(($year & 3) == 0 && ( $year%100 != 0 || $year%400 == 0)) { return(1);}
    return(0);
}
sub ndays_in_month { # month: 0--11; year: xxxx 
    my ($month, $year) = (@_);
    if($month != 1) { return $::mdays[$month];}
    return (($year & 3) == 0 && ( $year%100 != 0 || $year%400 == 0))? 29 : 28;
}
#---------------------------------------------------------------------------------------------------------
#  based on the short form of date format.
sub to_native_date {
    # convert mm/dd/yyyy to native date format, short form
    # month: 1--12
    my $n = $::o{'dateformat'}; $n=0 if not $n;
    my $ff = $::toNativeDate[$n];
    return &$ff(@_);
}
sub to_wcal_date {
    # convert from native date to mm/dd/yyyy
    # month: 1--12
    my $n = $::o{'dateformat'}; $n=0 if not $n;
    my $ff= $::toWcalDate[$n];
    my $ans= &$ff(@_);
    my ($m,$d,$y)=split(/\//, $ans); $m+=0; $d+=0; $y+=0;
    if($y<100){if($y>=90){$y+=1900;}else{$y+=2000;}}
    return "$m/$d/$y";
}
sub md_nstring {
    # month: 1--12
    my $n = $::o{'dateformat'};  $n=0 if not $n;
    my $ff = $::to_md_nstring[$n];
    return &$ff(@_);
}
sub mdy_nstring { 
    # mn: 1--12
    my $n = $::o{'dateformat'};  $n=0 if not $n;
    my ($mn, $dy, $yr) = (@_);
    my $ff=$::toNativeDate[$n];
    return &$ff("$mn/$dy/$yr");
}
#---------------------------------------------------------------------------------------------------------
# based on the long form of date format.
sub md_string {
    my $n = $::o{'dateformat2'}; $n=0 if not $n;
    my $ff = $::to_md_string[$n];
    return &$ff(@_);
}
sub mdy_string { # mn: 0--11
    my $n = $::o{'dateformat2'}; $n=0 if not $n;
    my $ff = $::to_mdy_string[$n];
    return &$ff(@_);
}
sub mdy_wstring {  #mn: 0--11
    my ($wcode, $mn, $dy, $yr, $wn, $n);
    ($mn, $dy, $yr) = (@_);
    $wcode= wday($mn, $dy, $yr);
    $wn = $::wdays[$wcode];
    $n = $::o{'dateformat2'}; $n=0 if not $n;
    my $ff = $::to_mdyw_string[$n];
    return &$ff($mn, $dy, $yr, $wn);
}
sub mdy_swstring {  #mn: 0--11
    my ($wcode, $mn, $dy, $yr, $wn, $n);
    ($mn, $dy, $yr) = (@_);
    $wcode= wday($mn, $dy, $yr);
    $wn = $::wkdNames[$wcode];
    $n = $::o{'dateformat2'}; $n=0 if not $n;
    my $ff= $::to_mdyw_string[$n];
    return &$ff($mn, $dy, $yr, $wn);
}
#---------------------------------------------------------------------------------------------------------
sub printDate {
    use integer;
    my ($mn, $dy, $yr, $out);
    ($mn, $dy, $yr) = canDate(@_);
    $mn += 1;
    $out = "$mn/$dy/$yr";
    return $out;
}
sub printDate0 {
    my ($mn, $dy, $yr, $out);
    ($mn, $dy, $yr) = canDate(@_);
    $out = "$mn/$dy/$yr";
    return $out;
}

sub canDate {
    use integer;
    my ($mn, $dy, $yr, $tmp, $out);
    ($mn, $dy, $yr) = (@_);
    if($mn < -3600 or $mn > 3600 or $dy <-10000 or $dy > 100000){calerror("$::phr{'invalid_date'}: Month=$mn  Day=$dy  Year=$yr", 1);}
    while( $mn < 0) { $mn += 12; $yr -= 1; }
    while( $mn > 11) { $mn -= 12; $yr += 1;}

    while( $dy <= -365) {
	$dy += 365;
	if($mn > 1) { if(isleap($yr)) {$dy += 1;}}
	$yr -= 1;
    }

    while( $dy >= 365) {
	$dy -= 365;
	if($mn <= 1) { if(isleap($yr)) {$dy -= 1;}}
	$yr += 1;
    }

    while( $dy <= 0) {
	if($mn == 0) { $mn = 11; $yr -= 1; $dy += 31;}
	else {
	    $mn -= 1;
	    if($mn == 1) { if(isleap($yr)) {$tmp = 29; } else {$tmp = 28;}}
	    else { $tmp = $::mdays[$mn]; }
	    $dy += $tmp;
	}
    }
    if(isleap($yr)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}
    while( $dy > $::mdays[$mn] ) {
	if($mn == 11) {
	    $mn = 0; $yr += 1; $dy -= 31;
	    if(isleap($yr)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}
	}
	else {
	    $dy -= $::mdays[$mn]; $mn += 1;
	}
    }
    return( ($mn, $dy, $yr));
}
#=====================================================================================================
# return the number of seconds of (ns, nh, nd, nm, nh) from 0:00 Jan 1, 1997
#
sub timeLocal {
    use integer;
    my ($tmp, $ndays, $ns, $nN, $nh, $nd, $nm, $ny);
    ($ns, $nN, $nh, $nd, $nm, $ny) = (@_);
    if($ny < 90) { $ny += 2000;}
    elsif($ny <= 99) { $ny += 1900;}
    if($ny < 1997) {$ny =1997;} elsif($ny > 2050) { $ny = 2050;}
    $ndays = ndays($nm, $nd, $ny, 0,1,1997)-1;
    $nh = 0 if ($nh eq "");
    $nN = 0 if ($nN eq "");
    $ns = 0 if ($ns eq "");
    $tmp= $ndays * 86400 + $nh * 3600 + $nN * 60 + $ns;
    return($tmp);
}

sub hm_string {
    my ($tim,$ampm);
    my ($hr,$mn) = (@_);

    $hr = 0 if ($hr eq "");
    $mn = "00" if ($mn eq "" || $mn eq "0");
    if (not $::o{'hourformat'}) {
      if($hr > 12) {
	$hr-=12;
       	if($hr == 12) { $ampm="a"; } else { $ampm="p"; }
      }
      elsif($hr == 12){ $ampm="p"; } else { $ampm="a"; }
#      $tim = "$hr:$mn$ampm";
      $tim = sprintf "%02.2d:%02.2d$ampm",$hr,$mn;
    }
    else {
      $tim = sprintf "%02.2d:%02.2d",$hr,$mn;
    }

    return $tim;
}

sub hm_hm_string {
    my ($tim, $ap, $bp);
    my ($hr,$mn,$ehr,$emn) = (@_);

    if (not $::o{'hourformat'}) {
	if (($hr eq $ehr) and ($mn eq $emn)) {
	    if($hr > 12) {$hr-=12; if($hr==12) {$ap='a';}else{$ap='p';}} 
	    elsif($hr == 12) { $ap='p'} 
	    else {$ap='a';}
	    $tim = sprintf "%02.2d:%02.2d$ap",$hr,$mn;
	}
	else {
	    if($hr > 12) {$hr-=12; if($hr == 12){ $ap='a';} else {$ap='p';}} elsif($hr == 12){$ap='p';} else {$ap='a';}
	    if($ehr > 12) {$ehr-=12; if($ehr ==12){ $bp='a';} else {$bp='p';} } elsif($ehr==12){$bp='p'} else {$bp='a';}
	    $tim = sprintf "%02.2d:%02.2d$ap-%02.2d:%02.2d$bp",$hr,$mn,$ehr,$emn;
	}
    }
    else {
	if ((($hr eq $ehr) and ($mn eq $emn)) or ($ehr eq "-") or ($emn eq "-")) {
	     $tim = sprintf "%02.2d:%02.2d",$hr,$mn;
	}
	else {
	     $tim = sprintf "%02.2d:%02.2d-%02.2d:%02.2d",$hr,$mn,$ehr,$emn;
	}
    }

    return $tim;
}

#=====================================================================================================
# print headers and standard HTML intro
sub headers {
    my ($title,$script,$refresh,$banner,$overlay,$body) = (@_);
    my $chunk1 = $::authCookie;
#   print  "Cache-Control: must-revalidate\n";    
    if($::phr{'CHARSET'}) { $chunk1 .= "Content-type: text/html; charset=$::phr{'CHARSET'}\n\n";}
    else { $chunk1 .= "Content-type: text/html\n\n";}
    print $chunk1 if $chunk1;

    select((select(STDOUT), $| = 1)[0]);    
    print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">";
    print "<HTML><HEAD>";
#    if($::phr{'CHARSET'}) {print "<META HTTP-EQUIV=\"CONTENT-TYPE\" CONTENT=\"text/html; charset=$::phr{'CHARSET'}\">\n"; }
    if($refresh and !($::vm & 0x80000)) { 
	print "<META HTTP-EQUIV=\"refresh\" CONTENT=\"$refresh\">\n";
    }
    print $::banner{'headseg'} if $banner;
    print "<TITLE>$title</TITLE>\n" if defined $title;
    print $::style_sheet if $::style_sheet;  
    if(! $::style_sheet_self_default) {	print $::style_sheet_system if $::style_sheet_system;}
    print $::style_sheet_self if $::style_sheet_self;      
    
    print "<SCRIPT LANGUAGE=\"JavaScript\" type=\"text/javascript\">\n<!--\n";

    if (defined $script || $overlay) {
	print "$script\n" if defined $script;
	if ($overlay) {
	    my $tooltipDelay;
	    if(defined $::calinfo{'tooltipDelay'} and $::calinfo{'tooltipDelay'}>0){
		$tooltipDelay=$::calinfo{'tooltipDelay'};
	    } elsif(defined $webcalConfig::r{'tooltipDelay'} and $webcalConfig::r{'tooltipDelay'}> 0){
		$tooltipDelay=$webcalConfig::r{'tooltipDelay'};
	    } else {$tooltipDelay=0;}
	    print "var w_timeout=$tooltipDelay;","\n";
	}
    }
    if($::o{'dnd'}){
	my $who=$::calinfo{'w'};
	print <<END;
function dodnd(cmd){var url="$::o{'cginame'}?c=dnd&w=$who&"+cmd;dndw=window.open(url,"dndw","scrollbars=yes,resizable=yes,width=8,height=8");if(window.focus){dndw.window.focus();}} 
END
    ;
    }
    print "// -->\n</SCRIPT>";
    print <<END;

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript" SRC="$::o{'imgdirurl'}/js.js"></SCRIPT>
END
    ;

    print "</HEAD>\n";
#    my $bgclr= $::calinfo{'bgcolor'} || $webcalConfig::r{'backgroundColor'};
    my $bgclr= $webcalConfig::r{'backgroundColor'};
    print "<BODY BGCOLOR=$bgclr TEXT=$webcalConfig::r{'textColor'} LINK=$webcalConfig::r{'linkColor'} VLINK=$webcalConfig::r{'linkColor'} topmargin=$webcalConfig::r{'topmargin'} marginheight=$webcalConfig::r{'marginheight'} leftmargin=$webcalConfig::r{'leftmargin'} marginwidth=$webcalConfig::r{'marginwidth'}";
    print " $body" if defined $body;
    print "><a name=uu></a>\n";
    if ($banner) {
	print $::banner{'prolog'};
	$::banner{'this'}= 1;
    }
}

# print trailer and standard HTML closer
sub trailer {
    my ($pad, $footer) =(@_);
    my ($key, $value);
    $|=1; print "<p>\n"; $|=0;

    if($::calinfo{'pnt'}) {
	; # do not print the hidden layers 
    } else {
	if($footer) {
	    my $zz= $footer;
	    if($::calinfo{'ftr'}) { $footer = customize_header(substImages($::calinfo{'ftr'}));}
	    elsif($::o{'footerCode'}) { $footer = customize_header(substImages($::o{'footerCode'}));} 
	    else {$footer = "";}
	    if($footer) { print "<p>\n<br>\n<p>\n<br>\n", $footer, "<br>\n";}
	}
	my ($fb, $fe) = ("<span class=\"tip\">", "</span>");
	if($webcalConfig::fontsize{'tip'}) { $fb="<font $webcalConfig::fontsize{'tip'}>$fb"; $fe="$fe</font>";}
    	for $key (keys %::allTips) {
	    $value = $::allTips{$key}; $value =~ s/blink>/bnxx>/g;
	    print <<END;
<div id="$key" style="position:absolute;z-index:16;visibility:hidden;top:0px;left:0px;">
<table border=0 cellspacing=0 cellpadding=0 bgcolor="#000000" class="tipholder">
<tr class="tipholder"><td bgcolor="#000000" class="tipholder">
 <table width="100%" cellpadding=8 cellspacing=1 border=0 bgcolor="#000000" class="tip"><tr class="tip"><td bgcolor="#c1edff" class="tip">$fb$value$fe</td></tr></table>
</td></tr></table>
</DIV>
END
    ;
	}
    	for $key (sort keys %::debugInfo) {
	    $value = $::debugInfo{$key};
	    print "<pre>$key=>$value<br></pre>";
	}
    }
    print $::banner{'postscript'} if $::banner{'this'};
    print "<p>\n<br>\n" x 9 if $pad;
    $|=1;  print "</body></html>\n"; $|=0;
}
#================================================================================================
sub addtip { # for arbitary tips
    my ($v) = (@_);
    my $c = $::allTipcnt;  $::allTipcnt++;
    my $k = "e$c";
    $::allTips{$k} = $v;
    return $k;
}
sub add2tip { # for RSVP
    my ($t, $v) = (@_);
    my $k="r$t";
    if(! exists($::allTips{$k})) { $::allTips{$k} = $v;}
    return $k;
}
sub add3tip { # for time intervals
    my ($t) = (@_);
    my $k = $t; $k =~ s/\W+//g; $k =~ s/_//g; $k = "t$k";
    if(! exists($::allTips{$k})) { $::allTips{$k} = $t;}    
    return $k;
}
sub add4tip { # for event details.
    my ($t, $v, $or) = (@_);
    my $k = "d$t";
    if($or or ! exists($::allTips{$k})) { $::allTips{$k} = $v;}    
    return $k;
}
#================================================================================================
# decode data from URL and escape HTML characters
sub urldecode {
    my ($value,$unhtml) = (@_);
    $value = "" if (!defined $value);
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
    $value =~ s/\r\n/\n/g;
    $value =~ s/\r/\n/g;
    if ($unhtml) {
    $value =~ s{(.)}{
        if    ($1 eq '<')           { '&lt;'    }
        elsif ($1 eq '>')           { '&gt;'    }
        elsif ($1 eq '&')           { '&amp;'   }
        elsif ($1 eq '"')           { '&quot;'  }
        elsif ($1 eq "\x8b")        { '&#139;'  }
        elsif ($1 eq "\x9b")        { '&#155;'  }
        else                        { $1    }
    }gsex;
  }
    return $value;
}

# encode data for inclusion in URL"
sub urlencode {
    my ($value) = (@_);
    $value =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
    return $value;
}
#=====================================================================================================

sub popupClrSelect {
  my ($r,$g,$b, $i, $j, $str, $cmd, $fg, $bg, $fix, $erasef, $eraseb);
  $cmd= (@_)[0];

  if($cmd eq 'showclr') {
      $fg = 'fgclr';   $bg = 'bgclr';  $fix="";  
      $erasef = "window.opener.document.webcal.pfgclr.selectedIndex=0;
if(window.opener.document.webcal.clrpair)window.opener.document.webcal.clrpair.selectedIndex=0;";
      $eraseb = "window.opener.document.webcal.pbgclr.selectedIndex=0;
if(window.opener.document.webcal.clrpair)window.opener.document.webcal.clrpair.selectedIndex=0;";
  } else { 
      $_ = $cmd;  s/^showclr//;  $fg = $_.'fg';   $bg = $_.'bg';   $fix='o';  
      $erasef = $eraseb = "";
  }

  &headers(undef,"function setFG(clr) {window.opener.document.webcal$fix.$fg.value = '#'+clr; $erasef }
function setBG(clr) {window.opener.document.webcal$fix.$bg.value = '#'+clr; $eraseb}");


  print "<center><br><font size=+1><b><span class=\"miscTitleSmall\">$::phr{'ForegroundColor'}</span></b></font><br>\n";
  print "<table border=0 cellpadding=2 cellspacing=2>\n<tr>";

  $i = 0;
  for($b=51; $b <= 255; $b += 51) {
    for($g=51; $g <= 255; $g += 51) {
      for($r=51; $r <= 255; $r += 51) {
	if($i == 0) { print "</tr>\n<tr>";}
	$str = sprintf "%02x%02x%02x", $r, $g, $b;
	print "<td bgcolor=#$str><a href=\"JavaScript:setFG('$str')\"><font color=#$str>&nbsp;&nbsp;&nbsp;</font></a></td>";
	$i++; if($i == 25) { $i = 0;}
      }
    }
  }
  print "</tr></table>";

  print "<p><font size=+1><b><span class=\"miscTitleSmall\">$::phr{'BackgroundColor'}</span></b></font><br>\n";
  print "<table border=0 cellpadding=2 cellspacing=2>\n<tr>";
  $i = 0;
  for($b=255; $b >= 51; $b -= 51) {
    for($g=255; $g >= 51; $g -= 51) {
      for($r=255; $r >= 51; $r -= 51) {
	if($i == 0) { print "</tr>\n<tr>";}
	$str = sprintf "%02x%02x%02x", $r, $g, $b;
	print "<td bgcolor=#$str><a href=\"JavaScript:setBG('$str')\"><font color=#$str>&nbsp;&nbsp;&nbsp;</font></a></td>";
	$i++; if($i == 25) { $i = 0;}
      }
    }
  }
  print "</tr></table>";
  print "<table><tr><td><form><input type=button onClick=\"self.close(); window.opener.pwin='';\" value=\"$::phr{'Close'}\" class=\"fmBtn\"></form></td></tr></table>\n";
  print "</center>";
  &trailer(0,0);
}

#===============================================================================================
sub getCalendars {
  my ($which) = (@_);
  my ($item, @othercals, $j, $script);
  &headers(undef,"");
  $::calinfo{'_clist_'} = 1;
  my (@bgclrs)=($webcalConfig::r{'rowColors'}->[1],$webcalConfig::r{'rowColors'}->[3]);
  my $tab_hbg= $webcalConfig::r{'tabcolorh'};

  print "<center><h2><span class=\"miscTitle\">$::phr{'PleaseSelectACalendar'}</span></h2></center>\n";
  print "<center><table border=0 cellpadding=2 cellspacing=1 class=\"listCal\">";

################################################!!
my($exp);
  $j=0;
  get_global_mgroups();
  @othercals= (sort keys %::GlobalMeetingGroups);
  foreach $item (@othercals) {
      $exp = $::GlobalMeetingGroups{$item}; $exp=~s/:/,/g;
      $item=~s/^mgp_//;
      my $bgclr=$bgclrs[$j]; $j = ($j == 0? 1: 0);
      if($which >= 0) {
	  my $href="javascript:sca(\'$exp\',$which)";
	  my $hover="onmouseover=\"nhover(this,1,'$tab_hbg','$bgclr')\" onmouseout=\"nhover(this,0,'$tab_hbg','$bgclr')\" onclick=\"$href\"";
	  print "<tr bgcolor=$bgclr class=\"listCalTR$j\"><td class=\"listCalTd1\" $hover>
<a href=\"$href\"><font color=red><span class=\"listCalGName\">$item</span></font></a></td>
<td class=\"listCalDes\">$::phr{'Meeting_group'} &nbsp;</td></tr>";
      }  else {  print "<tr bgcolor=$bgclr><td class=\"listCalGName\">$item</td><td class=\"listCalDes\">$::phr{'Meeting_group'}</td></tr> ";}
  }
  print "<tr><td colspan=2></td></tr>\n";

  get_private_mgroups($::calinfo{'w'});
  @othercals= (sort keys %::meetingGroups);
  foreach $item (@othercals) {
      $exp = $::meetingGroups{$item}; $exp=~s/:/,/g;
      $item=~s/^mgp_//;
      my $bgclr=$bgclrs[$j]; $j = ($j == 0? 1: 0);
      if($which >= 0) { 
	  my $href="javascript:sca(\'$exp\',$which)";
	  my $hover="onmouseover=\"nhover(this,1,'$tab_hbg','$bgclr')\" onmouseout=\"nhover(this,0,'$tab_hbg','$bgclr')\" onclick=\"$href\"";

	  print "<tr bgcolor=$bgclr class=\"listcalTR$j\"><td class=\"listCalTd1\" $hover>
<a href=\"$href\"><font color=red><span class=\"listCalGNameT\">$item</span></font></a></td>";
	  print "<td class=\"listCalDes\">$::phr{'Meeting_group'} &nbsp;</td></tr>";
      } else  {  print "<tr bgcolor=$bgclr><td class=\"listCalGName\">$item</td><td class=\"listCalDes\">$::phr{'Meeting_group'}</td></tr> ";}
  }

  print "<tr><td colspan=2></td></tr>\n";
###################################################

  my $nhref = &get_name_list;
  @othercals = &listcals;
  delete $::calinfo{'_clist_'};
  unshift @othercals,$::phr{'CombinedCalendar'} if($::d{'megaCal'} ne "");

  foreach $item (@othercals) {
      my $des = ""; if($nhref->{$item}) {$des = $nhref->{$item};}
      my $bgclr=$bgclrs[$j]; $j = ($j == 0? 1: 0);
      if($which >= 0) {
	  my $href ="javascript:sca(\'$item\',$which)";
	  my $hover="onmouseover=\"nhover(this,1,'$tab_hbg','$bgclr')\" onmouseout=\"nhover(this,0,'$tab_hbg','$bgclr')\" onclick=\"$href\"";
	  print "<tr bgcolor=$bgclr class=\"listcalTR$j\"><td class=\"listCalTd1\" $hover>
<a href=\"$href\"><b><span class=\"listCalNameT\">$item</span></b></a></td>
<td class=\"listCalDes\">$des &nbsp;</td></tr>";	
      }  else {  print "<tr bgcolor=$bgclr class=\"listCalTR$j\"><td class=\"listCalName\">$item</td><td class=\"listCalDes\">$des &nbsp;</td></tr>";}
  }

  print "<tr><td colspan=2></td></tr>\n";
  print "<tr><td colspan=2 align=center><form><font color=#ff0000><b>
<input type=button onClick=\"self.close();\" value=\"$::phr{'Close'}\" class=\"fmBtn\"></b></font></form></td></tr>\n";
  print "</table></center>";
  if($::calinfo{'listcalnbar'}) {
      print "<br><center>$::calinfo{'listcalnbar'}</center>";
      delete $::calinfo{'listcalnbar'};
  }
  &trailer(0,0);
}
#===============================================================================================

sub smallCal { #date selection popup
    use integer;
    my ($imonth, $iday, $iyear, $stmp, $out, $i, $day, $ndays, $syr, $smn, $yr, $nn, $mm,$code,$pmonth, $nmonth,$who,
	$itmp, $tyr, $tmn, $tdy, $todayc, $wklen, $percent, $ucode, $wknum, $offset, $mg, $jk, $str, $date, $cmd);

    $cmd= $::calinfo{'c'};
    $who = $::calinfo{'w'};
    $imonth= $::calinfo{'month'};
    $iyear = $::calinfo{'year'};
    $mm = $imonth; $nn = $iyear;
    $tmn = $::now{'month'}; $tdy = $::now{'day'}; $tyr = $::now{'year'};
    # validate date
    while( $mm < 0) { $mm += 12; $nn -= 1; }
    while( $mm > 11) { $mm -= 12; $nn += 1;}
    $syr = $nn; $smn = $mm;		#save year, month [0-11]
    $imonth = $smn; $iyear=$syr;	#modified input
    $pmonth = $imonth-1;
    $nmonth = $imonth+1;
    # compute weekday offset
    if(isleap($syr)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}
    $code = wday($smn, 1, $syr);
    $ndays = $::mdays[$smn];
    $todayc = printDate( $::now{'month'}, $::now{'day'}, $::now{'year'});
    $itmp = 0;
    if($::o{'excludeWeekend'}) { $wklen = 5; } else { $wklen = 7; }

    my $r1clr=$webcalConfig::r{'r1color'};
    $_ = $cmd;
    s/^smallcal-//;
    &headers(undef,"function setdate(str) {window.opener.document.$_.value = str; self.close();}");

    $out = "<center>
<a href=\"$::o{'cginame'}?c=$cmd&w=$who&d=$pmonth/1/$iyear$::vmg\"><img src=\"$::o{'imgdirurl'}/left.gif\" width=11 height=11 border=0></a>
<span class=\"dsMonthName\">$::mname[$smn] $syr</span>
<a href=\"$::o{'cginame'}?c=$cmd&w=$who&d=$nmonth/1/$iyear$::vmg\"><img src=\"$::o{'imgdirurl'}/right.gif\" width=11 height=11 border=0></a></center>
<center>
<table border=1 cellpadding=0 cellspacing=0 width=\"100%\">
<tr>\n";
    for ($i = 0; $i < $wklen; $i++) {
	$out .= "<td width=30 bgcolor=$r1clr align=center class=\"dsRow1Td\"><span class=\"dsRow1Txt\">$::swd[$::o{'weekstart'}+$i]</span></td>";
    }
    $out .= "</tr>\n";
    $ucode = ($code) % 7;
    if( ! $::o{'excludeWeekend'} || ( $ucode >$::o{'weekstart'} && $ucode <=5)) {
	if($::o{'weekstart'}) { $ucode = ($code==0? 6: $code - $::o{'weekstart'}); } else {$ucode = $code;}
	$stmp = "<td bgcolor=$webcalConfig::r{'backgroundColor'}><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=1 height=1 border=0></td>" x $ucode;
	$out .= "<tr>$stmp";
	$itmp=1;
    }
    $day = 1; $i = 0;
    $offset = $imonth * 31;
    while($day <= $ndays) {
	if($code % 7 == $::o{'weekstart'} && $day + $::o{'excludeWeekend'} > 1) {
            if($itmp) { $out .= "</tr>\n";}
	    $out .= "<tr>";
	    $itmp++; $i = 0;
	}
	my $ucode = $code % 7;
	if( ! $::o{'excludeWeekend'} || ( $ucode !=0 && $ucode !=6)) {
            if( $tyr == $syr && $tmn == $smn && $tdy == $day ) {
                $out .= "<td height=24 bgcolor=$webcalConfig::r{'todayHcolor'} align=right>";
            } else {
                $out .= "<td height=24 bgcolor=#ffffff align=right>";
            }
            $date = printDate($smn, $day, $syr);
            $str = to_native_date($date);
            $out .= "<a href=\"JavaScript:setdate('$str')\"><font size=-1><span class=\"dsDay\">$day</span></font></a>&nbsp;</td>";
            $i++;
	}
	$day++;
	$code++;
    }
    for(;$i<$wklen; $i++) {$out .= "<td bgcolor=$webcalConfig::r{'backgroundColor'}><br></td>";};
    $itmp += $::o{'excludeWeekend'};
    $out .= "</table>";
    print "$out";
    print "<table><tr><td><form><input type=button onClick=\"window.opener.dwin=''; window.close();\" value=\"$::phr{'Close'}\" class=\"fmBtn\"></form></td></tr></table>\n";
    print "</center>";
    &trailer(0,0);
}

sub linkSmallCal {
    my ($name,$who,$month,$year) = (@_);
    return "&nbsp;<a href=\"javascript:openpopup('$::o{'cginame'}?c=smallcal-$name&w=$who&d=$month/1/$year','dates',240,240)\"><img src=\"$::o{'imgdirurl'}/cal.gif\" width=16 height=15 border=0></a>";
}

#===============================================================================================

sub showVersion {
  my ($k, $v);
  &headers("Web Calendar",undef,undef,1);
  print <<END;
<center>
<br><h1><a href="http://www.ma.utexas.edu/WebCalendar/">You are running Web Calendar version $webCalVersion, $patchlevel</a></h1><br>
<a href="http://cvs.math.utexas.edu/cgi-bin/cvsweb.cgi/webCal2/?cvsroot=webCal">$cvsversion</a><br><br>
</center>
END
    ;
  print "<hr>";
  print "OS: $<br>$ $]<br>"; 
  if($ENV{'MOD_PERL'}) { print $ENV{'MOD_PERL'};}
  print "<hr>";
  print "Real UID: $<, Effective UID $>, Real GID: $(, Effective GID $) <br>";
  print "<hr>";
  if($::calinfo{'INC'}) {
      print "<br><b>INC Array:</b><br>"; map { print "$_<br>";} @INC;
      print "<hr>";
      print "<br><b>INC Hash:</b><br>";  map { print "$_ => $INC{$_}<br>";} (keys %INC);
      print "<hr>";
      print "<br><b>Environment:</b><br><br>"; map { print "$_ => $ENV{$_}<br>"; } (keys %ENV);
  }
  if($::calinfo{'config'}) {
      print "<hr>";
      print "<br><b>ConfigurationC:</b><br>";  map { print "$_ => $webcalConfig::c{$_}<br>"; } (keys %webcalConfig::c);
      print "<hr>";
      print "<br><b>ConfigurationR:</b><br>";
      map {
	  my $a=$webcalConfig::r{$_}; 
	  if(ref($a) eq 'ARRAY') {  print "$_ => ", '[ ', join(', ', @$a), ' ]<br>';}
	  else { print "$_ => $a<br>";}
      } (keys %webcalConfig::r);
      print "<hr>";
      print "<br><b>ConfigurationV:</b><br>"; 
      foreach $k (keys %webcalConfig::v) { 
	  print "<br><b>Virtual Server: $k</b><br>";
	  $v = $webcalConfig::v{$k};
	  map { print "$_ => $v->{$_}<br>"; } (keys %$v);
      }
  }

  &trailer(0,0);
}

#=====================================================================================================
sub wlog {
    my ($who, $raddr, $rhost, $qstr, $method, $ruser, $len, $cdate, @ltime, $cmon, $cday, $cyear, $chr, $cmin);
    my $logfile="$::o{'spooldir'}/log";
    my $fh = gensym;
    if (open($fh, ">>$logfile") ) {
	&webcalLock::doflock(\*$fh, LOCK_EX, "$logfile") or calerror("Cannot lock file $logfile': $!\n",1);     
	@ltime=(localtime);
	$cyear= 1900 + (@ltime)[5],
	$cmon = sprintf "%02d", 1+(@ltime)[4];
	$cday = sprintf "%02d", (@ltime)[3];
	$chr  = sprintf "%02d", (@ltime)[2];
	$cmin = sprintf "%02d", (@ltime)[1];
	$cdate= "$cmon/$cday/$cyear/$chr:$cmin";
	if(defined $ENV{'REMOTE_ADDR'}) {$raddr=$ENV{'REMOTE_ADDR'};} else {$raddr="";}
	if(defined $ENV{'REMOTE_HOST'}) {$rhost=$ENV{'REMOTE_HOST'};} else {$rhost="";}
	if(defined $ENV{'REMOTE_USER'}) {$ruser=$ENV{'REMOTE_USER'};} else {$ruser="";}
	if(defined $ENV{'REQUEST_METHOD'}) { $method=$ENV{'REQUEST_METHOD'};} else {$method="";}
	if(defined $ENV{'CONTENT_LENGTH'}){$len=$ENV{'CONTENT_LENGTH'};} else { $len='?';}
	$qstr=(@_)[0];
	$qstr =~ s/\\//g;
	$qstr =~ s/\$/\\\$/g;
	$qstr =~ s/\@/\\\@/g;
	$qstr =~ s/\'/\\\'/g;
	$qstr =~ s/\"/\\\"/g;
	print $fh "===========$cdate=============\n";
	print $fh "Raddr=$raddr,Rhost=$rhost,Ruser=$ruser\n";
	print $fh "method=$method,clen=$len\n";
	print $fh "Qstr=$qstr\n";
	&webcalLock::doflock(\*$fh, LOCK_UN, "$logfile") or calerror("Cannot unlock file $logfile: $!\n",1);     
	close $fh;
    }
}

# write values (from a hash) in a debug logfile
# usage: &webcalSupport::wdebug('calinfo',\%::calinfo);
sub wdebug {
    my ($name,$href,$key,$val);
    my $logfile="$::o{'spooldir'}/debug";
    my $fh = gensym;
    if (open($fh, ">>$logfile") ) {
	&webcalLock::doflock(\*$fh, LOCK_EX, "$logfile") or calerror("Cannot lock file $logfile': $!\n",1);     
	$name = shift;
	$href = shift;
	print $fh "===========$name=============\n";
	for $key (sort keys %$href) {
	    print $fh "$key: ";
	    $val = $$href{$key};
	    if (defined $val) {
		print $fh "\"$val\"\n";
	    } else {
		print $fh "undef\n";
	    }
	}
	&webcalLock::doflock(\*$fh, LOCK_UN, "$logfile") or calerror("Cannot lock file $logfile': $!\n",1);     
	close $fh;
    }
}

sub intersectTimeinterval {
  my ($ihr, $imn, $fhr, $fmn, $bhr, $bmn, $ehr, $emn) = (@_);
  my ($a, $b, $c, $d);
  $a = $ihr * 100 + $imn;
  $b = $fhr * 100 + $fmn;
  if($a == $b) { $b++; }
  $c = $bhr * 100 + $bmn;
  $d = $ehr * 100 + $emn;

  if( ($c >= $a and $c < $b) or ($d > $a and $d <= $b) or
      ($a >= $c and $a < $d) or ($b > $c and $b <= $d)) { return 1;}
  return 0;
}

sub sorttime {
    my ($ah, $am, $bh, $bm, $c1,$c2);
    ($ah, $am ) = split(/:/,$a);
    ($bh, $bm ) = split(/:/,$b);
    if($ah eq "") { return -1;}
    elsif($bh eq "") { return 1;}
    if($ah > $bh) { return 1;}
    elsif ($ah < $bh) { return -1;}
    elsif ($am > $bm) { return 1;}
    elsif ($am < $bm) { return -1;}
    else { return 0;}
}

sub dtAafterB {		#return 1 if a is after b
    use integer;
    my ($ma,$da,$ya,$ha,$na, $mb, $db,$yb,$hb,$nb) =(@_);
    if($ya > $yb) { return 1;}
    elsif ($ya == $yb) {
	if( $ma > $mb) { return 1;}
	elsif( $ma == $mb) {
	    if( $da > $db) { return 1;}
	    elsif($da == $db) {
		if($ha > $hb) { return 1;}
		elsif ( $ha == $hb) {
		    if( $na >= $nb) { return 1;}
		}
	    }
	}
    }
    return 0;
}

sub mdyAafterB {	#return 1 if a is after b
  use integer;
  my ($ma,$da,$ya, $mb, $db,$yb) =(@_);
  if($ya > $yb) { return 4;}
  elsif ($ya == $yb) {
    if( $ma > $mb) { return 3;}
    elsif( $ma == $mb) {
      if( $da > $db) { return 2 ;}
      elsif( $da == $db) { return 1 ;}
    }
  }
  return 0;
}

sub ndays {	# compute the number of days from $dm/$dd/$dy to $tm/$td/$ty inclusive
  use integer;
  my( $tm, $td, $ty, $dm, $dd, $dy, $count, $mm, $aa,$i);
  my @mndays=(31,28,31,30,31,30,31,31,30,31,30,31);
  ($tm, $td, $ty, $dm, $dd, $dy)= (@_);
  if( $ty > $dy + 1000 ) { calerror("In ndays: fromYear=$dy toYear=$ty are too far apart!",1);}
  $count=0; 
  for($i=$dy; $i<$ty; $i++){ $count += 365; if(isleap($i)) {$count++;}}
  if(isleap($dy)) {$mndays[1] = 29;}
  $mm = 0;
  for($i=0; $i < $dm; $i++) { $mm += $mndays[$i];} $mm += $dd;
  if(isleap($ty)) {$mndays[1] = 29;} else { $mndays[1] = 28;};
  $aa = 0;
  for($i=0; $i < $tm; $i++) { $aa += $mndays[$i];} $aa += $td;
  $count=$count -$mm + $aa + 1;
  return($count);
}

sub nweeks {	# count the number of weeks since $dm/$dd//$dy
  use integer;
  my( $tm, $td, $ty, $dm, $dd, $dy, $ndays, $code, $ans);
  my @mndays=(31,28,31,30,31,30,31,31,30,31,30,31);
  ($tm, $td, $ty, $dm, $dd, $dy)= (@_);
  $ndays = ndays(@_);
  $code = wday($dm, $dd, $dy);
  $ans = ($ndays + $code -1 -$::o{'weekstart'}) / 7;
  return($ans+1);
}

sub nmonths {	# compute the number of months from $dm/$dd/$dy to $tm/$td/$ty inclusive
  use integer;
  my( $tm, $ty, $dm, $dy, $count, $mm, $aa,$i);
  ($tm, $ty, $dm, $dy)= (@_);
  $count = ($ty - $dy) * 12 + ($tm - $dm + 1);
  return($count);
}

sub warntime {
  my ($ival,$unit) = (@_);

  if($unit eq 'm')    {
    $ival *= 60;
  } elsif($unit eq 'h') {
    $ival *= 3600;
  } elsif($unit eq 'd') {
    $ival *= 86400;
  } elsif($unit eq 'w') {
    $ival *= 604800;
  }
  return $ival;
}

#=====================================================================================================
sub validname {		# check if a valid calendar name
  my ($name) = (@_);

  return 0 if $name eq "";
  return 0 if $name =~ /^\./;
  return 0 if $name !~ /^[A-Za-z][\w|\.|\-|=]+$/;
  return 1;
}

sub validmname {		# check if a valid calendar name or email
  my ($name) = (@_);
  return 0 if $name eq "";
  return 0 if $name =~ /^\./;
  return 0 if $name !~ /^[A-Za-z][\w|\.|\@|\-|=]+$/;
  return 1;
}


sub untaintname {
  my ($name, $err) = (@_);

  if ($name =~ /^([^\/]*)$/) {
      $name = $1;
  } else {
      calerror("$err $name");
  }
  return $name;
}

sub listcals {
  my (@cals, @rcals, $name, $cmd);
  @cals = (); @rcals=();
  my $who = $::calinfo{'w'};
  if($::calinfo{'_clist_'}) {
      my $ruser = $::d{'remote_user'};
      my $list = undef;
      if( -f "$::o{'spooldir'}/$ruser/info") { $list = getinfo($ruser, 'clist');}
      if( !$list and -f "$::o{'spooldir'}/$who/info") { $list = getinfo($who, 'clist');}
      if($list) { @cals = split(/[,:]/, $list); }
      if(0+@cals > 0) { return sort {uc($a) cmp uc($b)} @cals;}
  }
  my $pgp = getcalpvgroup($::d{'remote_user'}); 
  if(!$pgp and $::d{'remote_user'} ne $who) { $pgp = getcalpvgroup($who);}
  if($pgp) {
      my ($gadm, @rcals) = list1vgroup($pgp); my $in=0; my $s; for $s (@rcals) { if($s eq $who) { $in=1; last;}}
      if($in==0) {push @rcals, $who; }
      return @rcals;
  }
  if($::o{'listAllCals'} == 0) { return("Calendar listing has been disabled by your administrator.");}
  my $DIR1= gensym;
  if (opendir($DIR1, $::o{'spooldir'})) {
      my @entries = grep(!/^\./, readdir($DIR1)); closedir($DIR1);
      @cals = sort {uc($a) cmp uc($b)} @entries;     
      my $len = $#cals;
      if( not $::o{'maxCals'}) { $::o{'maxCals'} = 400;}
      if($len > $::o{'maxCals'}) {
	  my ($offset, $nbar, $i, $j); $nbar = "";
          $cmd = 'getcal'; if($::calinfo{'selectCal'}) { $cmd= 'v&anonymous=1';}
	  if($::calinfo{'listcaloffset'}) {$offset = $::calinfo{'listcaloffset'};} else {$offset = 0;}
	  for($i=0; $i<$len; $i+= $::o{'maxCals'}) {
	      $j = $i+( $::o{'maxCals'} -1);
	      my $tmp = "$i" . "-" . "$j";
	      if($nbar) { $nbar .= "&nbsp;|&nbsp;";}
	      if($i ne $offset) { $nbar .= "<a href=\"$::o{'cginame'}?c=$cmd&listcaloffset=$i\" class=\"lnkrange\"><font color=#0000ff>$tmp</font></a>";}
	      else { $nbar .= "<font color=\"#333333\"><span class=\"lnkrange\"><b>$tmp</b></span></font>";}
	  }
	  $::calinfo{'listcalnbar'} = "<span class=\"rangeSelectNBar\">$nbar</span>";
	  my $end = $len;
	  if($len > $offset + $::o{'maxCals'}) { $end=$offset +$::o{'maxCals'};};
	  for($i=$offset; $i<$end; $i++) {
	      my $tmp = $cals[$i];
	      if( -d "$::o{'spooldir'}/$tmp" and $tmp !~ /^\./) {
		  push @rcals, $tmp;
	      }
	  }
      } else {
	  my $tmp;
	  foreach $tmp (@cals) {
	      if(-d "$::o{'spooldir'}/$tmp" and  $tmp !~ /^\./ ) {
		  push @rcals, $tmp;
	      }
	  }
      }
  }
  return @rcals;
}

sub get_private_mgroups {
  my ($who, $gfile, @gkeys, $tkey);
  $who = shift; $who = untaintname($who);
  $gfile="$::o{'spooldir'}/$who/mgroup";
  %::meetingGroups = ();
  if( -f $gfile) {
    &doReadFile("$gfile");
  }
  (@gkeys) = (sort keys %::meetingGroups);
  foreach $tkey (@gkeys) {
    $tkey =~ s/^mgp_//g;
  }
  return @gkeys;
}

sub get_global_mgroups {
  my ($gfile, $tkey, @ggkeys);
  $gfile="$::o{'spooldir'}/GlobalMeetingGroups";
  %::GlobalMeetingGroups = ();
  if( -f $gfile) {
      &doReadFile("$gfile");
  }
  (@ggkeys) = (sort keys %::GlobalMeetingGroups);
  foreach $tkey (@ggkeys) {
    $tkey =~ s/^mgp_//g;
  }
  return @ggkeys;
}

sub get_mgroups {
  my ($who, $gfile, @gkeys, $tkey, @ggkeys, $flag);
  $who = shift; $who = untaintname($who);
  $gfile="$::o{'spooldir'}/$who/mgroup";
  %::meetingGroups = ();
  if( -f $gfile) {
      &doReadFile("$gfile");
  }
  (@gkeys) = (keys %::meetingGroups);
  foreach $tkey (@gkeys) {
    $tkey =~ s/^mgp_//g;
  }
  $gfile="$::o{'spooldir'}/GlobalMeetingGroups";
  %::GlobalMeetingGroups = ();
  if( -f $gfile) {
      &doReadFile("$gfile");
  }
  (@ggkeys) = (keys %::GlobalMeetingGroups);
  foreach $tkey (@ggkeys) {
    $tkey =~ s/^mgp_//g;
    $tkey .= "($::phr{'global'})";
    push (@gkeys, $tkey);
  }
  return sort @gkeys;
}

sub ismember {
  my($usr, $list) = (@_);
  if(! $usr or ! $list) {return 0;}
  $list =~ s/[,; ]+/:/g;
  $list =~ s/:$//g; $list =~ s/\s//g;
  my(@rlist) = split(/:/, $list);
  my ($tmp,$i); $i = 1;
  foreach $tmp (@rlist) { if($usr eq $tmp) { return $i;}  $i++; }
  return 0;
}
sub isadmin {
    my ($user) = (@_);
    if($user ne "") { return ismember($user, $::o{'theAdministrator'}); }
    return 0;
}
sub iscreator {
    my ($user) = (@_);
    if($user ne "") { return ismember($user, $::o{'creator'}); }
    return 0;
}
sub iselement {
  my($elt, (@list)) = (@_);
  my ($tmp);
  foreach $tmp (@list) {
    if($elt eq $tmp) { return 1;}
  }
  return 0;
}

sub isre {
  my($usr, $cal, $kind) = (@_);
  if( $usr and $cal) {
   if($usr eq $cal) { return 1;}
    my $editors="";
    my $iname="$::o{'spooldir'}/$cal/info";
    my $fhdl = gensym;
    if(open($fhdl, "<$iname")) {
      &webcalLock::doflock(\*$fhdl, LOCK_SH, $iname) or calerror("Cannot lock file '$iname': $!\n",1);     
      if($kind eq 'any') {
	  while(<$fhdl>) {
	      if(/calinfo{\'(readers|editors)\'}\s*=\s*\'([^\']+)\'/) { $editors .= "$2,";}
	  }
      } else {
	  while(<$fhdl>) {
	      if(/calinfo{\'$kind\'}\s*=\s*\'([^\']+)\'/) {
		  $editors=$1; last;
	      }
	  }
      }
      &webcalLock::doflock(\*$fhdl, LOCK_UN, $iname) or calerror("Cannot unlock file '$iname': $!\n",1);     
      close $fhdl;
      return(ismember($usr, $editors));
    }
  }
  return 0;
}

sub select_option {
    my ($name,$value,@list,$v,$ret);

    ($name,$value,(@list)) = (@_);
    $ret = "<select name=\"$name\" class=\"fmList\">";

    while (defined($v = shift @list)) {
	$ret .= "<option";
	$ret .= " selected" if (defined $value && $v eq $value);
	$ret .= ">$v";
    }

    $ret .= "</select>";
    return $ret;
}

sub select_mgp {
    my ($name,$value,@list,$v,$ret, $tmp);
    ($name,$value,(@list)) = (@_);
    $ret = "<select name=\"$name\" class=\"fmList\">";

    while (defined($v = shift @list)) {
	$tmp=$v; $tmp=~ s/\(\)$//g;
	$ret .= "<option value=\"$v\"";
	$ret .= " selected" if (defined $value && $v eq $value);
	$ret .= ">$tmp";
    }
    $ret .= "</select>";
    return $ret;
}

sub select_optionX {
    my ($name,$value,@list,$v,$ret,$lab);
    ($name, $lab, $value,(@list)) = (@_);
    $ret = "<select name=\"$name\" class=\"fmList\"><option value=\"$value\">$lab";
    while (defined($v = shift @list)) {$ret .= "<option value=\"$v\">$v";}
    $ret .= "</select>";
    return $ret;
}

sub select_optionV {
    my ($name,$value,@list,$v,$ret, $code);

    ($name,$value,$code, (@list)) = (@_);
    $ret = "<select name=\"$name\" class=\"fmList\" $code>";

    while (defined($v = shift @list)) {
	$ret .= "<option value=\"$v\"";
	$ret .= " selected" if (defined $value && $v eq $value);
	$ret .= ">$v";
    }
    $ret .= "</select>";
    return $ret;
}

sub select_valueV {
    my ($name,$value,@list,$v,$t,$ret,$code);

    ($name,$value, $code, (@list)) = (@_); $code="" if not $code;
    $t = shift @list; $v = shift @list;  
    $ret = "<select name=\"$name\" class=\"fmList\" $code><option value=\"$v\">$t";
    while (defined($t = shift @list)) {
	$v = shift @list;
	$ret .= "<option";
	$ret .= " selected" if (defined $value && $v eq $value);
	$ret .= " value=\"$v\">$t";
    }
    $ret .= "</select>";
    return $ret;
}

sub select_value {
    my ($name,$value,@list,$v,$t,$ret);

    ($name,$value,(@list)) = (@_);
    $ret = "<select name=\"$name\" class=\"fmList\">";

    while (defined($v = shift @list) && defined($t = shift @list)) {
	$ret .= "<option";
	$ret .= " selected" if (defined $value && $v eq $value);
	$ret .= " value=\"$v\">$t";
    }

    $ret .= "</select>";
    return $ret;
}

sub select_hash {
    my ($name,$value,@list,$v,$t,$ret,$code, $href);
    ($name,$value, $code, $href) = (@_);
    @list = sort {uc($a) cmp uc($b)}  ( (keys %$href) );
    $t = shift @list; $v=$href->{$t};
    $ret = "<select name=\"$name\" class=\"fmList\" $code><option value=\"$v\">$t";
    while (defined($t = shift @list)) {
	$v = $href->{$t};
	$ret .= "<option";
	$ret .= " selected" if (defined $value && $v eq $value);
	$ret .= " value=\"$v\">$t";
    }
    $ret .= "</select>";
    return $ret;
}


sub select_multiple {
    my ($name,$maxsize,$vref,@list,$size,$v,$ret);

    ($name,$maxsize,$vref,(@list)) = (@_);
    $size = scalar @list;
    $size = 1 if ($size < 1);
    $size = $maxsize if ($size > $maxsize);
    $ret = "<select multiple size=$size name=\"$name\[]\" class=\"fmListN\">";

    foreach $v (@list) {
	$ret .= "<option selected>$v" if (defined $$vref{$v});
    }
    foreach $v (@list) {
	$ret .= "<option>$v" if (!defined $$vref{$v});
    }

    $ret .= "</select>";
    return $ret;
}


sub select_multicals {
    my ($name,$value,$ret1,$ret2,$tmp,@val,@cals,%cal, $tsiz);

    ($name,$value, $tsiz) = (@_); $tsiz=30 if not $tsiz;
    if (defined $value) {
	$value =~ s/[,; ]+/:/g;
	$value =~ s/:$//g;
    } else {
	$value = "";
    }

    if ($::o{'listAllCals'}) {
	my $wsize = $::o{'listAllCals'};
	if($wsize < 6) { $wsize = 6;}
	@val = split(/:/, $value);
	@cals = &listcals;
	foreach $tmp (@cals) {
	    $cal{$tmp} = undef;
	}
	foreach $tmp (@val) {
	    if (exists($cal{$tmp})) {
		$cal{$tmp} = 1;
		$tmp = "";
	    }
	}
	$value = join(':', @val);
	$value =~ s/[:]+/:/g; $value =~ s/^://;	$value =~ s/:$//;
	$ret2 = select_multiple($name,$wsize,\%cal,@cals);
    } else {
	$ret2 = "";
    }

    $ret1 = "<input type=text size=$tsiz maxlength=1024 name=\"$name\" value=\"$value\" class=\"fmEntry\">";

    return ($ret1,$ret2);
}

sub select_time {
    use integer;
    my ($name,$hr,$mn,$code) = (@_); if(not $hr) {$hr=0;} if(not $mn){$mn=0;} if(not $code) {$code="";}
    my ($i,$j,$ret); 

    $ret = "<select name=\"".$name."hour\" class=\"fmList\" $code>";
    if (not $::o{'hourformat'}) {
       for($i = 0; $i <= 12; $i++) {
	   if($hr == $i) { $ret .= "<option selected>$i";}
	   elsif ($hr == $i+12) { if($hr != 12){ $ret .= "<option selected>$i";} else { $ret .= "<option selected>12";}}
	   else { $ret .= "<option>$i";}
       }
    }
    else {
       for($i = 0; $i < 24; $i++) {
	   if($hr == $i) { $ret .= sprintf "<option selected>%02.2d",$i;}
	   else { $ret .= sprintf "<option>%02.2d",$i;}
       }
    }
    $ret .= "</select>";
    if ($mn >= 0) {
	$ret .= "<b>:</b>&nbsp;<select name=".$name."min class=\"fmList\" $code>";
	$mn = ($mn+1)/5 * 5;
	for($i=0; $i<60; $i+= 5){
	    if($i < 10) {$j="0$i";} else { $j=$i;}
	    if($i == $mn) { $ret .= "<option selected>$j";}
	    else {$ret .= "<option>$j";}
	}
	$ret .= "</select>";
    } else {
	$ret .= "<span class=\"fmLabel\"><b>:</b>&nbsp;00</span>";
    }
    if (not $::o{'hourformat'}) {
       my $ampm = $name."ampm";
       $ret .= "&nbsp;<select name=\"$ampm\" class=\"fmList\" $code>";
       if($hr < 12 or $hr == 24) {$ret .= "<option selected>am<option>pm</select>";}
       else { $ret .= "<option>am<option selected>pm</select>";}
    }
    return $ret;
}

sub input_radio {
    my ($name,$value,@list,$v,$t,$ret);

    ($name,$value,(@list)) = (@_);
    $ret = "";

    while (defined($v = shift @list) && defined($t = shift @list)) {
	$ret .= "<input type=radio name=\"$name\" class=\"fmRadio\" ";
	$ret .= " checked" if (defined $value && $v eq $value);
	$ret .= " value=\"$v\"><span class=\"fmLabel\"> $t</span> ";
    }

    return $ret;
}

#=====================================================================================================

sub calerror {
    my ($err, $nologin) = (@_);
    my $nn = $webcalConfig::r{'cookieAuth'};
    my $script = "";
    if( ! $::phr{'GoBack'}) { &loadLangfile;}
    &headers("WebCalendar $::phr{'Error'}"," ",undef,1);
    print "<center><br><h3 class=\"errorTitle\"><b>$::phr{'HasError'}</b></h3><br>";
    print "<table cellspacing=0 cellpadding=2 border=0 bgcolor=#009900><tr><td>";
    print   "<table width=460 bgcolor=#eeeeff border=0 cellpadding=12 cellspacing=0><tr><td>";
    print   "<font color=#ff0000 size=2><b><span class=\"errorMsg\">$err</span></b></font><br>";
    print   "</td></tr></table>";
    print "</td></tr></table>";
    if(! $nologin or $nologin > 0) {
        print "<br><form><table border=0><tr><td><input type=button value=\"$::phr{'GoBack'}\" onClick=\"history.go(-1)\" class=\"fmBtn\"></td></tr></table></form></br>";
    } else {
	my $back=""; 
	if($nologin > -9) { $back="<td><input type=button value=\"$::phr{'GoBack'}\" onClick=\"history.go(-1)\"  class=\"fmBtn\"></td>";}
        print "<form><table border=0><tr>$back<td>&nbsp;</td><td><input type=button value=\"$::phr{'Close'}\" onClick=\"self.close()\" class=\"fmBtn\"></td></tr></table></form></br>";
    }
    if($nn and ! $nologin) {
	# offer login as another user
	my $url = "$::o{'cginame'}?c=clogina$::vmg";
	print <<END;
	<form><table border=0><tr><td>
<font color="#ff0000">
<input type=button value="  $::phr{'newLogin'}  " onClick="openpopup('$url','signin',400,300)" class="fmBtn">
</font>
</td></tr></table></form>
END
    }
    print "</center>";
    &trailer(0,0);
    myexit(0) ;
}
#=====================================================================================================
sub setup {
     my ($do_not_exit) = (@_);
     my $isadm= isadmin($::d{'remote_user'}); my $isvgadm= $isadm || isvgadmin($::d{'remote_user'},$::d{'remote_user'});
     if($::o{'create'} == 0 and $isadm == 0 and $isvgadm==0 and iscreator($::d{'remote_user'})==0) {
	 if($do_not_exit) { return(0, $::phr{'creationDisabled'});}
	 calerror($::phr{'creationDisabled'});
	 exit 0;
     }
     my ($email, $who, $pswd, $rpswd, $calname, $errmsg, $url, $privacy, $username, $homepage, $name, $paswd, $salt,$dname);
     $email = $::calinfo{'email'}; if($email) { $email =~ s/\\|\'|\"|\`//g;} #"
     if(defined $::calinfo{'w'}) {$who = $::calinfo{'w'};} else {$who = "tmp";}
     $who =~ s/ //g;
     $::calinfo{'w'} = $username = untaintname($who,$::phr{'Invalidusername'});
     if(defined $::calinfo{'name'}){$name = $::calinfo{'name'};} else {$name="";}  $name =~ s/\\|\`//g; $name=~ s/\'/\\\'/g;
     if(defined $::calinfo{'dname'}){$dname = $::calinfo{'dname'};} else {$dname="";}  $dname =~ s/\\|\`//g; $dname=~ s/\'/\\\'/g;
     if(defined $::calinfo{'passwd'}) {$pswd = $::calinfo{'passwd'};} else {$pswd='_';};
     if(defined $::calinfo{'rpasswd'}) {$rpswd = $::calinfo{'rpasswd'};} else {$rpswd="";};
     if(defined $::calinfo{'homepage'}) {$homepage = $::calinfo{'homepage'};} else {$homepage="";} 
     $homepage =~ s/\\|\'|\"|\`//g; #"
     if(defined $::calinfo{'privacy'}) {$privacy = $::calinfo{'privacy'};} else {$privacy="";}
     $privacy = "" if $privacy eq 'ostxti';
     $calname="$::o{'spooldir'}/$username";

     $_=$email;
     if(! $who) {
	 if($do_not_exit) { return(0, $::phr{'HaveToSupplyCalendarName'});}
	 signup("$::phr{'HaveToSupplyCalendarName'}"); myexit(0);
     }
     if( not validname($who)) {
	 my $errmsg = "$::phr{'CannotCreateCalendar'}: $::phr{'Invalidusername'}";
	 if($do_not_exit) { return(0, $errmsg);} else { signup ($errmsg); myexit(0);}
     }
     if($who =~ /^mgp_/) {
	 my $errmsg = "$::phr{'CannotCreateCalendar'}: $::phr{'Invalidusername'}";
	 if($do_not_exit) { return(0, $errmsg);} else { signup ($errmsg); myexit(0);}
     }
     my $taken = 0; my $takenby="";
     my $DIR2= gensym;
     my @direntries=();
     if(opendir($DIR2, $::o{'spooldir'})) {
	 @direntries = readdir($DIR2); closedir($DIR2);
	 map { if("$_" eq "$username"){$taken=1;} } (@direntries);
     } else {
	 if($do_not_exit) { return(0, "Cannot examine '$::o{'spooldir'}' ($!)");}
	 calerror("Cannot examine '$::o{'spooldir'}' ($!)",1);     
     }
     if(!$taken) {
	 my $mname = "mgp_" . $username;
	 my ($n, $k);
	 for $n (@direntries) {
	     next if $n =~ /^\./;
	     if( -d "$::o{'spooldir'}/$n" and -f "$::o{'spooldir'}/$n/mgroup") {
		 %::meetingGroups = ();
		 doReadFile("$::o{'spooldir'}/$n/mgroup");
		 if( $::meetingGroups{$mname}) { $taken = 1; $takenby="$::phr{'Meeting_group'}" .":$n"; last;}
	     }
	 }
     }
     if(!$taken and -f "$::o{'spooldir'}/GlobalMeetingGroups") {
	 my $mname = "mgp_" . $username;
	 %::GlobalMeetingGroups = (); 
	 doReadFile("$::o{'spooldir'}/GlobalMeetingGroups");
	 if( $::GlobalMeetingGroups{$mname}) { $taken = 1; $takenby=$::phr{'Meeting_group'};}
     }

     if( $taken or -d $calname or $username =~ /nobody/i  or $username =~ /anonymous/i) {
	 if($do_not_exit) { return(0, "$::phr{'TheName'} \"$username\" $::phr{'HasBeenTaken'} ($takenby)");}
	 signup( "$::phr{'TheName'} \"$username\" $::phr{'HasBeenTaken'} ($takenby)"); myexit(0);
     } elsif(! $pswd or ($pswd ne $rpswd)) {
	 if($do_not_exit) { return(0, "$::phr{'PasswordMismatch'}, $::phr{'TryAgain'}");}
	 signup( "$::phr{'PasswordMismatch'}, $::phr{'TryAgain'}"); myexit(0);
     } elsif( ! $email or $email !~ /.+\@.+/) {
	 if($do_not_exit) { return(0, "$::phr{'EmailIncomplete'}, $::phr{'TryAgain'}");}
	 signup( "$::phr{'EmailIncomplete'}, $::phr{'TryAgain'}"); myexit(0);
     } 

     if(1) {
	 if(validname($who)) {
         my $cerror=0;
         if( ! -d "$::o{'spooldir'}") {
	     if(mkdir("$::o{'spooldir'}", 0711)) {
		 my $pswdf = "$::o{'spooldir'}/passwd";
		 my $htf = "$::o{'spooldir'}/.htaccess";
		 my $fhpf = gensym;
		 if(open($fhpf, ">$pswdf")) { print $fhpf "nobody:\n"; close $fhpf;} else { $cerror=1;}
		 my $fhht = gensym;
		 if(open($fhht, ">$htf")) {
		     print $fhht <<_END_;
AuthUserFile $::o{'spooldir'}/nothing
AuthGroupFile /dev/null
AuthName Restricted
AuthType Basic
<Limit GET POST PUT>
require valid-user
</Limit>
_END_
                    close $fhht;
		 } else { $cerror = 1;}
	     } else { $cerror = 1;}
	 }
	 my ($astatus, $amessage) = &webcalAuth::AuthenticateNewUser($username, $pswd);
	 if(! $astatus) {
	     $errmsg = "Auth Failed: $amessage";
	 } elsif($cerror or mkdir($calname, 0711) == 0) { 
	     $errmsg .= "Cannot create directory \"$calname\" ($!). <br> Please make sure your web server can write to \"$::o{'spooldir'}\"";}
       } else {
	 $errmsg = "$::phr{'CannotCreateCalendar'}: $::phr{'Invalidusername'}";
       }
       if($::calinfo{'ctype'} and $::calinfo{'ctype'} =~ "public" and
	  ismember($who, $::o{'corporate_calendar'})) { 
	   $errmsg = "Corporate Calendar \"$who\" must be a private calendar";
       };

       if (! $errmsg) {
	     my ($tmp);
	     #create two files: info and data
	     my $fhdl = gensym;
             if(sysopen($fhdl, "$calname/info", O_WRONLY | O_CREAT, 0644)) {
                 &webcalLock::doflock( \*$fhdl, LOCK_EX, "$calname/info") or calerror("Cannot lock file '$calname/info': $!\n",1);     
                 truncate($fhdl, 0);
		 print $fhdl "\$::calinfo{\'w\'}=\'$who\';\n";
		 print $fhdl "\$::calinfo{\'email\'}=\'$email\';\n";
		 print $fhdl "\$::calinfo{\'name\'}=\'$name\';\n";
		 print $fhdl "\$::calinfo{\'dname\'}=\'$dname\';\n"; print $fhdl "\$::calinfo{\'cfilter\'}=\'1\';\n";
		 if(defined $::calinfo{'ctype'}) {$tmp = $::calinfo{'ctype'};} else {$tmp="";}
                 if($tmp =~ "public") {$privacy = 'public';}
		 print $fhdl "\$::calinfo{\'privacy\'}=\'$privacy\';\n";
		 if($tmp) { print $fhdl "\$::calinfo{\'ctype\'}=\'$tmp\';\n";}
		 if($::calinfo{'resrc'}) { print $fhdl "\$::calinfo{\'resrc\'}=\'1\';\n";}
		 if($::calinfo{'aap'}) { print $fhdl "\$::calinfo{\'aap\'}=\'1\';\n";}
		 else { print $fhdl "\$::calinfo{\'aap\'}=\'0\';\n";}
		 if($homepage) { print $fhdl "\$::calinfo{\'homepage\'}=\'$homepage\';\n"; }
		 if($::calinfo{'cpyhdrftr'}) {
		     my $hdr = getinfo($::d{'remote_user'},'hdr'); my $ftr = getinfo($::d{'remote_user'},'ftr');
		     if($hdr) {$hdr =~ s/\\//g; $hdr =~ s/\'/\\\'/g; print $fhdl "\$::calinfo{\'hdr\'}=\'$hdr\';\n";}
		     if($ftr) {$ftr =~ s/\\//g; $ftr =~ s/\'/\\\'/g; print $fhdl "\$::calinfo{\'ftr\'}=\'$ftr\';\n";}
		 }
		 print $fhdl "\n1;\n";
                 &webcalLock::doflock( \*$fhdl, LOCK_UN, "$calname/info") or calerror("Cannot unlock file '$calname/info': $!\n",1); 
		 close $fhdl;
	     } else { $errmsg = "$::phr{'CannotWriteInfoFile'}";}
	     my $fhdld = gensym;	     
             if(sysopen($fhdld, "$calname/data", O_WRONLY | O_CREAT, 0644)) {
                 &webcalLock::doflock( \*$fhdld, LOCK_EX,"$calname/data") or calerror("Cannot lock file '$calname/data': $!\n",1);
#===============================
		 # import all events form corporate calendars,
		 {
		     my (@ccals, $cal, $file, $counter, $href);
		     truncate($fhdld, 0);
		     print $fhdld "\@::caldata = (\n";
		     @ccals = split(/[:;, ]+/, $::o{'corporate_calendar'});
		     $counter=1;
		     foreach $cal (@ccals) {
			 next if $cal eq $who;
			 $file= "$::o{'spooldir'}/$cal/data";
			 if( -f $file) {
			     @::caldata=(); doReadFile($file);
			     foreach $href (@::caldata) {
				 $href->{'key'} = $counter; $counter++;
				 my $tmp=print1Entry($href); print $fhdld $tmp;
			     }
			 }
		     }
		     $counter++;
		     print $fhdld "\n);\n$counter;\n";
		 }
		 #
#===============================
                 &webcalLock::doflock( \*$fhdld, LOCK_UN, "$calname/data") or calerror("Cannot unlock file '$calname/data': $!\n",1);
		 close $fhdld;
	     } else { $errmsg .= "$::phr{'CannotWriteDataFile'}";}
	     if(! $errmsg) {	#create password file
		 my ($astatus, $amessage) = &webcalAuth::AddPasswordEntry($who, $pswd);
		 if(! $astatus ){ 
		     $errmsg .= "$amessage";
		     if( -d "$calname") {
			 if( $ =~ m/MSWin|NT/i ) {	  deltree($calname);  }
			 else {
			     my @args = ('/bin/rm', '-r', $calname);
			     system(@args) == 0  or $errmsg .= "$::phr{'OpenFailed'} ($calname)<br>";
			 }
		     }
		 }
	     }
	 }
	 if( $errmsg) {
	     if($do_not_exit) { return(0, $errmsg);}	     
	     signup ($errmsg); myexit(0);
	 }
     }
     if($::calinfo{'ctype'} and $::calinfo{'ctype'} eq 'public_m'){ rebuildModeratedCalendarTable($who, 'public_m');}
     my $tmp; if($webcalConfig::r{'cookieAuth'} ==0){$tmp="?w=$who";} else {$tmp="";}
     my $return_msg = "";
     if($do_not_exit) {
	 $return_msg = <<END;
Caneldar "$who" has been created.
           Please use the URI:
             $::o{'fcginame'}?w=$who
           to access your new calendar.
END
    ;
     } else {
	 &headers("WebCalendar Greetings",undef,undef,1);
	 print "<center>
 <br><br><font size=+2><b>$::phr{'Congratulations'}!</b></font><br><br>
$::phr{'SetupGreetingA'}
<br><br><b><a href=\"$::o{'cginame'}?w=$who\"><font color=#0000cc>$::o{'fcginame'}$tmp</a></font></b><br><br>
$::phr{'SetupGreetingB'}.
<br><br><br>
<font color=#ff0000>$::phr{'SetupGreetingC'}</font>
<br><br>
<b><a href=\"$::o{'cginame'}?w=$who&c=option\"><font color=#0000cc>$::phr{'CalendarOptions'}</font></a></b><br>
</center>";
     }
     
     my $msgbody = "
        $::phr{'Congratulations'} $name !

$::phr{'SetupGreetingA'}

   $::o{'fcginame'}?w=$who

$::phr{'SetupGreetingB'}.

================== $::phr{'MiscInfo'} =============================
       $::phr{'CalendarName'}:      $username
       $::phr{'DescriptiveName'}:   $dname
       $::phr{'Password'}:          $rpswd
       $::phr{'OwnerEmailAddress'}: $email
       $::phr{'OwnerName'}:         $name
       $::phr{'OwnerHomepage'}:     $homepage
====================================================================

If the calendar server resides in different timezone from yours, 
you need to set your time zone in the calendar option page.
Otherwise, your visual or email reminders will not come in time.

";
     $msgbody =~ s/\r?\n/\015\012/g;

     # send registration info to user
     if($webcalConfig::r{'sendmail'}) {
         if( $ !~ m/MSWin|NT/i ) {
             my $SENDMAIL= $webcalConfig::r{'sendmail'};
             open (MAIL,"|-") || exec($SENDMAIL, "-t", "-oi");
	     my $now_string = &rfc2822_datetime; $email =~ s/\r?\n//g;
             print MAIL "To: $email\015\012";
	     print MAIL "From: $name <$email>\015\012";
	     print MAIL "Subject: $::phr{'WelcomeToWebCalendar'}\015\012";
	     print MAIL "Date: $now_string\015\012";
	     print MAIL "X-Mailer: webCalendar $webCalVersion $patchlevel\015\012";
	     print MAIL "\015\012";
	     print MAIL "$msgbody\015\012";
             close MAIL;
	     if($webcalConfig::r{'operator'}) {
		 my $operator = $webcalConfig::r{'operator'};
		 open (MAIL,"|-") || exec($SENDMAIL, "-t", "-oi");
		 print MAIL "To: $operator\015\012";
		 print MAIL "From: $name <$email>\015\012";
		 print MAIL "Subject: New WebCalendar\015\012";
		 print MAIL "Date: $now_string\015\012";
		 print MAIL "X-Mailer: webCalendar $webCalVersion $patchlevel\015\012";
		 print MAIL "\015\012";
		 print MAIL "User:  $username\015\012";
		 print MAIL "Email: $email\015\012";
		 print MAIL "Name:  $name\015\012";
		 close MAIL;
	     }
         }
     } else { # check for smtp server
         if($webcalConfig::r{'smtpto'} and $webcalConfig::r{'smtpfrom'}) {
             my $fromsmtp = $webcalConfig::r{'smtpfrom'};
             my $tosmtp = $webcalConfig::r{'smtpto'};
             my ($status, $error) = &smtplib::SmtpSendMail( $email, $fromsmtp, $email, $tosmtp, $::phr{'WelcomeToWebCalendar'}, $msgbody);
	     if($webcalConfig::r{'operator'}) {
		 my $operator = $webcalConfig::r{'operator'};
 		 my $msg = "User:  $username\nEmail: $email\nName:  $name";
		 &smtplib::SmtpSendMail($email, $fromsmtp, $operator, $tosmtp,"New Webcalendar", $msg);
	     }
         } 
     }
     if($::o{'vgroup'} and $::calinfo{'vgp'} and $::calinfo{'vgp'}  ne "??????") {
	 my $content="\$::calinfo{\'vgroup\'}=\"" . $::calinfo{'vgp'} ."\";\n1;";
	 my $file="$calname/vgroup"; write_file($file, $content);
	 addusertovgroup($username, $::calinfo{'vgp'});
     }
     if($do_not_exit) { &update_name_list($username, $name, $dname,'a'); return(1, $return_msg); }
     &update_name_list($username, $name, $dname,'a'); &trailer(0,0);
     myexit(0);
}
#=====================================================================================================
sub update_name_list {
    my ($cal, $name, $dname, $cmd) = (@_); $name="" if not $name; $dname="" if not $dname;
    my $file = "$::o{'spooldir'}/.namelist";
    my $content = "";
    my ($u, $line, $nn,$dd,$tmp); 
    if( ! -f $file) {
	my $DIRL= gensym;
	if (opendir($DIRL, $::o{'spooldir'})) {
	    my @entries = readdir($DIRL); closedir($DIRL);
	    for $u (@entries) {
		next if $u =~ /^\./;
		next if ! -f "$::o{'spooldir'}/$u/info";
		($nn, $dd) = getinfolist($u, 'name', 'dname');
		if($nn){$nn =~ s/^\s+|\s+$//g;} if($dd){$dd =~ s/^\s+|\s+$//g;} $nn= " " if not $nn; $dd = " " if not $dd;
		$tmp = "$u" . ':::' . $nn . ':::' . $dd . "\n";
		$content .= $tmp;
	    }
	    write_file($file, $content);	    
	}
    } elsif($cal) {
        my $fhhh = gensym;
	my $old = read_file_content("$file");
        if(1) {
            my @old = split(/\n/, $old);
            my $dirty = 1;
            $cal =~ s/^\s+|\s+$//g; $name =~ s/^\s+|\s+$//g; $dname =~ s/^\s+|\s+$//g;
            for $line (@old) {
                ($u,$nn,$dd) = split(/:::/, $line);
                if($u eq $cal) {
                    if($cmd eq 'u') {
                        $nn="" if not $nn; $dd="" if not $dd; $nn =~ s/^\s+|\s+$//g; $dd =~ s/^\s+|\s+$//g;
                        if($nn ne $name or $dd ne $dname) {
                            $name=" " if not $name; $dname=" " if not $dname;
                            $content .= "${u}:::${name}:::$dname\n";
                        } else { $dirty = 0;}
                    }
                } else { $content .= "$line\n";}
            }
            if($cmd eq 'a') { $name=" " if not $name; $dname=" " if not $dname; $content .= "${cal}:::${name}:::$dname\n";}
            if($dirty) {  write_file($file, $content);  }
        }
    }
}

sub get_name_list {
    my $file = "$::o{'spooldir'}/.namelist";    
    if(! -f $file) {update_name_list("","","","");}
    my %hash = ();
    my $all = read_file_content($file);
    my @all = split(/\n/, $all);
    my ($u, $n, $dn, $line, $des);
    for $line (@all) {
	($u,$n,$dn) = split(/:::/, $line);
	if($u) { if($dn !~ /^\s+$/){$des=$dn;}elsif($n !~ /^\s+$/){$des=$n;}else{$des=$u;} $hash{$u} = $des;}
    }
    return \%hash;
}
	
#=====================================================================================================
# code1: status of modifying attendee's calendar.   0 -- normal,  nozero -- fatal. 
#  msg1: error message when code1 != 0
# 
# code0: status of updating calendar data
#        1 -- fatal, permission problem.
#       all other codes are normal
#       10 --  returned from check checkOverlap.
#       20 --  general normal return from doinsert
#       1000 -- return from doinsert. Post the event editor again
#
#
sub handle_acknowledgement {
    my ($code0, $msg0, $code1, $msg1) = (@_);

    if($::calinfo{'donotacknowledge'}) { return;}

    # error
    if($code0 == 1) { # Fatal error: Permission problem
	calerror( $msg0);
    } 
    if($code1 > 0)  { # Fatal error: failed to modify attendee's calendar. Lock problem.
	calerror( $msg1);
    }  
    # normal situation 
    if($code0 == 1000) { # The "Next New" button was pressed. Insertion was succesful. Post the Event editor Again
	my $username = $::calinfo{'w'}; 
	my $calendarname="$::o{'spooldir'}/$username";
	doReadFile("$calendarname/info");
	if(defined $::calinfo{'mattendants'}) {$::calinfo{'imatt'} = $::calinfo{'mattendants'};}
	if(defined $::calinfo{'smtgp'} and $::calinfo{'smtgp'} ne "$::phr{'none'}"){$::calinfo{'mg'} = $::calinfo{'smtgp'};}
	delete $::calinfo{'detail'}; $::calinfo{'nextnew'}=1;
	$::calinfo{'lrem'} = $::calinfo{'_savedreminder_'};
	doReadFile("$calendarname/data");
	if( ! $::calinfo{'aq'}) { # not from quick add
	    &edit('nevent');
	} else {
	    &quickadd();
	}    
        myexit(0);
    } elsif($code0 == 10) { # overlapping event detected
	&headers($::phr{'CompareCalendars'},undef,undef,1,1);
	print $msg0;
	&trailer(0,0);
	myexit(0);
    }  elsif($code0 == 20) { # normal return from doinsert
	my $hrefresh = $::calinfo{'_header_refresh_code_'};
	&headers($::phr{'Acknowledgement'},undef,$hrefresh);	
	print $msg0;
	&trailer(0,0);
	myexit(0);	
    }
}
#=====================================================================================================
sub doedit {
    my $action = $::calinfo{'action'};
    my $who = $::calinfo{'w'}; $who = untaintname($who);
    my $calname = "$::o{'spooldir'}/$who";
    my ($ir0, $sr0, $ir1, $sr1, $toall);
    my ($DFILE, $dfname);
    my $fhdl = gensym;

    $::lastNewEvent={};
    $::lastOldEvent={};
    $::calinfo{'_header_refresh_code_'} = "";

    $toall = ismember($who, $::o{'corporate_calendar'});
    #opera hack
    if($::calinfo{'hidden_occurs'}) { $::calinfo{'occurs'} = $::calinfo{'hidden_occurs'};}
    if(not $::calinfo{'occurs'} or $::calinfo{'occurs'} eq 'Custom') { $::calinfo{'occurs'} = 'OneTime';}

    if($::calinfo{'fromqadd'}) { # apply default color or css.  11/18/2002
	if($::calinfo{'k'} == 1) { 
	    $::calinfo{'fgclr'} = $::calinfo{'dafg'} if $::calinfo{'dafg'};
	    $::calinfo{'bgclr'} = $::calinfo{'dabg'} if $::calinfo{'dabg'};
	    $::calinfo{'css'} = $::calinfo{'css1'} if $::calinfo{'css1'};
	} elsif($::calinfo{'k'} == 2) { 
	    $::calinfo{'fgclr'} = $::calinfo{'dtfg'} if $::calinfo{'dtfg'};
	    $::calinfo{'bgclr'} = $::calinfo{'dtbg'} if $::calinfo{'dtbg'};
	    $::calinfo{'css'} = $::calinfo{'css2'} if $::calinfo{'css2'};
	} elsif($::calinfo{'k'} == 3) { 
	    $::calinfo{'fgclr'} = $::calinfo{'dmfg'} if $::calinfo{'dmfg'};
	    $::calinfo{'bgclr'} = $::calinfo{'dmbg'} if $::calinfo{'dmbg'};
	    $::calinfo{'css'} = $::calinfo{'css3'} if $::calinfo{'css3'};
	} else {
	    $::calinfo{'fgclr'} = $::calinfo{'dsfg'} if $::calinfo{'dsfg'};
	    $::calinfo{'bgclr'} = $::calinfo{'dsbg'} if $::calinfo{'dsbg'};
	    $::calinfo{'css'} = $::calinfo{'css4'} if $::calinfo{'css4'};
	}
    }

    if((!$::calinfo{'repeat'} or $::calinfo{'repeat'}==1)) {
	if($::calinfo{'rforever'}) { $::calinfo{'repeat'} = 730;}
	elsif($::calinfo{'enddate'}) {
	    my (%href); $href{'date'} = $::calinfo{'sdate'}; $href{'occurs'}=$::calinfo{'occurs'};
	    my $newrepeat = &newrepeat(\%href, $::calinfo{'enddate'});
	    $::calinfo{'repeat'} = $newrepeat; if($newrepeat < 2) { delete $::calinfo{'enddate'};}	    
            $::calinfo{'orepeat'} =$newrepeat;
	}
    } # else { delete $::calinfo{'enddate'};}

    $dfname = "$calname/data";
    if($action eq "$::phr{'Insert'}") {
	&remove_xtra();
	if(sysopen($fhdl, "$dfname", O_WRONLY | O_CREAT, 0644)) {
	    &webcalLock::doflock( \*$fhdl, LOCK_EX, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);     
	    do "$dfname";
	    $DFILE=\*$fhdl;
	    ($ir0, $sr0, $ir1, $sr1) = &doinsert("",0, $DFILE);
	    &webcalLock::doflock( \*$fhdl, LOCK_UN, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);     	    
	    close $fhdl;
	    if($toall and $ir1 <=0 and ($ir0 == 20 || $ir0 ==1000)) {my @ary=($::lastNewEvent); insert_to_all(\@ary, $who);}
	    &handle_acknowledgement($ir0, $sr0, $ir1, $sr1);
	} else {calerror("$::phr{'OpenFailed'}: $dfname",1);}
    }
    elsif($action eq "$::phr{'NextNew'}") {
	&remove_xtra();
	if(sysopen($fhdl, "$dfname", O_WRONLY | O_CREAT, 0644)) {
            my $ww = $who;
	    &webcalLock::doflock( \*$fhdl, LOCK_EX, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);     
	    do "$dfname";
	    $DFILE=\*$fhdl;
	    ($ir0, $sr0, $ir1, $sr1) = &doinsert("",1, $DFILE);
	    &webcalLock::doflock( \*$fhdl, LOCK_UN, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);     	    
	    close $fhdl;
	    if($toall and not $ir1 and ($ir0 == 20 || $ir0 ==1000)) {my @ary=($::lastNewEvent); insert_to_all(\@ary, $who);}
            $::calinfo{'w'} = $ww;
	    &handle_acknowledgement($ir0, $sr0, $ir1, $sr1);
	} else {calerror("$::phr{'OpenFailed'}: $dfname",1);}
    }
    elsif ($action eq "$::phr{'InsertAsNew'}") {
	&remove_xtra();
	$::calinfo{'author'} = ""; 
	if(sysopen($fhdl, "$dfname", O_WRONLY | O_CREAT, 0644)) {
	    &webcalLock::doflock( \*$fhdl, LOCK_EX, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);     
	    do "$dfname";
	    $DFILE=\*$fhdl;
	    delete $::calinfo{'seq'} if defined $::calinfo{'seq'};
	    ($ir0, $sr0, $ir1, $sr1) = &doinsert("",0, $DFILE);
	    &webcalLock::doflock( \*$fhdl, LOCK_UN, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);     	    
	    close $fhdl;
	    if($toall and $ir1 <=0 and ($ir0 == 20 || $ir0 ==1000)) {my @ary=($::lastNewEvent); insert_to_all(\@ary, $who);}
	    &handle_acknowledgement($ir0, $sr0, $ir1, $sr1);
	} else {calerror("$::phr{'OpenFailed'}: $dfname",1);}
    }
    elsif($action eq "$::phr{'Modify'}") { 
	if(sysopen($fhdl, "$dfname", O_WRONLY | O_CREAT, 0644)) {
	    &webcalLock::doflock( \*$fhdl, LOCK_EX, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);     
	    do "$dfname";
	    $DFILE=\*$fhdl;
	    ($ir0, $sr0, $ir1, $sr1) = &domodify($DFILE);
	    &webcalLock::doflock( \*$fhdl, LOCK_UN, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);     	    
	    close $fhdl;
	    if($toall and $ir1 <=0 and $ir0 == 20) {modify_all($who, 'modify');}
	    if($toall) {modify_all($who, 'modify');}
	    &handle_acknowledgement($ir0, $sr0, $ir1, $sr1);
	} else {calerror("$::phr{'OpenFailed'}: $dfname",1);}
    }
    elsif($action eq "$::phr{'Delete'}") {
	if(sysopen($fhdl, "$dfname", O_WRONLY | O_CREAT, 0644)) {
	    &webcalLock::doflock( \*$fhdl, LOCK_EX, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);     
	    do "$dfname";
	    $DFILE=\*$fhdl;
	    ($ir0, $sr0, $ir1, $sr1) = &deleteAll($DFILE);
	    &webcalLock::doflock( \*$fhdl, LOCK_UN, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);     	    
	    close $fhdl;
	    if($toall and $ir1 <=0 and $ir0 == 20) {modify_all($who, 'deleteAll');}
	    &handle_acknowledgement($ir0, $sr0, $ir1, $sr1);
	} else {calerror("$::phr{'OpenFailed'}: $dfname",1);}
    }
    elsif($action eq "$::phr{'DeleteThisOne'}") {
	if(sysopen($fhdl, "$dfname", O_WRONLY | O_CREAT, 0644)) {
	    &webcalLock::doflock( \*$fhdl, LOCK_EX, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);
	    do "$dfname";
	    $DFILE=\*$fhdl;
	    ($ir0, $sr0, $ir1, $sr1) = &deleteOne($DFILE);
	    &webcalLock::doflock( \*$fhdl, LOCK_UN, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);
	    close $fhdl;
	    if($toall and $ir1 <=0 and $ir0 == 20) {modify_all($who, 'deleteOne');}
	    &handle_acknowledgement($ir0, $sr0, $ir1, $sr1);
	} else {calerror("$::phr{'OpenFailed'}: $dfname",1);}
    }
    elsif($action eq "$::phr{'DeleteAll'}") {
	if(sysopen($fhdl, "$dfname", O_WRONLY | O_CREAT, 0644)) {
	    &webcalLock::doflock( \*$fhdl, LOCK_EX, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);
	    do "$dfname";
	    $DFILE=\*$fhdl;
	    ($ir0, $sr0, $ir1, $sr1) = &deleteAll($DFILE);
	    &webcalLock::doflock( \*$fhdl, LOCK_UN, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);
	    close $fhdl;
	    if($toall and $ir1 <=0 and $ir0 == 20) {modify_all($who, 'deleteAll');}
	    &handle_acknowledgement($ir0, $sr0, $ir1, $sr1);
	} else {calerror("$::phr{'OpenFailed'}: $dfname",1);}
    }
    elsif($action eq "$::phr{'DeleteForward'}") {
	if(sysopen($fhdl, "$dfname", O_WRONLY | O_CREAT, 0644)) {
	    &webcalLock::doflock( \*$fhdl, LOCK_EX, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);
	    do "$dfname";
	    $DFILE=\*$fhdl;
	    ($ir0, $sr0, $ir1, $sr1) = &deleteForward($DFILE);
	    &webcalLock::doflock( \*$fhdl, LOCK_UN, "$dfname") or calerror("Cannot lock file '$dfname': $!\n",1);
	    close $fhdl;
	    if($toall and $ir1 <=0 and $ir0 == 20) {modify_all($who, 'deleteForward');}
	    &handle_acknowledgement($ir0, $sr0, $ir1, $sr1);
	} else {calerror("$::phr{'OpenFailed'}: $dfname",1);}
    } else { # no data updating 
        doReadFile("$calname/data");
        if ($action eq "$::phr{'FindConflict'}") { &findConflict("");}
        elsif ($action eq "$::phr{'ShowCombinedCalendar'}") {
	    &docompare("e");
	} else {
            if(defined $::calinfo{'mg'} and $::calinfo{'mg'}) {
                my $tmp = $::calinfo{'mg'};
                $::calinfo{'mattendants'} = $tmp;
		if($::calinfo{'sk'}) { &tasks;}
                else { &docompare('0');}
            } else {
		if($::calinfo{'sk'}) { &tasks;}
		else { &calendar; }
	    } # caldata is uptodate here
        }
    }
    if($::calinfo{'donotacknowledge'}) {return($ir0, $sr0, $ir1, $sr1);}
    myexit(0);
}
#=====================================================================================================
sub remove_xtra { my($i, $tmp); for $i (0..5) {$tmp="X$i"; delete $::calinfo{$tmp};}}
#=====================================================================================================
sub getEditorState {
  my ($stmp, $utmp, $vtmp,$rem,$imatten, $imgp, $author, $etmp, $rurl, $extra, $tmp, $privacy,$occurs,$ret);
  my ($repeat, $description,$fg,$bg,$clr, $detail, $iroom, $invitee);
  $ret=""; $invitee="";
  if(exists $::calinfo{'mattendants'} or exists $::calinfo{'smtgp'} ) {
      if(defined $::calinfo{'smtgp'}){ $imgp = $::calinfo{'smtgp'}; if($imgp ne $::phr{'none'}) {$tmp=urlencode($imgp); $invitee .= "&imgp=$tmp";} }
      if(defined $::calinfo{'mattendants'}) {
	  $imatten = $::calinfo{'mattendants'}; 
	  $imatten =~ s/ +/,/g;
	  $imatten =~ s/,+/,/g;
          $tmp=urlencode($imatten);
	  $invitee .= "&imatt=$tmp";
      }
    if(defined $::calinfo{'sroom'}){
	my $tmp = $::calinfo{'sroom'}; $tmp =~ s/\\//g; $tmp=~ s/\'//g; $tmp=urlencode($tmp); $ret .= "&iroom=$tmp";
    } 
    if(defined $::calinfo{'spkr'}){
	my $tmp = $::calinfo{'spkr'}; $tmp =~ s/\\//g; $tmp=~ s/\'//g;  $tmp=urlencode($tmp);$ret .= "&ispkr=$tmp";
    } 
    if(defined $::calinfo{'cat'}){
	my $tmp = $::calinfo{'cat'}; $tmp =~ s/\\//g; $tmp=~ s/\'//g; $tmp=urlencode($tmp);$ret .= "&icat=$tmp";
    } 
    if(defined $::calinfo{'kwd'}){
	my $tmp = $::calinfo{'kwd'}; $tmp =~ s/\\//g; $tmp=~ s/\'//g; $tmp=urlencode($tmp);$ret .= "&ikwd=$tmp";
    } 
    if(defined $::calinfo{'ctp'}){ 
	my $tmp = $::calinfo{'ctp'}; $tmp =~ s/\\//g; $tmp=~ s/\'//g; $tmp=urlencode($tmp);$ret .= "&ictp=$tmp";
    } 
    if(defined $::calinfo{'ctm'}){
	my $tmp = $::calinfo{'ctm'}; $tmp =~ s/\\//g; $tmp=~ s/\'//g; $tmp=urlencode($tmp);$ret .= "&ictm=$tmp";
    } 
    if(defined $::calinfo{'cp'}){
	my $tmp = $::calinfo{'cp'}; $tmp =~ s/\\//g; $tmp=~ s/\'//g; $tmp=urlencode($tmp);$ret .= "&icp=$tmp";
    } 
    if(defined $::calinfo{'r1'} and $::calinfo{'r1'}){$ret .= "&ir1=1";} 
    if(defined $::calinfo{'acc'}){ 
	my $tmp = $::calinfo{'acc'}; $tmp =~ s/\\//g;  $tmp=~ s/\'//g; $tmp=urlencode($tmp);$ret .= "&iacc=$tmp";
    } 
    if(defined $::calinfo{'dec'}){
	my $tmp = $::calinfo{'dec'}; $tmp =~ s/\\//g; $tmp=~ s/\'//g; $tmp=urlencode($tmp);$ret .= "&idec=$tmp";
    } 
    
    if(defined $::calinfo{'rsvp'}){ my $tmp = $::calinfo{'rsvp'};$ret .= "&irsvp=$tmp";} 
    if(defined $::calinfo{'mme'}) { my $tmp = $::calinfo{'mme'};$ret .= "&imme=$tmp";} 
    if(defined $::calinfo{'eme'}) { my $tmp = $::calinfo{'eme'};$ret .= "&ieme=$tmp";} 

  # current reminder setting
    if(defined $::calinfo{'rflash'}) {
      $stmp = $::calinfo{'rflash'};
      $utmp = $::calinfo{'rflashu'};
      $vtmp = $::calinfo{'rflashv'};
      $rem = "rf:$stmp:$vtmp:$utmp,rm:";
      $stmp = $::calinfo{'rmail'};
      $utmp = $::calinfo{'rmailu'};
      $vtmp = $::calinfo{'rmailv'};
      $rem .= "$stmp:$vtmp:$utmp,rp:";
      $stmp = $::calinfo{'rpopup'};
      $utmp = $::calinfo{'rpopupu'};
      $vtmp = $::calinfo{'rpopupv'};
      $rem .= "$stmp:$vtmp:$utmp,rc:";
      $stmp = $::calinfo{'rchime'};
      $utmp = $::calinfo{'rchimeu'};
      $vtmp = $::calinfo{'rchimev'};
      $rem .= "$stmp:$vtmp:$utmp";
      $ret .="&imrem=$rem";
    } 
    if(defined $::calinfo{'author'}) { $author=$::calinfo{'author'};   $author =~ s/ +/:/g; $tmp=urlencode($author); $ret .= "&author=$tmp";}
    if(defined $::calinfo{'rurl'}) { $rurl = $::calinfo{'rurl'}; $tmp=urlencode($rurl);$ret .= "&rurl=$tmp";}
    if(defined $::calinfo{'eprivacy'}) { $privacy=$::calinfo{'eprivacy'}; $ret .= "&eprivacy=$privacy";} 
    if(defined $::calinfo{'occurs'}) { $occurs=$::calinfo{'occurs'}; $ret .= "&occurs=$occurs";}
    if(defined $::calinfo{'repeat'}) { $repeat=$::calinfo{'repeat'}; $ret .= "&repeat=$repeat";} 
    if(defined $::calinfo{'fgclr'}) { $fg = $::calinfo{'fgclr'}; $fg=~ s/\s|\\|\'|\"|\`//g;} else {$fg = "";} #"
    if(defined $::calinfo{'bgclr'}) { $bg = $::calinfo{'bgclr'}; $bg=~ s/\s|\\|\'|\"|\`//g;} else { $bg="";} #"
    if($fg ne "" or $bg ne "") { $ret .= "&fgclr=$fg&bgclr=$bg";} 
    if(defined $::calinfo{'cs'}) { $fg =$::calinfo{'cs'}; $ret .= "&cs=$fg";}

    if(defined $::calinfo{'description'}) { $description=$::calinfo{'description'};} else {$description="";}
    $description =~ s/\\//g; $description =~ s/\'/\\\'/g; 
    $description =~ s/\n/\|/g;
    $description =~ s/ +/_/g;
    if($description) { $tmp=urlencode($description); $ret .= "&desc=$tmp";}
    if(defined $::calinfo{'detail'}) {$detail=$::calinfo{'detail'};} else {$detail="";}
    if($detail ne "") {
      $detail =~ s/\\//g; $detail =~ s/\'/\\\'/g; 
      $detail =~ s/\n/\|/g;
      $detail =~ s/ +/_/g;
    }
    if($detail ne "") { $tmp=urlencode($detail);  $ret .= "&detail=$tmp";}
  }
  $ret =~ s/^&//;
  return ($ret, $invitee);
}
#=====================================================================================================
sub calmatch {			#match calendar event with date
  use integer;
  my ( $i, $tm, $td, $ty, $dm, $dd, $dy, $nth, $elength, $tmp,
       $smp, $ump, $twday, $wday, $occ, $modulo, $wdaymask);
  my ($today, $date, $occurs, $repeat, $exception, $kind) = (@_);

  ($occ, $modulo, $wdaymask) =(1,0,0);
  if($occurs) {
      if( substr($occurs,0,1) eq 'Z' and $occurs =~ /^Z(.+),(\d+),(\d*)/) {
	  my ($word, $c1, $c2) = ($1, $2, $3);
	  return calmatch16($today, $date, $repeat, $exception, $kind, $word, $c1, $c2);
      } else {
	  my $oaref = $::occurenceHash{$occurs};
	  if($oaref) {
	      $occ = $oaref->[0];   $modulo = $oaref->[1];  $wdaymask = $oaref->[2];
	  } 
      }
  }
  
  if($occ <= 1) {                # shortcut for most common case
      return 1 if ($today eq $date) ;
      return 0;
  }
  
  if(defined $exception) { $elength = 0+@{$exception}; } else {$elength = -1;}

  if($today eq $date) {			# today is the day, check for exceptions
    my $eoffset=1;      
    if($wdaymask) {			# not on all weekdays
      ($tm, $td, $ty)=split(/\//, $today);
      $twday = wday($tm-1, $td, $ty);	# weekday for today
      return 0 if (((1 << $twday) & $wdaymask) == 0);
      my $aryref = $::occurenceHash{$occurs};
      if($aryref) {$eoffset = $aryref->[3+$twday];}
    }
    if($elength > 0) {
      for ($i=0; $i <$elength; $i++) {
	  if( abs($exception->[$i]) == $eoffset) {
	    if($kind != 2 or $exception->[$i] > 0) { return 0; }
	}
      }
    }
    return 1;
   } elsif ($repeat and $repeat > 0) {
    ($tm, $td, $ty)=split(/\//, $today);
    ($dm, $dd, $dy)=split(/\//, $date);
    if($dy > $ty or ( $dy == $ty and ($dm > $tm or ($dm == $tm and $dd > $td)))) { return 0; }
    $tm--; $dm--;

    if($modulo) {			# repeats at integral number of days
      $nth = ndays($tm, $td, $ty, $dm, $dd, $dy)-1;
      if(($nth % $modulo) != 0) { return 0;}
      $nth =($nth+$modulo)/$modulo; if( $nth > $repeat) { return 0; }

      if($elength > 0) {
	for ($i=0; $i <$elength; $i++) {
	  if( abs($exception->[$i]) == $nth) {
	      if($kind != 2 or $exception->[$i] > 0) { return 0; } 
	  }
	}
      }
      return $nth;
    }

    if($wdaymask) {			# not on all weekdays
      $twday = wday($tm, $td, $ty);	# weekday for today
      return 0 if (((1 << $twday) & $wdaymask) == 0);
      $wday = wday($dm, $dd, $dy);	# weekday of event
      $nth = ndays($tm, $td, $ty, $dm, $dd, $dy);
      my $aref = $::occurenceHash{$occurs};
      $tmp = (($nth+$wday-$twday)/7) * $aref->[9] + $aref->[3+$twday];
      if($tmp > $repeat) { return 0;}
      if($elength > 0) {
	for ($i=0; $i <$elength; $i++) {
	  if( abs($exception->[$i]) == $tmp) {
	      if($kind != 2 or $exception->[$i] > 0) { return 0; }
	  }
	}
      }
      return ($tmp);
    }

    if ($occ == 5) {			# if ($occurs eq "MonthlyByDate")
      if($td != $dd) { return 0; }
      $tmp = nmonths($tm, $ty, $dm, $dy);
      if($tmp > $repeat) { return 0;}
      if($elength > 0) {
	for ($i=0; $i <$elength; $i++) {
	  if( abs($exception->[$i]) == $tmp) { 
	      if($kind != 2 or $exception->[$i] > 0) { return 0; }
	  }
	}
      }
      return ($tmp);
    } elsif ($occ == 6) {		# elsif ($occurs eq "MonthlyByWeekday")
      my ($code, $codet);
      $tmp = nmonths($tm, $ty, $dm, $dy);
      if($tmp > $repeat) { return 0;}
      $twday = wday($tm, $td, $ty);	# weekday for today
      $wday =  wday($dm, $dd, $dy);	# weekday of event
      if($twday == $wday) {
	my ($code, $tcode);
	$code = $dd % 7; if($code==0 ){ $code = 7;}
	$tcode = $td % 7; if($tcode==0 ){ $tcode = 7;}
	$smp = (($td - $tcode)/7);
	$ump = (($dd - $code)/ 7);
	if($smp != $ump) { return 0 ; }
	if($elength > 0) {
	  for ($i=0; $i <$elength; $i++) {
	    if( abs($exception->[$i]) == $tmp) {
	      if($kind != 2 or $exception->[$i] > 0) { return 0; }
	    }
	  }
	}
	return ($tmp);
      }
      return (0);
    } elsif ($occ == 7) {		# elsif ($occurs eq "Yearly")
      if($td != $dd or $tm != $dm) { return 0; }
      $tmp = $ty - $dy + 1;
      if($tmp > $repeat) { return 0;}
      if($elength > 0) {
	for ($i=0; $i <$elength; $i++) {
	    if( abs($exception->[$i]) == $tmp) { 
	      if($kind != 2 or $exception->[$i] > 0) { return 0; }
	    }
	}
      }
      return ($tmp);
    } elsif ($occ == 11) {		# elsif ($occurs eq "YearlyByMonthWeekday")
      $tmp = $ty - $dy + 1;
      if($tmp > $repeat) { return 0;}
      if($tm != $dm) { return 0;}
      $twday = wday($tm, $td, $ty);	# weekday for today
      $wday = wday($dm, $dd, $dy);	# weekday of event
      if($twday == $wday) {
	my ($code, $tcode);
	$code = $dd % 7; if($code==0 ){ $code = 7;}
	$tcode = $td % 7; if($tcode==0 ){ $tcode = 7;}
	$smp = (($td - $tcode)/7);
	$ump = (($dd - $code)/ 7);
	if($smp != $ump) { return 0 ; }
	if($elength > 0) {
	  for ($i=0; $i <$elength; $i++) {
	    if( abs($exception->[$i]) == $tmp) {
	      if($kind != 2 or $exception->[$i] > 0) { return 0; }
	    }
	  }
	}
	return ($tmp);
      }
      return (0);
    } else { return (0); }
  }
  return (0);
}
#=====================================================================================================

sub dogoto {
    my ($who, $month, $day, $year, $i, $view, @mlist, $mg, $ls);
    $who = $::calinfo{'w'};
    $view = $::calinfo{'v'};
    $ls = $::calinfo{'ls'};
    $month = $::calinfo{'month'};
    $year = $::calinfo{'year'};
    $day = $::calinfo{'day'};
    if(defined $::calinfo{'mg'} and $::calinfo{'mg'} ne "")
      {$mg="<input type=hidden name=mg value=\"$::calinfo{'mg'}\">"; }
    else {$mg="";}

    &headers($::phr{'Goto_Date'},undef,undef,1);
    print "<Form action=\"$::o{'cginame'}\" method=GET>$::vmp
<input type=hidden name=c value=\"dogoto\">
<input type=hidden name=v value=\"$view\">
<input type=hidden name=ls value=\"$ls\">
<input type=hidden name=w value=\"$who\">$mg
<center>
<br><font size=+1><b><span class=\"miscTitle\">$::phr{'SelectDate'}</span></b></font><br>
<br>
<table border=0 cellpadding=0 cellspacing=0>
<tr>";
    @mlist = ();
    for($i = 0; $i< 12; $i++) {
	push @mlist, $i;
	push @mlist, $::mname[$i];
    }
    $month = "<td>".select_value("month",$month,@mlist)."</td>";
    $day = "<td>".select_option("day",$day,(1..31))."</td>";
    $year = "<td>".select_option("year",$year,(1999..2030))."</td>";
    $i = $::o{'dateformat'};
    if ($i == 0) {
	print $month,$day,$year;
    } elsif ($i == 2 or $i == 6 or $i == 7 or $i == 9) {
	print $year,$month,$day;
    } else {
	print $day,$month,$year;
    }
    print "<td><span class=\"fmlabel\">$::phr{'View'}: </span>",select_value("v",$view,@::viewList),
	"</td></tr>";
    print "<tr><td colspan=4 align=center>
 <input type=submit name=action value=\"$::phr{'Go'}\" class=\"fmBtnSt\">
 <input type=submit name=action value=\"$::phr{'Cancel'}\" class=\"fmBtnSt\">
</td></tr></table></center></form>";
    &trailer(0,0);
}

#=====================================================================================================
#
#  Post a setup form
sub signup {
     my ($sname, $who, $email, $name, $homepage, $privacy, $ctype, $msg, $pswd, $rpswd, $dname, $resrc,$isadm,$isvgadm,$vgp,$vgps);
     $msg = (@_)[0];
     $sname=$ENV{'SCRIPT_NAME'};
     $isadm= isadmin($::d{'remote_user'}); $isvgadm= $isadm || isvgadmin($::d{'remote_user'},$::d{'remote_user'});
     if($::o{'create'} == 0 and $isadm == 0 and $isvgadm==0 and iscreator($::d{'remote_user'})==0) {
	 calerror($::phr{'creationDisabled'});
	 exit 0;
     }
     # get default values for fields
     if (-f "./customsignup.pl") {
         do "./customsignup.pl";
     } elsif(not $isvgadm) {
         my $u = $::d{'remote_user'};
         my $cal = "$::o{'spooldir'}/$u";
         if($u and $u ne 'anonymous' and ! -d $cal) { &webcalAuth::GetUserInfo();}
     }
     
     $vgps="";
     if(defined $::calinfo{'email'}) {$email=$::calinfo{'email'}; } else {$email="";}
     if(defined $::calinfo{'w'}) {$who = $::calinfo{'w'};} else {$who = "";}
     if(defined $::calinfo{'name'}){$name = $::calinfo{'name'};} else {$name="";}
     if(defined $::calinfo{'dname'}){$dname = $::calinfo{'dname'};} else {$dname="";}
     if(defined $::calinfo{'homepage'}) {$homepage = $::calinfo{'homepage'};} else {$homepage="";}
     if(defined $::calinfo{'privacy'}) {$privacy = $::calinfo{'privacy'};} else {$privacy="";}
     if(defined $::calinfo{'ctype'}) {$ctype=$::calinfo{'ctype'};} else {$ctype="";}
     if(defined $::calinfo{'passwd'}) {$pswd=$::calinfo{'passwd'};} else {$pswd="";}     
     if(defined $::calinfo{'rpasswd'}) {$rpswd=$::calinfo{'rpasswd'};} else {$rpswd="";} 
     if( $::o{'vgroup'}){
	 if($isadm){
	     my @vgps = &listvgroups; 
	     if(scalar(@vgps)) {$vgps=select_option('vgp', $::calinfo{'vgp'} || "",("??????",@vgps));}
	 } elsif($isvgadm) { 
	     my $g = getcalpvgroup($::d{'remote_user'});
	     $vgps="<span class=\"fmLabel\"><font color=red>&nbsp;<b>$g</b></font></span><input type=hidden name=vgp value=\"$g\">";
	 }
     }
     &headers($::phr{'SetupYourCalendar'},undef,undef,1);
     print "<Form action=\"$sname\" method=POST>
 <input type=hidden name=c value=\"setup\">
 <center>
 <br><font size=+1><b><span class=\"miscTitle\">$::phr{'SetupYourCalendar'}</span></b></font><br>
 <br>";

    if($::calinfo{'msg'}) {
	print "<font color=#ff0000><b>$::calinfo{'msg'}</b></font>\n";
	$msg="";
    }

    print "<table border=0 cellpadding=0 cellspacing=0>
 <tr><td colspan=2 align=center><hr></tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'CalendarName'}: </span></b></td>
    <td><input type=text size=30 maxlength=30 name=w value=\"$who\" class=\"fmEntry\"></td>
 </tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'DescriptiveName'}: </span></b></td>
    <td><input type=text size=30 maxlength=100 name=dname value=\"$dname\" class=\"fmEntry\"></td>
 </tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'OwnerName'}: </span></b></td>
   <td><input type=text size=30 maxlength=64 name=name value=\"$name\" class=\"fmEntry\"></td>
 </tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'OwnerEmailAddress'}: </span></b></td>
    <td><input type=text size=30 maxlength=100 name=email value=\"$email\" class=\"fmEntry\"></td>
 </tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'OwnerHomepage'}: </span></b></td>
   <td><input type=text size=30 maxlength=64 name=homepage value=\"$homepage\" class=\"fmEntry\"></td>
 </tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'Password'}: </span></b></td>
   <td><input type=password size=30 maxlength=16 name=passwd value=\"$pswd\" class=\"fmEntryP\"></td>
 </tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'RetypePassword'}: </span></b></td>
   <td><input type=password size=30 maxlength=16 name=rpasswd value=\"$rpswd\" class=\"fmEntry\"></td>
 </tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'CalendarType'}: </span></b></td>
   <td>",select_value("ctype",$ctype, @::ctypeList), "</td></tr>";

     {
	 my $tmp =0; if($::calinfo{'resrc'}) { $tmp=1;}
	 print "<tr><td colspan=2 align=center><font color=#009900><b><span class=\"fmLabelS\">$::phr{'ResrcCal'}&nbsp;</span>";
	 print input_radio("resrc", $tmp, @::switchList);
	 print "</b></font></td></tr>\n";
	 $tmp = 0;  if($::calinfo{'aap'}) { $tmp=1;}
	 print "<tr><td colspan=2 align=center><font color=#000099 size=\"-1\"><b><span class=\"fmLabelS\">$::phr{'AllowAP'} &nbsp;</span>";
	 print input_radio("aap", $tmp, @::switchList);
	 print "</b></font></td></tr>\n";
     }

     print "
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'Privacy'}: <br></span><font color=#ff0000 size=-1><span class=\"fmLabelS\">($::phr{'ForPrivateCalendar'})</span></font></b></td>
  <td>",select_value("privacy",$privacy,	(@::privacyList)),"</td> </tr>";
     
     if($vgps){print "<tr><td><font size=1>&nbsp;</font></td></tr><tr><td align=right><b><span class=\"fmLabel\">$::phr{'VirtualGroup'}: </span></td><td>$vgps</td></tr>";}

     if($isvgadm) {
	 print "<tr><td colspan=2 align=center><span class=\"fmLabel\">Copy header/footer html code from calendar <b>$::d{'remote_user'}</b>? <b>&nbsp;";
	 print input_radio("cpyhdrftr", 0, @::switchList);
	 print "</b></td></tr>\n";
     }
       print "
 <tr><td colspan=2 align=center><hr></tr>
 <tr><td colspan=2 align=center>
   <input type=submit name=action value=\"$::phr{'Submit'}\" class=\"fmBtnSt\"></td>
 </tr>
 </table>
 </form>";
   if($msg) { print "<font color=#ff0000 size=+1><br><b><span class=\"warnMsg\">$msg</span></b></font>\n";}
  print "</center>";
  &trailer(0,0);
}

#=====================================================================================================
sub format_recur_string {
    my ( $occurs, $repeat, $sdate) = (@_);
    if($repeat > 99) {	return  "$::phr{'Occurs'} $occurs";}
    else {return sprintf $::phr{'recurFormat'}, $occurs, $repeat, $sdate; }
}
#=====================================================================================================
sub special_recurring_rule {
    my ($word, $c1,$c2, $repeat)=(@_); 
    my $zstr="";
    if($word eq 'W') {
	my @maskary = wdayoffsets($c2);
	my $nbits = $maskary[9];
	$repeat = int(($repeat +$nbits-1) / $nbits);
	if($c1 == 1) { $zstr= "weekly on ";}
	elsif($c1 == 2) { $zstr= "biweekly on ";}
	else { $zstr= "every $c1 weeks on ";}
	my $i; for($i=0; $i<7; $i++) { if($c2 &(1<<$i)) { $zstr .= "$::swd[$i]";}}
    } elsif($word eq 'D') {
	if($c1==1){ $zstr = "daily";}
	else { $zstr= "every $c1 days";}
    } elsif($word eq 'MD') {
	if($c1 == 1) { $zstr= "monthly on the same day"}
	else {$zstr= "every $c1 month on the same day";	}
    } elsif($word eq 'MWD') {
	if($c1 == 1) { $zstr= "monthly on the same weekday"}
	else { $zstr= "every $c1 month on the same weekday";}
    } elsif($word eq 'MND') {
	if($c1 == 1) { $zstr= "monthly on the same day counting from the end of the month"}
	else { $zstr= "every $c1 month on the same day counting from the end of the month";}
    } elsif($word eq 'MNW') {
	if($c1 == 1) { $zstr= "monthly on the same weekday counting backwards from the end of the month"}
	else { $zstr= "every $c1 month on the same weekday counting abckwards from the end of the month";}
    } elsif($word eq 'X') {
	$zstr = "every $c1 weekdays";
    }
    return ($zstr, $repeat);
}
#=====================================================================================================
sub monthRow {
    my ($imonth, $iyear) = (@_);
    my ($i,$j, $k, $ans, $ndays, $offset, $key, $mg, $ls,$iwho);
    if($imonth == 1 and isleap($iyear)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}
    my $wgclr= $webcalConfig::r{'c1color'};
    my $code = wday($imonth, 1, $iyear);
    $ls=$::calinfo{'ls'}; $iwho=$::calinfo{'w'};
    if($::d{'megaCal'} ne "") {$mg="&mg=$::d{'megaCal'}"; } else {$mg="";}
    $ans=<<EOL;
<tr><td class="yvCol1Td" bgcolor=$wgclr>
<a href="$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=3&d=$imonth/1/$iyear/9/0$mg$::vmg">
<span class="yvCol1Txt">$::mNames[$imonth]</span></a>
</td> 
EOL
    ;
    $k=0;
    for($i=0; $i<$code; $i++, $k++) {
	$ans .= "<td background=\"$::o{'imgdirurl'}/mask1.gif\" class=\"ycm\">&nbsp;</td>";
    }
    $ndays = 1+$::mdays[$imonth];
    $offset = $imonth * 31;
    my ($ab);
    $ab = "$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=1&$mg$::vmg";
    
    for($i=1; $i< $ndays; $i++, $k++) {
	$key = $::yeartable[$offset + $i];
	if($key > 1) {
	    my $tmp = (($key - 1) & 0x1f); 
	    my $clr = $webcalConfig::r{'txtColors'}->[$tmp];
	    my $bclr = "bgcolor=$clr";
	    $ans .= "<td width=20 height=20 $bclr class=\"yc2\"><b><a href=\"$ab&d=$imonth/$i/$iyear\"><font size=-1 color=red><span class=\"ycbusy\">$i</span></font></a></b></td>";
	} elsif($key) {
	    $ans .= "<td width=20 height=20 bgcolor=#ffffff class=\"yc1\"><b><a href=\"$ab&d=$imonth/$i/$iyear\"><font size=-1 color=red><span class=\"ycbusy\">$i</span></font></a></b></td>";
	} else {
	    $ans .= "<td width=20 height=20 bgcolor=#ffffff class=\"yc0\"><a href=\"$ab&d=$imonth/$i/$iyear\"><font size=-1><span class=\"ycfree\">$i</span></font></a></td>";
	}
    }
    while($k < 37) {
	$ans .= "<td background=\"$::o{'imgdirurl'}/mask1.gif\" class=\"ycm\">&nbsp;</td>";
	$k++;
    }
    $ans .= "</tr>";
    return $ans;
}
#=====================================================================================================
sub yearViewOptions {
    my ($ls,$iwho,$month,$day,$year,$mg) = (@_);
    my ($detail, $summary);

    if($::vm & 0x800000) { # combined matrix view
	$detail=<<END;
<img src="$::o{'imgdirurl'}/eww.gif" width=11 height=11 border=0 title="$::phr{'CombinedView'}" alt="$::phr{'CombinedView'}"><font size=1>&nbsp;</font>
<a href="$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=4&ydetail=d&d=$month/$day/$year$mg$::vmg"><img src="$::o{'imgdirurl'}/ed.gif" width=11 height=11 border=0 title="$::phr{'DetailedView'}" alt="$::phr{'DetailedView'}"></a><font size=1>&nbsp;</font>

END
    ;
    } else {
	$detail=<<END;
<a href="$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=4&ydetail=n&d=$month/$day/$year/9/0$mg$::vmg"><img src="$::o{'imgdirurl'}/ew.gif" width=11 height=11 border=0 title="$::phr{'CombinedView'}" alt="$::phr{'CombinedView'}"></a><font size=1>&nbsp;</font>
<img src="$::o{'imgdirurl'}/edd.gif" width=11 height=11 border=0 title="$::phr{'DetailedView'}" alt="$::phr{'DetailedView'}"><font size=1>&nbsp;</font>
END
    ;
    }
    return $detail;
}
#=====================================================================================================

sub yearCal {
    my ($month, $day, $year, @mcals, $i,$iwho,$ls, $mg);
    ($month, $day, $year) = (@_);
    @mcals = (" "," "," "," "," "," "," "," "," "," "," "," "," ");
    $iwho = $::calinfo{'w'};
    if($::catfilterpattern) {makeYearTableFilter($year, $::o{'spooldir'}, $iwho, $::d{'megaCal'}, $::calinfo{'dctoc'});}
    elsif($::srchftrptn) {makeYearTableSrch($year, $::o{'spooldir'}, $iwho, $::d{'megaCal'}, $::calinfo{'dctoc'});}
    else {makeYearTable($year, $::o{'spooldir'}, $iwho, $::d{'megaCal'}, $::calinfo{'dctoc'});}
    $ls = $::calinfo{'ls'};    
    if($::d{'megaCal'} ne "") {$mg="&mg=$::d{'megaCal'}"; } else {$mg="";}
    my $options = yearViewOptions($ls,$iwho,$month,$day,$year,$mg);

    my ($nextc, $prevc, $search, $vmg);
    if(! $::calinfo{'pnt'}) {
	$nextc = "&nbsp;&nbsp;<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=4&d=$::o{'nextc'}$mg$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/rright.gif\" width=10 height=12 border=0></a>";
	$prevc = "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=4&d=$::o{'previousc'}/9/0$mg$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/rleft.gif\" width=10 height=12 border=0></a>&nbsp;&nbsp;";
	if($::d{'megaCal'}){$vmg="<input type=hidden name=mg value=\"$::d{'megaCal'}\">";} else {$vmg="";}
	$search = <<END;
<table border=0 cellpadding=0 cellspacing=0 class="calSearch"><tr><td nowrap>
<Form name=csearch action="$::o{'cginame'}" method=GET  class="searchform">
<input type=hidden name=c value="dosearch">
<input type=hidden name=w value="$iwho">
<input type=hidden name=searchRange value="all">
<input type=hidden name=v value=4>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$month/$day/$year">
$::vmp
$::srchi<a href="$::o{'cginame'}?c=search&w=$iwho&v=4&ls=$ls&$mg$::vmg"><font size=1><span class="fmLabelSa">$::phr{'Search'}:</span></font></a>
<font size=1><input type=text name=stopic size=10 maxlength=128 value="$::srchftrptn" class="fmEntrySa"></font>
<font size=1><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font>
</Form>
</td></tr></table>
END
    ;
    } else { $nextc = $prevc ="";  $search ="&nbsp;";}

    #==========================================================================
    my ($eventTable, $spacer, $filler) = ("","", "");
    my $rbg = "bgcolor=$webcalConfig::r{'dkbackground'}";
    my $irepository = "$::o{'imgdirurl'}/$::o{'uploadsubdir'}";
    my $etitle; if($::srchftrptn){$etitle = $::phr{'Search_Results'};} else { $etitle=$::phr{'SpecialEvents'};}
    #==========================================================================
    my $dnd = ($::vm & 0x1000) ? 0 : 1;
    my $dndid="";
    if(not ($::o{'dnd'} and $dnd)) { $dnd =0;} 
    {
	my($earray, $href, $repeat, $sstr, $recur_str, $occurs, $sdate, $URL,$mg, $edate, $gprivacy, $eprivacy,
	   $smn, $mmn, $sdy, $mdy, $syr, $myr, $title, $key, $bg, $clr, %hash, $counter, $detail, $ed, $dtip);
	%hash=(); $counter=0; 
	if($::vm & 0x40) { $ed = "m2";} elsif($ls < 0) { $ed="ec";} else {$ed="ed";}	

	#if($::year_special_cached and scalar(@::ydata)>0) { $earray = \@::ydata;} else { $earray = \@::caldata;}
	$earray=\@::caldata;
	($gprivacy, $mg) = &getPrivacy(1);

	foreach $href (@$earray) {
	    if($::year_special_cached or $href->{'ycm'}) {
		if( $href->{'pnd'}) {
		    next if not $::d{'ceditor'};
		    next if $href->{'pnd'} ne $iwho;
		}
		if($gprivacy > 3) { $eprivacy = 3;}
		else {
		    if(defined $href->{'e'} or (defined $href->{'w'} and $href->{'w'} eq $::d{'remote_user'})) { $eprivacy = 3;} #for megaCalendar
		    elsif(defined $href->{'privacy'}) { $eprivacy = $::privacyTable{$href->{'privacy'}} -1;}
		    else {$eprivacy = $gprivacy;}
		}
		next if $eprivacy == 0;
		next if not &$::catfiltersub($href->{'cat'});
		if($::srchftrptn) { next if not match_search_words($href,$eprivacy);}		
		
		if($eprivacy >= 2) { $title = $href->{'what'}; } else { $title = "$::phr{'Protected'}";}
		if($title) {
		    $recur_str = "";
		    $key = $href->{'key'};
		    $sdate = $href->{'date'};
		    ($smn, $sdy, $syr) = split(/\//, $sdate); ($mmn, $mdy, $myr) = ($smn, $sdy, $syr);
		    $smn--;  $edate="$smn/$sdy/$syr";
		    $repeat = $href->{'repeat'}; $occurs = $href->{'occurs'};
		    $dtip="";
		    if( $repeat and  $repeat > 1 and $occurs and $occurs !~ /OneTime/) {
			my ($tm,$td,$ty,$exception,$x,$y, $ntimes, $alldates, $zstr, @maskary); 
			my @alldates = getAllDates($smn, $sdy, $syr, $occurs, $repeat);
			$zstr="";
			if($occurs eq 'MTWThF') { $repeat =  int((4+$repeat) / 5);}
			elsif ($occurs eq 'MWF') {$repeat =  int((2+$repeat) / 3);}
			elsif ($occurs eq 'TTh') { $repeat =  (1+$repeat) >> 1;}
			elsif(substr($occurs,0,1) eq 'Z' and $occurs =~ /^Z(.+),(\d+),(\d*)/ ) {
			    my ($word,$c1,$c2) = ($1,$2,$3);
			    ($zstr, $repeat) = special_recurring_rule($word, $c1, $c2, $repeat);
			}
			$ntimes=@alldates; 
			if($ntimes > 0) {
			    my $exception = $href->{'exception'};
			    if($exception) {
				my $elength = $#$exception;
				for $x (0.. $elength) {
				    $y = abs($exception->[$x]);
				    my $z = $y -1;
				    $tm = $alldates[$z];
				    my ($m, $d, $y) = split(/\//, $tm);
				    $alldates[$z] = "$m/-$d/$y";
				}
			    }
			    my ($m, $d, $y) = split(/\//, $alldates[0]);
			    my ($t, $c);
			    if($y != $year) {
				for $t (0 .. $ntimes) {
				    ($m, $d, $y) = split(/\//, $alldates[$t]);
				    if($y and $y != $year) { $alldates[$t] = "$m/$d/-$y";}
				    elsif($d > 0) { $smn = $m -1; $sdy = $d; last;}
				}
			    }
			    ($m, $d, $y) = split(/\//, $alldates[$ntimes-1]);
			    if($y != $year) {
				for($t=$ntimes -1; $t>= 0; $t--){
				    ($m, $d, $y) = split(/\//, $alldates[$t]);
				    if($y and $y != $year) { $alldates[$t] = "$m/$d/-$y";}
				    else { last;}				    
				}
			    }
			    my $total = 0;
			    for($x=0; $x< $ntimes;$x++) {
				next if $alldates[$x] eq "0/0/0";
				($tm, $td, $ty) = split(/\//, $alldates[$x]); #month is in 0--11
				if($ty < 0) {
				    $alldates[$x] = "<font color=#666699>" . md_nstring($tm, $td) . "</font>"; 
				} elsif($td < 0) {
				    $alldates[$x]="<strike><font color=#999999>" . md_nstring($tm, -$td) . "</font></strike>"; 
				} else {
				    $total++;
				    $alldates[$x] = md_nstring($tm, $td); 
				}
			    }
			    if($total and $occurs !~ /Yearly/) {
				$alldates="<font color=#ff0000><b>$::phr{'EventDates'}:</b></font><br><br><font size=1>";
				$c = 0;
				foreach $t (@alldates) { 
				    next if $t eq "0/0/0";
				    $alldates .= $t . ",&nbsp; "; $c++; 
				    if($c > 4) { $c=0; $alldates .= "<br><br>";}
				}
				$alldates .= "</font><br>";
			    
				my $tid = addtip($alldates);
				$dtip = " onMouseOver=\"showtip(event,\'$tid\');\" onMouseout=\"hidetip(\'$tid\');\"";

				if($zstr) {$occurs = $zstr; } else {$occurs = $::phr{$occurs};}
				$recur_str = format_recur_string($occurs, $repeat, mdy_nstring($mmn,$mdy,$myr));
			    }
			}
		    }

		    $sstr = md_nstring(1+$smn, $sdy);
		    $URL=$detail=""; my $cfm="";
		if($eprivacy >= 3) {
		    if($href->{'detail'}) { $detail = "$href->{'detail'}";} else {$detail ="";}
		    my ($misc, $troom, $tspkr, $tcat, $trest)  = getMiscInfo($href);
		    if($misc){ if($detail) {$detail .= "<br>$misc";} else { $detail=$misc;}}
		    my $rurl= $href->{'url'}; 
		    if($rurl) {
			my (@urls, $a, $b); @urls = split(/\s+/, $rurl); 
			foreach $a (@urls) {
			    my $icon = select_url_icon($a);
			    $a =~ s/\\?\^o\^\//$irepository\//g;
			    $URL .="<A HREF=\"$a\" target=i><img src=\"$::o{'imgdirurl'}/$icon\" width=20 height=9 border=0></A> ";
			}
		    }
		    $cfm = DoConfirmMeeting1($href, $edate, $mg);
		    $detail = &substImages($detail);
		}
		    my ($tc, $bg, $tip)=("","","");
		    $tc = $href->{'fg'} if $href->{'fg'}; $bg = $href->{'bg'} if $href->{'bg'};
		    my ($aref, $zzz); 
		    if($::d{'megaCal'} ne "") {
			my $owner = $href->{'w'};
			if($dnd) {$dndid="id=\"_:$owner:t=$key\" onmousemove=\"dndmv()\" ondragstart=\"dndst()\"";}
			if($detail) {
			    my $zz = $owner; $zz =~ s/[^A-Za-z0-9]//g;
			    $detail =~ s/\n/<br>/g if ($detail =~ tr/\n/\n/) <20;
			    my $tpid = add4tip("$key$zz", $detail,0);
			    $tip = " onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"";
			} 
			if($tc){
			    $aref ="$::o{'cginame'}?w=$owner&v=4&ls=$ls&t=$key&k=4&d=$edate$mg$::vmg";
			    $zzz=$URL . $cfm . "<a href=\"$aref&c=$ed\"$tip $dndid><font color=$tc>$title</font></a>";  
			} else {
			    $aref ="$::o{'cginame'}?w=$owner&v=4&ls=$ls&t=$key&k=4&d=$edate$mg$::vmg";
			    $zzz = $URL . $cfm . "<a href=\"$aref&c=$ed\"$tip $dndid>$title</a>";
			}
		    } else {
			if($dnd) {$dndid="id=\"_:$iwho:t=$key\" onmousemove=\"dndmv()\" ondragstart=\"dndst()\"";}
			if($detail) {
			    $detail =~ s/\n/<br>/g if ($detail =~ tr/\n/\n/) <20;
			    my $tpid = add4tip($key, $detail,0);
			    $tip = " onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"";
			} 
			if($tc) {
			    $aref ="$::o{'cginame'}?w=$iwho&v=4&ls=$ls&t=$key&k=4&d=$edate$::vmg";
			    $zzz = $URL . $cfm . "<a href=\"$aref&c=$ed\"$tip $dndid><font color=$tc>$title</font></a>";
			} else {
			    $aref="$::o{'cginame'}?w=$iwho&v=4&ls=$ls&t=$key&k=4&d=$edate$::vmg";
			    $zzz = $URL . $cfm . "<a href=\"$aref&c=$ed\"$tip $dndid>$title</a>";
			}			
		    }
		    $zzz = &substImages($zzz);		    
		    $clr = ($key & 0x1f); $clr = $webcalConfig::r{'txtColors'}->[$clr];
		    $clr = "color=$clr";
		    if($bg){ $bg=" bgcolor=$bg";}
		    if($recur_str) { $recur_str = "<br><font color=#9090ff size=1><span class=\"yvRecurrence\">$recur_str</span></font>";}
		    my $ktmp = sprintf "%02d/%02d/%04d", $smn, $sdy, $counter; $counter++; 
		    if($dtip){ $sstr="<u>$sstr</u><br><img src=\"$::o{'imgdirurl'}/recur.gif\" width=12 height=12 border=0>";}
		    $hash{$ktmp}="<tr valign=top $rbg><td nowrap$bg class=\"yvEttdt\"><a href=\"$aref&c=m2\"$dtip $dndid><font $clr><b>$sstr</b></font></a></td><td$bg class=\"yvEttde\">$zzz$recur_str</td></tr>";
		}
	    }
	}
	if($counter) {
	    use integer;
	    for $key (sort keys %hash) {$eventTable .= $hash{$key}; }
	    $spacer="<img src=\"$::o{'imgdirurl'}/spacer.gif\" width=200 height=10 border=0><br>";
	    $filler = "<tr><td colspan=3 height=1000>&nbsp;</td></tr>";
	    $counter = 1 + $counter/30; 
	    $filler = "$filler" x $counter;
	}
    }
    #==========================================================================    
    if(($::vm & 0x800000)) {
	my $zgclr= $webcalConfig::r{'r1color'};
	my ($borderwidth, $spacing);
	if($::calinfo{'pnt'}) {$borderwidth=1; $spacing=0;} else { $borderwidth=0; $spacing=1;}
	for( $i = 0; $i < 12; $i++) { $mcals[$i] = monthRow($i, $year);}
	my $ans = <<END;
<table border=0 cellpadding=0 cellspacing=0 bgcolor="#c0cccf" width="100%" class="backtblycal">
<tr><td bgcolor="#c0cccf" width="100%" class="backtblycal">
<table class=yvtbl border=$borderwidth cellspacing=$spacing cellpadding=0><tr>
<td class="yvRow1Td" bgcolor=$zgclr>&nbsp;</td>
END
    ;
	for($i=0; $i<37; $i++) {
	    my $tmp = $i%7; 
	    $ans .= "<td class=\"yvRow1Td\" bgcolor=$zgclr><font size=-1 color=white><span class=\"yvRow1Txt\">$::swd[$tmp]</span></font></td>";
	}
	$ans .="<tr>";
	my $result="";
	if($eventTable) {
	    $result= <<END;
<center>
<table border=0 cellspacing=0 cellpadding=1 width="$::o{'tw'}%"><tr><td width="25%" align=center>$::o{'qadd'}&nbsp;</td><td width="50%" align=center nowrap>
$::mnbar<font color="#ff0000"><b><span class="yvTitle">$prevc$::srchn$year$nextc</span></b></font>$::vnbar $options 
</td><td width="25%" align=right nowrap valign=top>$search</td></tr></table>
<table border=0 cellpadding=0 cellspacing=8 width="$::o{'tw'}%">
<tr valign=top>
<td>
$ans $mcals[0] $mcals[1] $mcals[2] $mcals[3] $mcals[4] $mcals[5]
$mcals[6] $mcals[7] $mcals[8] $mcals[9] $mcals[10] $mcals[11]
</table>
</td></tr></table>
</td>
<td>
     <table border=0 cellspacing=0 cellpadding=0 width="100%"  class="yvEtHolder">
      <tr><td bgcolor="#333333" width="100%"  class="yvEtHolderTD">
	     <table border=0 cellspacing=0 cellpadding=3 width="100%" class="yvETbl">
                 <tr><td align=center colspan=2 $rbg class="yvEtTRow"><font size=+1 color=red><span class="yvEtTitle">$etitle</span><br></font></td></tr>
		 $eventTable
	      </table>
       </td>
    </tr>
    </table>
</td>
</table>
</center>
END
    ;
	} else {
	    $result= <<END;
<center>
<table border=0 cellspacing=0 cellpadding=1 width="$::o{'tw'}%"><tr><td width="25%" align=center>$::o{'qadd'}&nbsp;</td><td width="50%" align=center nowrap>
$::mnbar<font color="#ff0000"><b><span class="yvTitle">$prevc$::srchn$year$nextc</span></b></font>$::vnbar $options 
</td><td width="25%" align=right nowrap valign=top>$search</td></tr></table>
$ans $mcals[0] $mcals[1] $mcals[2] $mcals[3] $mcals[4] $mcals[5]
$mcals[6] $mcals[7] $mcals[8] $mcals[9] $mcals[10] $mcals[11]
</table>
END
    ;
	}
	return ($result);
    }
    for( $i = 0; $i < 12; $i++) { $mcals[$i] = monthCal($i, 0, $year, 0, 1);}
    #==========================================================================    
    if($eventTable) {
	my ($spacing, $border);
	if($::calinfo{'pnt'}){$spacing=0;$border=1;}else{$spacing=1;$border=0;}
	my $ans = <<END;
<center>
<table border=0 cellspacing=0 cellpadding=1 width="$::o{'tw'}%"><tr><td width="25%" align=center>$::o{'qadd'}&nbsp;</td><td width="50%" align=center nowrap>
$::mnbar<font color="#ff0000"><b><span class="yvTitle">$prevc$::srchn$year$nextc</span></b></font>$::vnbar $options 
</td><td width="25%" align=right nowrap valign=top>$search</td></tr></table>
</center>
<table border=0 cellpadding=0 cellspacing=8 width="$::o{'tw'}%">
<tr valign=top>
  <td width="23%" bgcolor="#c0cccf" class="yvmth">$mcals[0]</td>
  <td width="23%" bgcolor="#c0cccf" class="yvmth">$mcals[1]</td>
  <td width="23%" bgcolor="#c0cccf" class="yvmth">$mcals[2]</td>
  <td rowspan=99 align=center width="28%">
     $spacer
     <table border=0 cellspacing=0 cellpadding=0 width="100%"  class="yvEtHolder">
      <tr><td bgcolor="#333333" width="100%"  class="yvEtHolderTD">
	     <table border=0 cellspacing=0 cellpadding=3 width="100%" class="yvETbl">
                 <tr><td align=center colspan=2 $rbg class="yvEtTRow"><font size=+1 color=red><span class="yvEtTitle">$etitle</span><br></font></td></tr>
		 $eventTable
	      </table>
       </td>
    </tr>
    </table>
  </td>
</tr>
<tr valign=top>
  <td bgcolor="#c0cccf" class="yvmth">$mcals[3]</td>
  <td bgcolor="#c0cccf" class="yvmth">$mcals[4]</td>
  <td bgcolor="#c0cccf" class="yvmth">$mcals[5]</td>
</tr>

<tr valign=top>
  <td bgcolor="#c0cccf" class="yvmth">$mcals[6]</td>
  <td bgcolor="#c0cccf" class="yvmth">$mcals[7]</td>
  <td bgcolor="#c0cccf" class="yvmth">$mcals[8]</td>
</tr>

<tr vaign=top>
  <td bgcolor="#c0cccf" class="yvmth">$mcals[9]</td>
  <td bgcolor="#c0cccf" class="yvmth">$mcals[10]</td>
  <td bgcolor="#c0cccf" class="yvmth">$mcals[11]</td>
</tr>
$filler
</table>
END
    ;
	return $ans;
    } else {
	my $ans = <<END
<center>
<table border=0 cellspacing=0 cellpadding=1 width="$::o{'tw'}%"><tr><td width="25%" align=center>$::o{'qadd'}&nbsp;</td><td width="50%" align=center nowrap>
$::mnbar<font color="#ff0000"><span class="dvTitle">$prevc$::srchn$year$nextc</span></font>$::vnbar $options
</td><td width="25%" align=right nowrap valign=top>$search</td></tr></table>
</center>

<table border=0 cellpadding=0 cellspacing=3 width="$::o{'tw'}%">
<tr valign=top>
  <td bgcolor="#c0cccf" width="25%" class="yvmth">$mcals[0]</td>
  <td bgcolor="#c0cccf" width="25%" class="yvmth">$mcals[1]</td>
  <td bgcolor="#c0cccf" width="25%" class="yvmth">$mcals[2]</td>
  <td bgcolor="#c0cccf" width="25%" class="yvmth">$mcals[3]</td></tr>
</table>
<table border=0 cellpadding=0 cellspacing=3 width="$::o{'tw'}%">
<tr valign=top>
  <td bgcolor="#c0cccf" width="25%" class="yvmth">$mcals[4]</td>
  <td bgcolor="#c0cccf" width="25%" class="yvmth">$mcals[5]</td>
  <td bgcolor="#c0cccf" width="25%" class="yvmth">$mcals[6]</td>
  <td bgcolor="#c0cccf" width="25%" class="yvmth">$mcals[7]</td></tr>
</table>
<table border=0 cellpadding=0 cellspacing=3 width="$::o{'tw'}%">
<tr valign=top>
  <td bgcolor="#c0cccf" width="25%" class="yvmth">$mcals[8]</td>
  <td bgcolor="#c0cccf" width="25%" class="yvmth">$mcals[9]</td>
  <td bgcolor="#c0cccf" width="25%" class="yvmth">$mcals[10]</td>
  <td bgcolor="#c0cccf" width="25%" class="yvmth">$mcals[11]</td></tr>
</table>
END
    ;
	return $ans;
    }
}

#=====================================================================================================
# Args: month day year size
#      size=0 or 1 (for small and big)
#
sub monthCal {
    use integer;
    my ($flag, $cview, $imonth, $iday, $iyear, $stmp, $out, $i, $day, $ndays, $syr, $smn, $yr, $nn, $mm,$code,$wkendclr,
	$itmp, $tyr, $tmn, $tdy, $iwho, $todayc, $espace, $wklen, $percent, $ucode, $wknum, $offset, $mg, $ls, $ar, $borderwidth, $spacing);
    ($imonth, $iday, $iyear, $cview, $ar) = (@_);
    $mm = $imonth; $nn = $iyear;
    # validate date
    while( $mm < 0) { $mm += 12; $nn -= 1; }
    while( $mm > 11) { $mm -= 12; $nn += 1;}
    $syr = $nn; $smn = $mm;		#save year, month [0-11]
    $imonth = $smn; $iyear=$syr;	#modified input

    if($cview != 3) {			#large month view
	# small month calendar, no event table
	$out = mkSmallMCal($imonth, $iday, $iyear, $iday, $iday, "width=\"100%\"", "height=20", $ar, 2, '#6699cc', 1, 0, "");
	return($out);
    }
    my $dnd = ($::vm & 0x1000) ? 0 : 1;
    my ($dndid,$dndop)=("","");
    if($::o{'dnd'} and $dnd){
	$dndop ="ondragenter=\"dnden()\" ondragover=\"dndov()\" ondragleave=\"dndlv()\" ondrop=\"dnddp()\"" ;
    } else {$dnd = 0;}
    $iwho = $::calinfo{'w'};
    $ls = $::calinfo{'ls'};
    $tmn = $::now{'month'}; $tdy = $::now{'day'}; $tyr = $::now{'year'};    
    # compute weekday offset
    $code = wday($smn, 1, $syr);
    $todayc = printDate( $::now{'month'}, $::now{'day'}, $::now{'year'});
    $itmp = 0;
    if($::d{'megaCal'} ne "") {$mg="&mg=$::d{'megaCal'}"; } else {$mg="";}
#    $wkendclr="";
    $::scntr=1;
    if($::o{'excludeWeekend'}) { $wklen = 5; $percent = 20;  } 
    else { $wklen = 7; $percent = 14;}
#    else { $wklen = 7; $percent = 14; if($::calinfo{'wkendclr'}) {$wkendclr=$::calinfo{'wkendclr'};}}
    # if($cview == 3) {			#large month view
      if(isleap($syr)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}
      $ndays = $::mdays[$smn];
      if( $webcalConfig::r{'moonphase'}) {
	$::yeartable[69] =0;
	for($i=21; $i < 69; $i++) { $::yeartable[$i] = 0;}
	# find moon phases
	my ($jd, @ptimes, $pmonth, $nmonth);
	if($imonth == 0) {$pmonth = 11; } else {$pmonth = $imonth -1;}
	if($imonth == 11) {$nmonth = 0; } else {$nmonth = $imonth +1;}
	$jd=webcalMoon::jtime($iyear, $imonth, 1, 0, 0, 0);
	@ptimes = &webcalMoon::phasehunt($jd);
	for($i = 0; $i < 8; $i++) {
	  $jd = $ptimes[$i];
	  my ($yy,$mm, $dd) = &webcalMoon::jyear($jd); $mm--;
	  if($mm == $pmonth) { $::yeartable[$dd] = ($i %4) + 1;}
	  elsif($mm == $imonth) { $::yeartable[31+$dd] = ($i %4) + 1;}
	  elsif($mm == $nmonth) { $::yeartable[62+$dd] = ($i %4) + 1;}
	}
      }
      if($::calinfo{'pnt'}){$borderwidth=1;$spacing=0;}else{$borderwidth=0;$spacing=1;} 
      $itmp = $wklen+1;
      my $zgclr= $webcalConfig::r{'r1color'};
      my $wgclr= $webcalConfig::r{'c1color'};
      my ($nextc, $prevc, $search, $vmg);
      if(! $::calinfo{'pnt'}) {
	  $nextc = "&nbsp;&nbsp;<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=3&d=$::o{'nextc'}/9/0$mg$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/rright.gif\" width=10 height=12 border=0></a>";
	  $prevc = "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=3&d=$::o{'previousc'}/9/0$mg$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/rleft.gif\" width=10 height=12 border=0></a>&nbsp;&nbsp;";
	  if($::d{'megaCal'}){$vmg="<input type=hidden name=mg value=\"$::d{'megaCal'}\">";} else {$vmg="";}
	  $search = <<END;
<table border=0 cellpadding=0 cellspacing=0 class="calSearch"><tr><td nowrap>
<Form name=csearch action="$::o{'cginame'}" method=GET  class="searchform">
<input type=hidden name=c value="dosearch">
<input type=hidden name=searchRange value="all">
<input type=hidden name=w value="$iwho">
<input type=hidden name=v value=3>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$imonth/$iday/$iyear">
$::vmp$vmg
$::srchi<a href="$::o{'cginame'}?c=search&w=$iwho&v=3&ls=$ls&$mg$::vmg"><font size=1><span class="fmLabelSa">$::phr{'Search'}:</span></font></a>
<font size=1><input type=text name=stopic size=10 maxlength=128 value="$::srchftrptn" class="fmEntrySa"></font>
<font size=1><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font>
</Form>
</td></tr></table>
END
    ;
      } else { $nextc = $prevc =""; $search = "&nbsp;";}
     $out = <<END;
<center>
<table border=0 cellspacing=0 cellpadding=1 width="$::o{'tw'}%"><tr><td width="25%" align=center>$::o{'qadd'}&nbsp;</td><td width="50%" align=center nowrap>
$::mnbar<font color=red><b><span class="mvTitle">$prevc$::srchn$::mname[$smn] $syr</span>$nextc</b></font>$::vnbar
</td><td width="25%" align=right nowrap valign=top>$search</td></tr></table>
</center>

<table border=0 cellpadding=0 cellspacing=0 bgcolor="#c0cccf" width="$::o{'tw'}%" class="backtblmcal">
<tr><td bgcolor="#c0cccf" width="100%" class="backtblmcal">
<table class="mvtbl" border=$borderwidth cellpadding=0 cellspacing=$spacing width="100%">
<tr><td width="1%" bgcolor=$zgclr class="mvRow1Td"><font size=-2>&nbsp;</font></td>
END
    ;
      for ($i = 0; $i < $wklen; $i++) {
	$out .= "<td width=\"$percent%\" bgcolor=$zgclr align=center class=\"mvRow1Td\"><font $webcalConfig::fontsize{'tablabel'} color=#ffffff><span class=\"mvRow1Txt\">$::wdays[$::o{'weekstart'}+$i]</span></font></td>";
      }
      $out .= "</tr>\n";
      if( ! $::o{'excludeWeekend'} || ( $code > $::o{'weekstart'} && $code <= 5)) {
	$wknum = weekNum($imonth,1,$iyear, $::o{'weekstart'}); 
	$stmp = "<tr><td align=center width=\"1%\" bgcolor=$wgclr class=\"mvCol1Td\"><a href=\"$::o{'cginame'}?c=get&w=$iwho&v=2&ls=$ls&d=$imonth/1/$iyear$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/right.gif\" width=11 height=11 border=0></a><br><font color=#ffff00 size=1><span class=\"mvCol1Txt\">$wknum</span></font></td>";
	$out .= $stmp;
	if($::o{'weekstart'}) { $ucode = ($code==0? 6: $code - $::o{'weekstart'}); } else {$ucode = $code;}
	if($ucode > 0) {
	  my ($pmonth, $pday, $pyear, $pii);
	  ($pmonth, $pday, $pyear) = canDate($imonth, 1-$ucode, $iyear);
	  for($pii = 0; $pii < $ucode; $pii++) {
	    my ($bclr, $diary, $iswkend); $iswkend = $::o{'weekstart'} + $pii;
	    my $id="mvtdpmth"; my $iswknd=($iswkend==0 or $iswkend >= 6); # if($iswknd){$id="mvtdwknd";}
	    if( $tyr == $pyear && $tmn == $pmonth && $tdy == $pday) { $bclr="$webcalConfig::r{'todayHcolor'}";}
#	    if($::calinfo{'clr2'}) {$bclr=$::calinfo{'clr2'};}
#	    elsif ($wkendclr and $iswknd) { $bclr=$wkendclr;}
	    else { $bclr="$webcalConfig::r{'backgroundColor'}";}
	    $diary=hasdiary($iwho, "$pmonth/$pday/$pyear");
	    if($diary) { $diary = "<a href=\"$::o{'cginame'}?c=diary&w=$iwho&v=3&vd=1&ls=$ls&d=$pmonth/$pday/$pyear$::vmg\"><img src=\"$::o{'imgdirurl'}/diary.gif\" width=16 height=14 border=0 align=right></a>";} else {$diary="";}
	    my $ph=""; my $cbg="";
	    $stmp = oneDaySummary($pmonth, $pday, $pyear, $todayc, $webcalConfig::fontsize{'mdsummary'}, 1);
	    if($::cell_bg){ $cbg=&hack_cell_bg_style($bclr);}
	    if($dnd) {$dndid="id=\"$iwho:$pmonth/$pday/$pyear\"";}
	    $out .= "<td class=\"$id\" width=\"$percent%\" $dndid $dndop height=100 bgcolor=$bclr valign=top$cbg>";
	    if($webcalConfig::r{'moonphase'} and $::yeartable[$pday]) { 
		my $phase = $::yeartable[$pday];
		$ph = "<img src=\"$::o{'imgdirurl'}/mn$phase.gif\" width=11 height=11 border=0 align=right>";
	    } 
	    my $ae .="<a href=\"$::o{'cginame'}?c=ne&w=$iwho&k=1&v=3&ls=$ls&d=$pmonth/$pday/$pyear$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/add3.gif\" width=11 height=11 border=0 align=right></a>"; 
	    $out .= "$ae$ph$diary<a href=\"$::o{'cginame'}?c=get&w=$iwho&v=1&ls=$ls&d=$pmonth/$pday/$pyear$mg$::vmg\"><b><span class=\"mvDay\">$pday</span></b><br></a>";
	    $out .= "<font size=-2>".$stmp."</font>" if ($stmp);
	    $out .= "</td>";
	    $pday++;
	  }
	}
#      $stmp = "<td><br></td>" x $ucode;
	#      $out .= $stmp;
      }
      $offset = 32;
      $day = 1;
      while($day <= $ndays) {
	if($code % 7 == $::o{'weekstart'} && $day + $::o{'excludeWeekend'} > 1) {
	  $wknum = weekNum($imonth,$day+1,$iyear, $::o{'weekstart'}); %::scntr=(); $::scntr=1;
	  $out .= "</tr><tr><td align=center width=\"1%\" bgcolor=$wgclr class=\"mvCol1Td\"><a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=2&d=$imonth/$day/$iyear$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/right.gif\" width=11 height=11 border=0></a><br><font color=#ffff00 size=1><span class=\"mvCol1Txt\">$wknum</span></font></td>\n";
	}
	$ucode = $code % 7;
	if( ! $::o{'excludeWeekend'} || ( $ucode !=0 && $ucode !=6)) {
	  my $cbg=""; my $id="mvtd"; my $iswknd=($ucode == 0 or $ucode==6); if($iswknd){$id="mvtdwknd";}
	  $stmp = oneDaySummary($imonth, $day, $iyear, $todayc, $webcalConfig::fontsize{'mdsummary'}, 1);
	  if($dnd){$dndid="id=\"$iwho:$imonth/$day/$iyear\"";}
	  if( $tyr == $syr && $tmn == $smn && $tdy == $day) { 
	    if($::cell_bg){ $cbg=&hack_cell_bg_style($webcalConfig::r{'todayHcolor'});}
	    $out .="<td class=\"mvtdtdy\" width=\"$percent%\" $dndid $dndop height=100 bgcolor=$webcalConfig::r{'todayHcolor'} valign=top$cbg>";
#	  } elsif($wkendclr and $iswknd) {
#	    if($::cell_bg){ $cbg=&hack_cell_bg_style($wkendclr);}
#	    $out .= "<td class=\"$id\" width=\"$percent%\" $dndid $dndop height=100 bgcolor=$wkendclr valign=top$cbg>";
  	  } else {
	    if($::cell_bg){ $cbg=&hack_cell_bg_style("white");}
	    $out .= "<td class=\"$id\" width=\"$percent%\" $dndid $dndop height=100 bgcolor=#ffffff valign=top$cbg>";
	  }
	  my $diary = hasdiary($iwho, "$imonth/$day/$iyear/");
	  if($diary) {
	    $diary = "<a href=\"$::o{'cginame'}?c=diary&w=$iwho&v=3&vd=1&ls=$ls&d=$imonth/$day/$iyear$::vmg\"><img src=\"$::o{'imgdirurl'}/diary.gif\" width=16 height=14 border=0 align=right></a>";}
	  else {$diary="";}
	  my $ph="";
	  if($webcalConfig::r{'moonphase'} and $::yeartable[$offset]) {
	      my $phase = $::yeartable[$offset];
	      $ph = "<img src=\"$::o{'imgdirurl'}/mn$phase.gif\" width=11 height=11 border=0 align=right>";
	  } else {$ph = "";}
	  my $ae .="<a href=\"$::o{'cginame'}?c=ne&w=$iwho&k=1&v=3&ls=$ls&d=$imonth/$day/$iyear$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/add3.gif\" width=11 height=11 border=0 align=right></a>"; 
	  $out .= "$ae$ph$diary<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=1&d=$imonth/$day/$iyear$mg$::vmg\"><b><span class=\"mvDay\">$day</span></b><br></a>";
	  $out .= "<font size=-2>".$stmp."</font>" if ($stmp);
	  $out .= "</td>";
	}
	$code++;
	$day++;
	$offset++;
      }
      $ucode = $code % 7;
      $espace= ($ucode==0? ($::o{'weekstart'}? 6 : 0) : $ucode - $::o{'weekstart'});
      if($espace && $espace < $wklen) {
	my $extra;
	my $left = $wklen - $espace;
	if($left > 3) {  $extra = $left -1; } else {  $extra = $left; }
	$left = $left - $extra;
	($imonth, $day, $iyear) = canDate($imonth+1, 1, $iyear);
	$offset=63;
	for($i=0; $i<$extra; $i++) {
	  my ($bclr, $diary, $iswkend); $iswkend = $::o{'weekstart'} + $espace + $i;
	  my $cbg="";
	  $stmp = oneDaySummary($imonth, $day, $iyear, $todayc, $webcalConfig::fontsize{'mdsummary'}, 1);
	  $diary = hasdiary($iwho, "$imonth/$day/$iyear");
	  if($diary) {
	      $diary = "<a href=\"$::o{'cginame'}?c=diary&w=$iwho&vd=1&v=3&ls=$ls&d=$imonth/$day/$iyear$::vmg\"><img src=\"$::o{'imgdirurl'}/diary.gif\" width=16 height=14 border=0 align=right></a>";
	  } else { $diary="";}
	  my $id="mvtdnmth"; # if($iswkend==0 or $iswkend >= 6){ $id="mvtdwknd";}
	  if( $tyr == $iyear && $tmn == $imonth && $tdy == $day) { $bclr="$webcalConfig::r{'todayHcolor'}";$id="wvtdtdy";}
#	  elsif($::calinfo{'clr2'}) {$bclr=$::calinfo{'clr2'};}
#	  elsif ($wkendclr and ($iswkend==0 or $iswkend >= 6)) { $bclr=$wkendclr;}
	  else { $bclr="$webcalConfig::r{'backgroundColor'}";}
	  if($::cell_bg){ $cbg=&hack_cell_bg_style($bclr);}
	  if($dnd){$dndid="id=\"$iwho:$imonth/$day/$iyear\"";}
	  $out .= "<td class=\"$id\" width=\"$percent%\" $dndid $dndop height=100 bgcolor=$bclr valign=top$cbg>";
	  my $ph="";
	  if($webcalConfig::r{'moonphase'} and $::yeartable[$offset]) {
	      my $phase = $::yeartable[$offset];
	      $ph = "<img src=\"$::o{'imgdirurl'}/mn$phase.gif\" width=11 height=11 border=0 align=right>";
	  }
	  my $ae .="<a href=\"$::o{'cginame'}?c=ne&w=$iwho&k=1&v=3&ls=$ls&d=$imonth/$day/$iyear$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/add3.gif\" width=11 height=11 border=0 align=right></a>"; 
	  $out .= "$ae$ph$diary<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=1&d=$imonth/$day/$iyear$mg$::vmg\"><b><span class=\"mvDay\">$day</span></b><br></a>";
	  $out .= "<font size=-2>".$stmp."</font>" if ($stmp);
	  $out .= "</td>";
	  $day++;
	  $offset++;
	}
	if($left) {
	  my $bclr ="$webcalConfig::r{'backgroundColor'}";
	  #if($::calinfo{'clr2'}){$bclr=$::calinfo{'clr2'};}
	  #elsif($wkendclr){ $bclr= $wkendclr;}
	  $out .= "<td class=\"mvtdnmth\" bgcolor=$bclr align=center valign=middle>$webcalConfig::r{'cgiInfoA'}</td>";
	}
      }
      $out .= "</tr></table></td></tr></table>";
      return($out);
#  }
}

#=======================================================================================================
sub hack_cell_bg_style {
    my($bg,$x)=(@_);
    my $in = $::cell_bg;
    my $ans;
    if( $in =~ /^w\-(.+)\-sCs\-([^\s]+)/) {
	$in =~ s/\s.+//g; $ans=" class=\"$in\"";
    } else {
	if($in =~ /\\?\^o\^\/([^\s]+?)\.(gif|jpg|png|jpeg|bmp)/i) {
	    my $irepository = "$::o{'fimgdirurl'}/$::o{'uploadsubdir'}";
	    $in =~ s/\\?\^o\^\/([^\s]+?)\.(gif|jpg|png|jpeg|bmp)/ url($irepository\/$1\.$2)/ig;
	} elsif($in =~ /(http:\/\/[^\s]+?)\.(gif|jpg|png|jpeg|bmp)/i){
	    $in =~ s/(http:\/\/[^\s]+?)\.(gif|jpg|png|jpeg|bmp)/ url($1\.$2)/ig;
	}
        my $xpos="center"; if($x) { $xpos = $x;} 
	#$ans =" style=\"background: $bg $in no-repeat scroll center center\"";
	$ans =" style=\"background-image:$in;background-repeat:no-repeat;background-position: $xpos center\"";
    }
    return $ans;
}
#=======================================================================================================
sub mkSmallMCal {
    my ($imonth, $iday, $iyear, $dbgn, $dend, $twidth, $height, $ar, $size, $dkclr, $tblclr, $arrow, $pfx) = (@_);
    my ( $i, $offset, $jk, $pa, $pb, $pnt, $wklen, $code, $ucode, $ndays, $stmp, $itmp, $day, $view); 
    my ($ls, $iwho, $mg, $bse, $tyr, $tmn, $tdy, $out, $tsize, $ibse, $acmd, $tgt);
    $ls = $::calinfo{'ls'}; $ls=0 if not $ls;
    $view = $::calinfo{'v'};$view=2 if not $view;
    $iwho = $::calinfo{'w'};
    $pnt = $::calinfo{'pnt'};
    $code = wday($imonth, 1, $iyear);
    if(isleap($iyear)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}
    $ndays = $::mdays[$imonth];
    $tmn = $::now{'month'}; $tdy = $::now{'day'}; $tyr = $::now{'year'};
    if($size == 1) { $tsize = "size=1";} else {$tsize="size=2";}
    my $dnd = ($::vm & 0x1000) ? 0 : 1;
    my($dndid, $dndop)=("","");
    if($::o{'dnd'} and $pfx eq "" and $dnd) {
	if($::o{'dnd'}){ $dndop ="ondragenter=\"dnden()\" ondragover=\"dndov()\" ondragleave=\"dndlv()\" ondrop=\"dnddp()\"" ;}
    } else { $dnd=0;}

    if($::o{'excludeWeekend'}) { $wklen = 5; $pa = 5; $pb =19; } else { $pa = 2; $pb = 14; $wklen = 7;}

    if($::d{'megaCal'} ne "") {$mg="&mg=$::d{'megaCal'}"; } else {$mg="";}   
    if($::calinfo{'u_f_url'}){
	my $an="&anonymous=1"; #my $an=""; if($::d{'remote_user'} eq 'anonymous') {$an="&anonymous=1";}
	my $args=""; if($::calinfo{'cgi_args_nav'}) {$args=$::calinfo{'cgi_args_nav'};}
	$bse="$::o{'fcginame'}?c=get&ls=$ls&w=$iwho$an$mg$::vmg";$ibse=$::o{'fimgdirurl'}; $tgt="target=cal";
	$acmd="$::o{'fcginame'}?c=navigation_table&ls=$ls&w=$iwho$an$args$mg$::vmg";
    } else {
	$bse="$::o{'cginame'}?c=get&ls=$ls&w=$iwho$mg$::vmg"; $ibse=$::o{'imgdirurl'}; $acmd="get";
	$acmd=$bse; $tgt="";
    }
    if($arrow) {
	my($pm, $nm, $pd, $py, $ny, $mm, $yy);
	if($imonth == 11) { $nm = 0; $ny = $iyear+1;} else { $nm = $imonth+1; $ny = $iyear;}
	if($imonth == 0) { $pm = 11; $py = $iyear-1;} else { $pm = $imonth-1; $py = $iyear;}	
	$pd = $::mdays[$pm]; if($pm == 1 and isleap($py)) { $pd=29;}
	
	$out = "<center><table class=\"${pfx}Smvtbl\" border=0 cellspacing=0 cellpadding=0 width=\"100%\"><tr><td class=\"${pfx}SmvTdnav\" nowrap width=\"100%\" align=center><font size=2><b><a href=\"$acmd&v=$view&d=$pm/$pd/$py\"><span class=\"${pfx}SmvTitle\">&lt;&lt;&nbsp;</span></a></font>
<font size=2><a $tgt href=\"$bse&v=3&d=$imonth/1/$iyear\"><span class=\"${pfx}SmvTitle\">$::mname[$imonth] $iyear</span></a></font>
<font size=2><a href=\"$acmd&v=$view&d=$nm/1/$ny\"><span class=\"${pfx}SmvTitle\">&nbsp;&gt;&gt;</span></a></font></td></tr></table>
</center>";
    } else {
	$out = "<table class=\"${pfx}Smvtbl\" border=0 cellspacing=0 cellpadding=0 width=\"100%\" bgcolor=#ffffff><tr><td class=\"${pfx}SmvTdnav\" width=\"100%\" align=center><font size=2><a $tgt href=\"$bse&v=3&d=$imonth/1/$iyear\"><span class=\"${pfx}SmvTitle\">$::mname[$imonth] $iyear</span></a></font></td></tr></table>\n";
    }
    if(!$tblclr or $pnt) {$out .= "<table border=1 cellpadding=0 cellspacing=0 $twidth class=\"${pfx}Smvtbl\">";}
    else {$out .= "<table border=0 cellpadding=0 cellspacing=1 $twidth class=\"${pfx}Smvtbl\">"; }

    $out .="<tr><td align=center bgcolor=$dkclr width=\"$pa%\" class=\"${pfx}SmvRow1Td\"><font size=1><i>&nbsp;</i></font></td>";

    for($i = 0; $i < $wklen; $i++) {
	$out .= "<td bgcolor=$dkclr width=\"$pb%\" align=center class=\"${pfx}SmvRow1Td\"><font color=#ffffff $tsize><span class=\"${pfx}SmvRow1Txt\">$::swd[$::o{'weekstart'}+$i]</span></font></td>";
    }
    $out .= "</tr>\n";
    $ucode = ($code) % 7;
    if( ! $::o{'excludeWeekend'} || ( $ucode >$::o{'weekstart'} && $ucode <=5)) {
	$stmp = "<tr><td width=\"$pa%\" align=center bgcolor=$dkclr class=\"${pfx}SmvCol1Td\"><a $tgt href=\"$bse&v=2&d=$imonth/1/$iyear\"><img src=\"$ibse/lright.gif\" width=8 height=8 border=0></a></td>";
	$out .= $stmp;
	if($::o{'weekstart'}) { $ucode = ($code==0? 6: $code - $::o{'weekstart'}); } else {$ucode = $code;}
	$stmp = "<td  class=\"${pfx}SmvTdout\" width=\"$pb%\" bgcolor=$webcalConfig::r{'backgroundColor'}><font size=1>&nbsp;</font></td>" x $ucode;
	$out .= $stmp;
	$itmp=1;
    }
    $day = 1; $i = 0;
    $offset = $imonth * 31;
    my $dkbg; if($view==4) {$dkbg = " bgcolor=#f0f0f0";} else { $dkbg =" bgcolor=#f9f9f6";}
    while($day <= $ndays) {
	if($code % 7 == $::o{'weekstart'} && $day + $::o{'excludeWeekend'} > 1) {
	    if($itmp) { $out .= "</tr>\n";}
	    $out .= "<tr><td width=\"$pa%\" bgcolor=$dkclr class=\"${pfx}SmvCol1Td\"><a $tgt href=\"$bse&v=2&d=$imonth/$day/$iyear\"><img src=\"$ibse/lright.gif\" width=8 height=8 border=0></a></td>\n";
	    $itmp++; $i = 0;
	}
	my ($ucode, $key);
	$key = $::yeartable[$offset + $day];
	$ucode = $code % 7;
	if($dnd){$dndid="id=\"$iwho:$imonth/$day/$iyear\"";}
	if( ! $::o{'excludeWeekend'} || ( $ucode !=0 && $ucode !=6)) {
	    my ($ba, $bb, $fclr)=("","", "");
	    if($key) {
		if($key > 1 ) {
		    my $tmp = (($key - 1) & 0x1f); 
		    my $clr = $webcalConfig::r{'txtColors'}->[$tmp];
		    $fclr = " color=$clr";
		    $ba = "<b>"; $bb="</b>";
		} else {
		    $fclr = " color=#ff0000";
		    if($pnt) {$ba = "<b>"; $bb="</b>";}
		}
	    } 
	    if( $day == $tdy && $tyr == $iyear && $tmn == $imonth) {
		$out .= "<td class=\"${pfx}SmvTdtdy\" $height width=\"$pb%\" bgcolor=$webcalConfig::r{'todayHcolor'} align=right nowrap $dndid $dndop>";
		$ba = "<font color=#666600><b>"; $bb="</b></font>";
	    } elsif( $day <= $dend && $day >= $dbgn) {
		$out .= "<td $height width=\"$pb%\" bgcolor=#ccccff align=right nowrap class=\"${pfx}SmvTd\" $dndid $dndop>";
	    } elsif($key > 1) {
		$out .= "<td $height width=\"$pb%\"$dkbg align=right nowrap class=\"${pfx}SmvTd\" $dndid $dndop>";		
	    } else {
		$out .= "<td $height width=\"$pb%\" bgcolor=#ffffff align=right nowrap class=\"${pfx}SmvTd\" $dndid $dndop>";
	    }
	    $out .="<a $tgt href=\"$bse&v=1&d=$imonth/$day/$iyear\"><font $tsize$fclr><span class=\"${pfx}SmvDay\">&nbsp;$ba$day$bb&nbsp;</span></font></a></td>";
	    $i++;
	}
	$day++;
	$code++;
    }
    for(;$i<$wklen; $i++) {
	$out .= "<td class=\"${pfx}SmvTdout\"  width=\"$pb%\" bgcolor=$webcalConfig::r{'backgroundColor'}><font size=1>&nbsp;</font></td>";
    };
    $itmp += $::o{'excludeWeekend'};
    if($ar) {
	for(; $itmp <6; $itmp++) {$out .= "<tr><td width=\"$pa%\" bgcolor=$dkclr class=\"${pfx}SmvCol1Td\"><font size=1>&nbsp;</font></td>". "<td class=\"${pfx}SmvTdout\" bgcolor=$webcalConfig::r{'backgroundColor'} width=\"$pb%\" $height><font size=1>&nbsp;</font></td>" x $wklen . "</tr>\n";}
    }
    $out .= "</table>";
    return($out);
}
#=======================================================================================================
sub navigation_table {
    my ($month, $day, $year, $tbl, $arrow, $width, $height, $gcolor, $ccolor, $bcolor, $args, $scolor);
    $month= $::calinfo{'month'};
    $day  = $::calinfo{'day'};
    $year = $::calinfo{'year'};
    $args="";
    if($::calinfo{'noarrow'}) { $arrow = 0; $args .="&noarrow=1";} else {$arrow=1;}
    if($::calinfo{'width'}) {$width =$::calinfo{'width'}; $args .="&width=$width";} else {$width="";}
    if($::calinfo{'height'}) {$height =$::calinfo{'height'};$args .="&height=$height";} else {$height="";}
    if($::calinfo{'cellcolor'}) {$ccolor =$::calinfo{'cellcolor'};$args.="&cellcolor=$ccolor";} 
    else {$ccolor='#cccccc';}
    if($::calinfo{'gridcolor'}) {$gcolor =$::calinfo{'gridcolor'};$args .="&gridcolor=$gcolor";} 
    else {$gcolor='ccccff';}
#    if($::calinfo{'bgcolor'}) {$bcolor =$::calinfo{'bgcolor'};$args .="&bgcolor=$bcolor";} else {$bcolor="white";}
    $bcolor="white";
    &readData;         
    make3MonthTable($month, $year,1);
    $::calinfo{'u_f_url'} = 1;
    if($width){$width="width=$width";} if($height){ my $tmp = int($height/7); $height="height=$tmp" if $tmp;}
    if($args) {$::calinfo{'cgi_args_nav'}=$args;}
    if($bcolor) { $scolor=$webcalConfig::r{'backgroundColor'}; $webcalConfig::r{'backgroundColor'} = $bcolor;}
    $tbl = mkSmallMCal($month, $day, $year, 0, 0, $width, $height, 0, 1, $ccolor, 1, $arrow, "nav");
    &headers("webcal","");
    if($bcolor) { $webcalConfig::r{'backgroundColor'} = $scolor;}    
    print "<table border=0><tr valign=middle><td bgcolor=$gcolor align=center>$tbl</td></tr></table>";
    &trailer(0,0);
}
#=======================================================================================================
sub make3MonthTable { # flag those days in month-1, month, month+1 in which some events has been booked.
  my ($offset, $ndays, $i, $month, $year, $kind, $edate, $href, $dmonth);
  my ($endM, $endD, $endY, $today, $cached, $who, $count);
  ($month, $year, $count) = (@_); 
  $year = untaintname($year,$::phr{'invalid_date'});
  $who = $::calinfo{'w'};
  $cached = 0;
  if(not $::d{'megaCal'}) { # see if we have the table cached
      $ = time;
      if($count <= 1 or ($month > 0 and $month < 11)) { 
	  my ($datm, $yttm, $cf);

	  $cf = "$::o{'spooldir'}/$who/cache/yt-$year";
	  if( -f "$cf") {
	      $yttm = -M "$cf";
	      $datm = -M "$::o{'spooldir'}/$who/data";
	      if( $yttm <= $datm) {
                  &doReadFile("$cf");
		  $cached = 1;
	      }
	  }
      } elsif ($month == 0) {
	  my ($cfp, $cf, $pyear, $datm, $yttm, $pyttm, @tmp, $i);
	  $pyear = $year -1; $pyear=untaintname($pyear,"");
	  $cfp = "$::o{'spooldir'}/$who/cache/yt-$pyear";	  
	  $cf = "$::o{'spooldir'}/$who/cache/yt-$year";	  
	  if( -f $cfp and -f $cf) {
	      $datm = -M "$::o{'spooldir'}/$who/data";
	      $yttm = -M "$cf";	      
	      $pyttm = -M "$cfp";
	      if( $yttm <= $datm and $pyttm <= $datm) {
                  &doReadFile("$cfp");
		  @tmp = @::yeartable;
                  &doReadFile("$cf");
		  for($i=342; $i <= 372; $i++) { $::yeartable[$i] = $tmp[$i];}
		  $cached = 1;
	      }
	  }
      } else {
	  my ($cfn, $cf, $nyear, $datm, $yttm, $nyttm, @tmp, $i);
	  $nyear = $year + 1; $nyear=untaintname($nyear,"");
	  $cfn = "$::o{'spooldir'}/$who/cache/yt-$nyear";	  
	  $cf = "$::o{'spooldir'}/$who/cache/yt-$year";	  
	  if( -f $cfn and -f $cf) {
	      $datm = -M "$::o{'spooldir'}/$who/data";
	      $yttm = -M "$cf";	      
	      $nyttm = -M "$cfn";
	      if( $yttm <= $datm and $nyttm <= $datm) {
                  &doReadFile("$cfn");
		  @tmp = @::yeartable;
                  &doReadFile("$cf");
		  for($i=1; $i <= 31; $i++) { $::yeartable[$i] = $tmp[$i];}
		  $cached = 1;
	      }
	  }
      }
  }
  
  if($cached == 0) {
      @::yeartable = map(0,(0..372));
      if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;} 
      my (@ms, @yrs, @days, $amonth, @offsets, $ayear, $j);
      if($month == 0) {
	  @yrs=($year-1, $year, $year); @ms = (11,0,1); @days=(31, 31, $::mdays[1]);
	  @offsets=(341, 0, 31);
	  $amonth = 11; $ayear = $year-1;
      } elsif($month == 11) {
	  @yrs=($year, $year, $year+1); @ms = (10,11,0); @days=(30, 31,31);
	  @offsets=(310, 341, 0);
	  $amonth = 10; $ayear = $year;
      } else {
	  @yrs=($year, $year, $year); @ms = ($month-1,$month,$month+1); 
	  @days=($::mdays[$month-1],$::mdays[$month],$::mdays[$month+1]);
	  my $tmp = ($month -1) * 31;
	  @offsets = ($tmp, $tmp+31, $tmp+62);
	  $amonth = $month-1; $ayear = $year;
      }
      for($i=1; $i <= 371; $i++) { $::yeartable[$i] = 0;}

      if(not $::d{'megaCal'}) { my $o=untaintname($who, ""); doReadFile("$::o{'spooldir'}/$o/data");}
      
      for $href (@::caldata) {
	  next if $href->{'deleted'};
	  if($href->{'end'}) {
	      ($endM, $endD, $endY) = split(/\//, $href->{'end'}); $endM--;
	      next if $ayear > $endY;
	      next if $ayear == $endY and $amonth > $endM;
	  }
	  $kind = $href->{'kind'};
	  if($kind == 2 or $kind == 4) {		# todo event,
	      next if( defined $href->{'done'} and $href->{'done'} eq 'y');	# do not display completed tasks
	  }
	  my $save_me = ($kind == 4);
	  my $mkind; if($::calinfo{'dctoc'}) { $mkind = $kind;} else {$mkind = 0;}	  
          my ($bgnm, $endm);
          if($count <= 1) { $bgnm=1; $endm=2;} else {$bgnm=0; $endm=3;}
	  for($j = $bgnm; $j < $endm; $j++) {
	      my($dmonth, $dyear, $ddays, $offset);
	      $dmonth = 1+$ms[$j]; $dyear = $yrs[$j]; $ddays = $days[$j]; $offset = $offsets[$j];
	      for($i = 1; $i <= $ddays; $i++) {
		  $today = "$dmonth/$i/$dyear";
		  if($::yeartable[$offset+$i] == 0 or $save_me) {
		      if(calmatch($today, $href->{'date'}, $href->{'occurs'}, $href->{'repeat'}, $href->{'exception'},$mkind)) {
			  if($save_me) { $::yeartable[$offset+$i] = 1 + $href->{'key'};}
			  else {$::yeartable[$offset+$i] = 1;}
		      }
		  }
	      }
	  }
      }
  }
}
#=====================================================================================================
sub make3MonthTableSrch { # flag those days in month-1, month, month+1 in which some events has been booked.
  my ($offset, $ndays, $i, $month, $year, $kind, $edate, $href, $dmonth);
  my ($endM, $endD, $endY, $today, $who, $count, $eprivacy);
  ($month, $year, $count) = (@_); 
  $year = untaintname($year,$::phr{'invalid_date'});
  $who = $::calinfo{'w'};
  my ($gprivacy, $mg) = &getPrivacy(1);
  
  @::yeartable = map(0,(0..372));
  if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;} 
  my (@ms, @yrs, @days, $amonth, @offsets, $ayear, $j);
  if($month == 0) {
      @yrs=($year-1, $year, $year); @ms = (11,0,1); @days=(31, 31, $::mdays[1]);
      @offsets=(341, 0, 31);
      $amonth = 11; $ayear = $year-1;
  } elsif($month == 11) {
      @yrs=($year, $year, $year+1); @ms = (10,11,0); @days=(30, 31,31);
      @offsets=(310, 341, 0);
      $amonth = 10; $ayear = $year;
  } else {
      @yrs=($year, $year, $year); @ms = ($month-1,$month,$month+1); 
      @days=($::mdays[$month-1],$::mdays[$month],$::mdays[$month+1]);
      my $tmp = ($month -1) * 31;
      @offsets = ($tmp, $tmp+31, $tmp+62);
      $amonth = $month-1; $ayear = $year;
  }
  for($i=1; $i <= 371; $i++) { $::yeartable[$i] = 0;}
  if(not $::d{'megaCal'}) { my $o=untaintname($who, ""); doReadFile("$::o{'spooldir'}/$o/data");}
      
  for $href (@::caldata) {
      next if $href->{'deleted'};
      if($href->{'end'}) {
	  ($endM, $endD, $endY) = split(/\//, $href->{'end'}); $endM--;
	  next if $ayear > $endY;
	  next if $ayear == $endY and $amonth > $endM;
      }
      if($gprivacy > 3) { $eprivacy = 3;}
      else {
	  if(defined $href->{'e'} or (defined $href->{'w'} and $href->{'w'} eq $::d{'remote_user'})) { $eprivacy = 3;} #for megaCalendar
	  elsif(defined $href->{'privacy'}) { $eprivacy = $::privacyTable{$href->{'privacy'}} -1;}
	  else {$eprivacy = $gprivacy;}
      }
      next if ($eprivacy == 0);
      my ($bgnm, $endm);
      if($count <= 1) { $bgnm=1; $endm=2;} else {$bgnm=0; $endm=3;}
      for($j = $bgnm; $j < $endm; $j++) {
	  my($dmonth, $dyear, $ddays, $offset);
	  $dmonth = 1+$ms[$j]; $dyear = $yrs[$j]; $ddays = $days[$j]; $offset = $offsets[$j];
	  for($i = 1; $i <= $ddays; $i++) {
	      $today = "$dmonth/$i/$dyear";
	      if(calmatch($today, $href->{'date'}, $href->{'occurs'}, $href->{'repeat'}, $href->{'exception'},$href->{'kind'})) {
		  if($href->{'ycm'} or match_search_words($href,$eprivacy)) {
		      $href->{'ycm'} = 1; $::yeartable[$offset+$i] += 1;
		  }
	      }
	  }
      }
  }
}
#======================================================================================================
sub make3MonthTableFilter { # flag those days in month-1, month, month+1 in which some events has been booked.
  my ($offset, $ndays, $i, $month, $year, $kind, $edate, $href, $dmonth);
  my ($endM, $endD, $endY, $today, $cached, $who, $count);
  ($month, $year, $count) = (@_); 
  $year = untaintname($year,$::phr{'invalid_date'});
  $who = $::calinfo{'w'};
  $cached = 0;
  if(not $::d{'megaCal'}) { # see if we have the table cached
      $ = time;
      if($count <= 1 or ($month > 0 and $month < 11)) { 
	  my ($datm, $yttm, $cf);

	  $cf = "$::o{'spooldir'}/$who/cache/fyt-$year";
	  if( -f "$cf") {
	      $yttm = -M "$cf";
	      $datm = -M "$::o{'spooldir'}/$who/data";
	      if( $yttm <= $datm) { &doReadFile("$cf"); $cached = 1;@::yeartable = map(0,(0..372));}
	      my ($key, $tref);
	      for $key (keys %::filtertable) {
		  if($key =~ /^\s*$::catfilterpattern\s*$/i) {
		      $tref = $::filtertable{$key};
		      for($i=0; $i<372; $i++) { $::yeartable[$i]= $tref->[$i];}
		      last;
		  }
	      }
	  }
      } elsif ($month == 0) {
	  my ($cfp, $cf, $pyear, $datm, $yttm, $pyttm, @tmp, $i);
	  $pyear = $year -1; $pyear=untaintname($pyear,"");
	  $cfp = "$::o{'spooldir'}/$who/cache/fyt-$pyear";	  
	  $cf = "$::o{'spooldir'}/$who/cache/fyt-$year";	  
	  if( -f $cfp and -f $cf) {
	      $datm = -M "$::o{'spooldir'}/$who/data";
	      $yttm = -M "$cf"; $pyttm = -M "$cfp";
	      if( $yttm <= $datm and $pyttm <= $datm) {
		  $cached = 1; @::yeartable = map(0,(0..372));
                  &doReadFile("$cf");
		  my ($key, $tref);
		  for $key (keys %::filtertable) {
		      if($key =~ /^\s*$::catfilterpattern\s*$/i) {
			  $tref = $::filtertable{$key};
			  for($i=0; $i<62; $i++) { $::yeartable[$i]= $tref->[$i];}
			  last;
		      }
		  }
                  &doReadFile("$cfp");
		  for $key (keys %::filtertable) {
		      if($key =~ /^\s*$::catfilterpattern\s*$/i) {
			  $tref = $::filtertable{$key};
			  for($i=342; $i<=372; $i++) { $::yeartable[$i]= $tref->[$i];}
			  last;
		      }
		  }
	      }
	  }
      } else {
	  my ($cfn, $cf, $nyear, $datm, $yttm, $nyttm, @tmp, $i);
	  $nyear = $year + 1; $nyear=untaintname($nyear,"");
	  $cfn = "$::o{'spooldir'}/$who/cache/fyt-$nyear";	  
	  $cf = "$::o{'spooldir'}/$who/cache/fyt-$year";	  
	  if( -f $cfn and -f $cf) {
	      $datm = -M "$::o{'spooldir'}/$who/data";
	      $yttm = -M "$cf";	 $nyttm = -M "$cfn";
	      @::yeartable = map(0,(0..372));
	      if( $yttm <= $datm and $nyttm <= $datm) {
                  $cached = 1;  &doReadFile("$cf");
		  my ($key, $tref);
		  for $key (keys %::filtertable) {
		      if($key =~ /^\s*$::catfilterpattern\s*$/i) {
			  $tref = $::filtertable{$key};
			  for($i=32; $i<=372; $i++) { $::yeartable[$i]= $tref->[$i];}
			  last;
		      }
		  }
                  &doReadFile("$cfn");
		  for $key (keys %::filtertable) {
		      if($key =~ /^\s*$::catfilterpattern\s*$/i) {
			  $tref = $::filtertable{$key};
			  for($i=1; $i<=31; $i++) { $::yeartable[$i]= $tref->[$i];}
			  last;
		      }
		  }
	      }
	  }
      }
  }
  
  if($cached == 0) {
      @::yeartable = map(0,(0..372));
      if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;} 
      my (@ms, @yrs, @days, $amonth, @offsets, $ayear, $j);
      if($month == 0) {
	  @yrs=($year-1, $year, $year); @ms = (11,0,1); @days=(31, 31, $::mdays[1]);
	  @offsets=(341, 0, 31);
	  $amonth = 11; $ayear = $year-1;
      } elsif($month == 11) {
	  @yrs=($year, $year, $year+1); @ms = (10,11,0); @days=(30, 31,31);
	  @offsets=(310, 341, 0);
	  $amonth = 10; $ayear = $year;
      } else {
	  @yrs=($year, $year, $year); @ms = ($month-1,$month,$month+1); 
	  @days=($::mdays[$month-1],$::mdays[$month],$::mdays[$month+1]);
	  my $tmp = ($month -1) * 31;
	  @offsets = ($tmp, $tmp+31, $tmp+62);
	  $amonth = $month-1; $ayear = $year;
      }
      if(not $::d{'megaCal'}) { my $o=untaintname($who, ""); doReadFile("$::o{'spooldir'}/$o/data");}
      for $href (@::caldata) {
	  next if $href->{'deleted'};
	  next if not &$::catfiltersub($href->{'cat'});
	  if($href->{'end'}) {
	      ($endM, $endD, $endY) = split(/\//, $href->{'end'}); $endM--;
	      next if $ayear > $endY;
	      next if $ayear == $endY and $amonth > $endM;
	  }
	  $kind = $href->{'kind'};
	  if($kind == 2 or $kind == 4) {		# todo event,
	      next if( defined $href->{'done'} and $href->{'done'} eq 'y');	# do not display completed tasks
	  }
	  my $save_me = ($kind == 4);
	  my $mkind; if($::calinfo{'dctoc'}) { $mkind = $kind;} else {$mkind = 0;}	  
          my ($bgnm, $endm);
          if($count <= 1) { $bgnm=1; $endm=2;} else {$bgnm=0; $endm=3;}
	  for($j = $bgnm; $j < $endm; $j++) {
	      my($dmonth, $dyear, $ddays, $offset);
	      $dmonth = 1+$ms[$j]; $dyear = $yrs[$j]; $ddays = $days[$j]; $offset = $offsets[$j];
	      for($i = 1; $i <= $ddays; $i++) {
		  $today = "$dmonth/$i/$dyear";
		  if($::yeartable[$offset+$i] == 0 or $save_me) {
		      if(calmatch($today, $href->{'date'}, $href->{'occurs'}, $href->{'repeat'}, $href->{'exception'},$mkind)) {
			  if($save_me) { $::yeartable[$offset+$i] = 1 + $href->{'key'};}
			  else {$::yeartable[$offset+$i] = 1;}
		      }
		  }
	      }
	  }
      }
  }
}

#=====================================================================================================
sub makeYearTable {
  my ($offset, $ndays, $i, $month, $kind, $edate, $href, $dmonth);
  my ($endM, $endD, $endY, $today, $cached, $save);
  my ($year, $spooldir, $who, $megaCal, $dctoc) = (@_);

  if($spooldir =~ /^(.+)$/) { $spooldir = $1;}
  $who = untaintname($who);
  @::ydata = ();
  $cached = 0; $save = 0;
  if(not $megaCal) { # see if we have the table cached
      my ($datm, $yttm, $ydtm, $cf, $df);
      $save = 1;
      $year = untaintname($year,$::phr{'invalid_date'});
      $cf = "$spooldir/$who/cache/yt-$year";
      $df = "$spooldir/$who/cache/y-$year";
      if( -f "$cf" and -f "$df" ) {
	  $ = time;
	  $yttm = -M "$cf"; 
	  $datm = -M "$spooldir/$who/data";
	  if( $yttm <= $datm) {
              &doReadFile("$cf");
	      &doReadFile("$df"); $::year_special_cached=1;
	      $cached = 1;
	  }
      }
  }

  if($cached == 0) {
      if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}
      @::yeartable = map(0,(0..372));

      for $href (@::caldata) {
	  next if $href->{'deleted'};
	  if($href->{'end'}) {
	      ($endM, $endD, $endY) = split(/\//, $href->{'end'}); $endM--;
	      next if $year > $endY;
	  }
	  $kind = $href->{'kind'};
	  if($kind == 2 or $kind == 4) {		# todo event,
	      next if(defined $href->{'done'} and $href->{'done'} eq 'y');	# do not display completed tasks
	  }
	  my $save_me = ($kind == 4);
	  my $mkind; if($dctoc) { $mkind = $kind;} else {$mkind = 0;}	  
	  for($offset=0, $dmonth = 1; $dmonth <=12; $dmonth++, $offset += 31 ) {
	      $ndays = $::mdays[$dmonth-1];
	      for($i = 1; $i <= $ndays; $i++) {
		  my $cv = $::yeartable[$offset+$i];
		  if($cv == 0 or $save_me) {
		      $today = "$dmonth/$i/$year";
		      if(calmatch($today, $href->{'date'}, $href->{'occurs'}, $href->{'repeat'}, $href->{'exception'},$mkind)) {
			  if($save_me) {
			      $::yeartable[$offset+$i] = 1 + $href->{'key'}; $href->{'ycm'} = 1;
			  } else {
			      $::yeartable[$offset+$i] = 1;
			  }
		      }
		  }
	      }
	  }
      }
      if($save) {
	  my ($fname);
	  $year = untaintname($year,$::phr{'invalid_date'});
	  $fname = "$spooldir/$who/cache/yt-$year";
	  my $content =  '@::yeartable=(' .  join(',', @::yeartable) . ');';
	  write_file($fname, $content);
	  # save special events
	  $fname = "$spooldir/$who/cache/y-$year";
	  my $fhy = gensym;
	  if(sysopen($fhy, "$fname", O_WRONLY | O_CREAT, 0644)) {
	      &webcalLock::doflock( \*$fhy, LOCK_EX, "$fname")  or calerror("Cannot lock file '$fname': $!\n",1);
	      truncate($fhy, 0);
	      print $fhy '@::ydata=(', "\n";
	      for $href (@::caldata) { 
		  if(defined $href->{'ycm'}) {
		      delete  $href->{'ycm'};
		      my $tmp = print1Entry($href);
		      print $fhy $tmp;
		      $href->{'ycm'}=1;
		  }      
	      }
	      print $fhy ");\n1;\n";
	      &webcalLock::doflock( \*$fhy, LOCK_UN, "$fname") or calerror("Cannot unlock file '$fname': $!\n",1);
	      close $fhy;
	  }
	  # end saving special events
      }
  }
}

#=============================================================================================================

sub makeYearTableSrch {
  my ($year, $spooldir, $who, $megaCal, $dctoc) = (@_);
  my ($offset, $ndays, $i, $month, $kind, $edate, $href, $dmonth);
  my ($endM, $endD, $endY, $today, $eprivacy);

  if($spooldir =~ /^(.+)$/) { $spooldir = $1;}
  $who = untaintname($who);
  my ($gprivacy, $mg) = &getPrivacy(1);

  if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}
  @::yeartable = map(0,(0..372));
      
  for $href (@::caldata) {
      next if $href->{'deleted'};
      if($href->{'end'}) {
	  ($endM, $endD, $endY) = split(/\//, $href->{'end'}); $endM--;
	  next if $year > $endY;
      }
      if($gprivacy > 3) { $eprivacy = 3;}
      else {
	  if(defined $href->{'e'} or (defined $href->{'w'} and $href->{'w'} eq $::d{'remote_user'})) { $eprivacy = 3;} #for megaCalendar
	  elsif(defined $href->{'privacy'}) { $eprivacy = $::privacyTable{$href->{'privacy'}} -1;}
	  else {$eprivacy = $gprivacy;}
      }
      next if ($eprivacy == 0);
	  
      for($offset=0, $dmonth = 1; $dmonth <=12; $dmonth++, $offset += 31 ) {
	  $ndays = $::mdays[$dmonth-1];
	  for($i = 1; $i <= $ndays; $i++) {
	      $today = "$dmonth/$i/$year";
	      if(calmatch($today, $href->{'date'}, $href->{'occurs'}, $href->{'repeat'}, $href->{'exception'},$href->{'kind'})) {
		  if($href->{'ycm'} or match_search_words($href,$eprivacy)) {
		      $href->{'ycm'} = 1;   $::yeartable[$offset+$i] += 1;
		  }
	      }
	  }
      }
  }
}
#=====================================================================================================
sub makeYearTableFilter {
  my ($offset, $ndays, $i, $month, $kind, $edate, $href, $dmonth);
  my ($endM, $endD, $endY, $today, $cached, $save );
  my ($year, $spooldir, $who, $megaCal, $dctoc) = (@_);

  if($spooldir =~ /^(.+)$/) { $spooldir = $1;}
  $who = untaintname($who);
  @::ydata = ();
  $cached = 0; $save = 0;
  if(not $megaCal) { # see if we have the table cached
      my ($datm, $yttm, $cf, $df);
      $save = 1;
      $year = untaintname($year,$::phr{'invalid_date'});
      $cf = "$spooldir/$who/cache/fyt-$year";
      $df = "$spooldir/$who/data";
      if( -f "$cf" and -f "$df" ) {
	  $ = time;
	  $yttm = -M "$cf"; 
	  $datm = -M "$df";
	  if( $yttm <= $datm) {
              &doReadFile("$cf"); $::year_special_cached=1;
	      $cached = 1;  @::yeartable = map(0,(0..372));
	      my ($key, $tref);
	      for $key (keys %::filtertable) {
		  if($key =~ /^\s*$::catfilterpattern\s*$/i) {
		      $tref = $::filtertable{$key};
		      for($i=0; $i<372; $i++) { $::yeartable[$i]= $tref->[$i];}
		      last;
		  }
	      }
	  }
      }
  }

  if($cached == 0) {
      if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}
      @::yeartable = map(0,(0..372));
      if($save) {
	  my %allcats = (); my $cat;
	  for $href (@::caldata) {
	      next if $href->{'deleted'};
	      $cat = $href->{'cat'} || "";
	      if(!$allcats{$cat}) {$allcats{$cat} = [ map(0,(0..372)) ];}
	      my $thistable = $allcats{$cat};
	      if($href->{'end'}) {
		  ($endM, $endD, $endY) = split(/\//, $href->{'end'}); $endM--;
		  next if $year > $endY;
	      }
	      $kind = $href->{'kind'};
	      if($kind == 2 or $kind == 4) {		# todo event,
		  next if(defined $href->{'done'} and $href->{'done'} eq 'y');	# do not display completed tasks
	      }
	      my $mkind; if($dctoc) { $mkind = $kind;} else {$mkind = 0;}
	      for($offset=0, $dmonth = 1; $dmonth <=12; $dmonth++, $offset += 31 ) {
		  $ndays = $::mdays[$dmonth-1];
		  for($i = 1; $i <= $ndays; $i++) {
		      my $cv = $thistable->[$offset+$i];
		      if($cv == 0) {
			  $today = "$dmonth/$i/$year";
			  if(calmatch($today, $href->{'date'}, $href->{'occurs'}, $href->{'repeat'}, $href->{'exception'},$mkind)) {
			      $thistable->[$offset+$i] = 1;
			  }
		      }
		  }
	      }
	  }
	  my ($fname,$key, $tref); $tref="";
	  $year = untaintname($year,$::phr{'invalid_date'});
	  $fname = "$spooldir/$who/cache/fyt-$year";
	  my $content =  "\%::filtertable=(\n";
	  for $key (keys %allcats) {
	      my $v = '[' . join(',', @{$allcats{$key}}) . "],\n";
	      if($key =~ /^\s*$::catfilterpattern\s*$/i) { $tref = $allcats{$key};}
	      $key =~ s/\'/\\\'/g;
	      $content .= "\'$key\'=> $v";
	  }
	  $content .= ");1;\n";
	  if($tref) { for($i=0; $i<372; $i++) { $::yeartable[$i]= $tref->[$i];}}
	  write_file($fname, $content);
      } else {
	  for $href (@::caldata) {
	      next if $href->{'deleted'};
	      my $cat = $href->{'cat'};
	      next if $cat !~ /^\s*$::catfilterpattern\s*$/i;
	      if($href->{'end'}) {
		  ($endM, $endD, $endY) = split(/\//, $href->{'end'}); $endM--;
		  next if $year > $endY;
	      }
	      $kind = $href->{'kind'};
	      if($kind == 2 or $kind == 4) {		# todo event,
		  next if(defined $href->{'done'} and $href->{'done'} eq 'y');	# do not display completed tasks
	      }
	      my $mkind; if($dctoc) { $mkind = $kind;} else {$mkind = 0;}
	      for($offset=0, $dmonth = 1; $dmonth <=12; $dmonth++, $offset += 31 ) {
		  $ndays = $::mdays[$dmonth-1];
		  for($i = 1; $i <= $ndays; $i++) {
		      my $cv = $::yeartable[$offset+$i];
		      if($cv == 0) {
			  $today = "$dmonth/$i/$year";
			  if(calmatch($today, $href->{'date'}, $href->{'occurs'}, $href->{'repeat'}, $href->{'exception'},$mkind)) {
			      $::yeartable[$offset+$i] = 1;
			  }
		      }
		  }
	      }
	  }
      }
  }
}

#=====================================================================================================
sub dayCal {
  my ($pmonth, $nmonth, $month, $day, $year,$pout, $tout, $nout, $dcal, $iwho, $out, $todayc, $pa, $pb, $ls, $diary, $stmp);
  my ($pnt, $detail, $mg, $ss, $dflag, $nbclr, $vmg);
  ($month, $day, $year) = (@_);
  $iwho = $::calinfo{'w'};
  $ls = $::calinfo{'ls'};
  $pnt = $::calinfo{'pnt'};
  if($::catfilterpattern) { make3MonthTableFilter($month, $year, 3);}
  elsif($::srchftrptn) {  make3MonthTableSrch($month, $year, 3);}
  else {make3MonthTable($month, $year, 3);}

  if($pnt or ($::vm & 0x100)) {
      $pout=$tout=$nout="<br>";
      $pa=1; $pb=99;$nbclr="";
  } else {
      $pout = monthCal($month-1, 0, $year, 2, 0);
      $tout = monthCal($month,  $day, $year, 2, 0);
      $nout = monthCal($month+1, 0, $year, 2, 0);
#      if($::o{'excludeWeekend'}) { $pa = 24; $pb = 75;} else {$pa=29; $pb = 70;}
      if($::o{'excludeWeekend'}) { $pa = 15; $pb = 84;} else {$pa=20; $pb = 79;}  $nbclr="bgcolor=\"#c0cccf\"";
  }
    
  if($::d{'megaCal'}) {
      $mg="&mg=$::d{'megaCal'}"; 
      $vmg="<input type=hidden name=mg value=\"$::d{'megaCal'}\">";
  } else {$mg= ""; $vmg="";}
  my ($nextc, $prevc, $search);
  if(!($::vm & 0x70000) and $::calinfo{'dayview'}) { $::vm |= (0 + $::calinfo{'dayview'});}
  if($::vm & 0x30000) {
	  $detail=<<END;
<a href="$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=1&ddetail=n&d=$month/$day/$year/9/0$mg$::vmg"><img src="$::o{'imgdirurl'}/en.gif" width=11 height=11 border=0 title="$::phr{'CombinedView'}" alt="$::phr{'CombinedView'}"></a><font size=1>&nbsp;</font>
END
    ;
      } else {
	  $detail=<<END;
<img src="$::o{'imgdirurl'}/enn.gif" width=11 height=11 border=0 title="$::phr{'CombinedView'}" alt="$::phr{'CombinedView'}"><font size=1>&nbsp;</font>
END
    ;
	  $dflag = 0;
      }
  if($::vm & 0x10000) {
	  $detail .= <<END;
<img src="$::o{'imgdirurl'}/edd.gif" width=11 height=11 border=0 title="$::phr{'DetailedView'}" alt="$::phr{'DetailedView'}"><font size=1>&nbsp;</font>
END
    ;
	  $dflag = 1;
      } else {
	  $detail .= <<END;
<a href="$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=1&ddetail=d&d=$month/$day/$year/9/0$mg$::vmg"><img src="$::o{'imgdirurl'}/ed.gif" width=11 height=11 border=0 title="$::phr{'DetailedView'}" alt="$::phr{'DetailedView'}"></a><font size=1>&nbsp;</font>
END
    ;
      }
  if($::vm & 0x20000) {      
	  $detail .= <<END;
<img src="$::o{'imgdirurl'}/ebb.gif" width=11 height=11 border=0 title="$::phr{'BannerView'}" alt="$::phr{'BannerView'}"><font size=1>&nbsp;</font>
END
    ;
	  $dflag = 2; 
      } else {
	  $detail .= <<END;
<a href="$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=1&ddetail=b&d=$month/$day/$year/9/0$mg$::vmg"><img src="$::o{'imgdirurl'}/eb.gif" width=11 height=11 border=0 title="$::phr{'BannerView'}" alt="$::phr{'BannerView'}"></a><font size=1>&nbsp;</font>
END
    ;
      }
  if(! $::calinfo{'pnt'}) {
      $nextc = "&nbsp;&nbsp;<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=1&d=$::o{'nextc'}/9/0$mg$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/rright.gif\" width=10 height=12 border=0></a>";
      $prevc = "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=1&d=$::o{'previousc'}/9/0$mg$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/rleft.gif\" width=10 height=12 border=0></a>&nbsp;&nbsp;";	  

      $search=<<END;
<table border=0 cellpadding=0 cellspacing=0 class="calSearch"><tr><td nowrap>
<Form name=csearch action="$::o{'cginame'}" method=GET  class="searchform">
<input type=hidden name=c value="dosearch">
<input type=hidden name=searchRange value="all">
<input type=hidden name=w value="$iwho">
<input type=hidden name=v value=1>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$month/$day/$year">
$::vmp$vmg
$::srchi<a href="$::o{'cginame'}?c=search&w=$iwho&v=1&ls=$ls&$mg$::vmg"><font size=1><span class="fmLabelSa">$::phr{'Search'}:</span></font></a>
<font size=1><input type=text name=stopic size=10 maxlength=128 value="$::srchftrptn" class="fmEntrySa"></font>
<font size=1><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font>
</Form>
</td></tr></table>
END
    ;
  } else { $nextc = $prevc = $detail = ""; $search="&nbsp;";}


  $todayc = printDate( $::now{'month'}, $::now{'day'}, $::now{'year'});

  $diary= hasdiary($iwho, "$month/$day/$year");
  if($diary){ $diary="&nbsp;<a href=\"$::o{'cginame'}?c=diary&w=$iwho&vd=1&v=1&ls=$ls&d=$month/$day/$year$::vmg\"><img src=\"$::o{'imgdirurl'}/diary.gif\" width=16 height=14 border=0></a>";} else {$diary="";}
  $stmp = mdy_wstring($month,$day,$year);

  if($dflag == 1) {  $dcal = oneDayDetailA($month, $day, $year, $todayc,$iwho);}
  elsif($dflag == 2) {
      if($::d{'megaCal'}) {
	  my @allusers = split(/,/, $::d{'megaCal'});
	  my $nusers = 0+@allusers; 
	  if($nusers < 10){ $dcal = oneDayDetailBannerA($month, $day, $year, $todayc);}
	  else {$dcal = oneDayDetailBanner($month, $day, $year, $todayc);}
      } else {$dcal = oneDayDetailBanner($month, $day, $year, $todayc);}
  } else {  $dcal = oneDayDetail($month, $day, $year, $todayc);}

  $out= <<END;
<script language=Javascript type="text/javascript">
function da(u,t){
 var url="$::o{'cginame'}?c=ne&k=1&ls=$ls&v=1&w=" + u + "$::vmg&d=$month/$day/$year/" + t;
 document.location = url;
}
function db(t){
 var url="$::o{'cginame'}?c=ctd&k=1&ls=$ls&v=1$mg&w=$iwho$::vmg&d=$month/$day/$year/" + t;
 document.location = url;
}
</script>
<table border=0 cellpadding=0 cellspacing=4 width="$::o{'tw'}%">
  <tr valign=top><td width="$pa%" align=center><font size=1><br></font>
<table border=0 cellspacing=0 cellpadding=0 width="100%" class="dvtbl">
<tr><td $nbclr class="dvpmonth">$pout</td></tr>
<tr><td class="dvmonthfill">&nbsp;</td></tr>
<tr><td $nbclr class="dvmonth">$tout</td></tr>
<tr><td class="dvmonthfill">&nbsp;</td></tr>
<tr><td $nbclr class="dvnmonth">$nout</td></tr>
</table>
</td>
  <td><br></td>
  <td width="$pb%">
<center>
<table border=0 cellspacing=0 cellpadding=1 width="100%"><tr><td width="25%" align=center>$::o{'qadd'}&nbsp;</td><td width="50%" align=center nowrap>
$::mnbar<font color="#ff0000"><b><span class="dvTitle">$prevc$::srchn$stmp</span></b></font>$nextc$::vnbar $diary &nbsp; $detail
</td><td width="25%" align=right nowrap valign=top>$search</td></tr></table>
</center>
$dcal</td></tr>
</table>
END
    ;
  
  return $out;
}
#
#===============================================================================================
sub oneDayDetailBanner {
    use integer;
    my ($i, $j, $k,$iwho, $cal, $stmp, $t, $month, $day, $year, $out, $start, $end, $special,$diary,$href,
	@keys, $key, $tmp, $hr, $mn, $ehr, $emn, $ump, $tim, $kind, $tag, $todayc, $color, $tdcolor, $percent);
    my ($before, $after) = ("","");
    my ($dayStart, $dayEnd, @etable, $nevents, $nrows, $ncols, $wcode, @ttable, $editing, $user, $nusers);
    my ($rstart, $rend, $usr, $bcnt,$acnt); $bcnt=0; $acnt=0;
    my ($itv, $hccnt);
    ($month, $day, $year,$todayc) = (@_);
    $iwho = $::calinfo{'w'};
    $editing = ($::vm & 0x1000) ? 0 : 1;
    $out = "";
    $start = $::calinfo{'hourB'};
    $end = $::calinfo{'hourE'};
    $wcode= wday($month, $day, $year);
    my $dnd = $editing;
    my ($dndid, $dndop,$sdate)=("","","");
    if($::o{'dnd'} and $dnd) {
	$dndop ="ondragenter=\"dnden()\" ondragover=\"dndov()\" ondragleave=\"dndlv()\" ondrop=\"dnddp()\"";
	$sdate="$month/$day/$year";
    } else { $dnd=0;}
    my ($spacing, $border); if($::calinfo{'pnt'}) { $spacing=0; $border=1;} else {$spacing=1; $border=0;}
    if($::calinfo{'interval'}) {$itv = $::calinfo{'interval'}; $itv=30 if $itv>30;} else {$itv=15;}  $hccnt = 60/$itv;
    if($::d{'megaCal'}) {
	$dayStart=0; $dayEnd=9999;
	my @allusers = split(/,/, $::d{'megaCal'}); $nusers = 0+@allusers;
	foreach $usr (@allusers) {
	    getWorkingHourTable($usr);
	    $tmp = $::WorkingHours[$wcode];   $hr= $tmp/100; $mn=$tmp%100;
	    $i = ($hr * 60 + $mn)/$itv; if($i > $dayStart) { $dayStart=$i;}
	    $tmp = $::WorkingHours[8+$wcode]; $hr= $tmp/100; $mn=$tmp%100; 
	    $i = ($hr * 60 + $mn)/$itv;  if($i < $dayEnd) { $dayEnd=$i;}
	}
    } else {
	$nusers = 1;
	getWorkingHourTable($iwho);
	$tmp = $::WorkingHours[$wcode];   $hr= $tmp/100; $mn=$tmp%100;    $dayStart = ($hr * 60 + $mn)/$itv ;
	$tmp = $::WorkingHours[8+$wcode]; $hr= $tmp/100; $mn=$tmp%100;    $dayEnd = ($hr * 60 + $mn)/$itv;
    }
    $rstart = $start * $hccnt;
    $rend   = $end * $hccnt;
    $nrows = $rend - $rstart + 1;
    $ncols=0;
    getOneDayEvents($month, $day, $year, $todayc, 0);
    @keys = sort sorttime (keys %::oneDayEvents);
    $nevents = 1 + @keys; 
    for($i=0; $i <= $rend; $i++) { $etable[$i] = [ map(" ", (0..$nevents)) ];}
    my @cells= [map(0,(0..3*$nevents))]; my $cellcnt=0;
    @ttable= map(0,(0..$rend));

    for $key (@keys) {
	my ($row, $col, $span);
	$cal = "";
	($hr,$mn, $ehr, $emn, $kind, $tag, $color)=split(/:/, $key); if($kind==4){$hr=~ s/^\(\d+\)//;}
	if($kind == 4 or $ehr < $start or $ehr == $start and $emn == 0) {
	    $row = -2; $span=1; $col=0;
	} elsif($hr >= $end) { 
	    $row = -1; $span=1; $col=0;	    
	} else {
	    ($row, $col, $span) = find_slot($hr, $mn, $ehr, $emn, $rstart, $rend, \@etable,$nevents,$itv,$hccnt);
	}
	$tim = hm_hm_string($hr,$mn,$ehr,$emn);
	$tmp = $::oneDayEvents{$key};
	$href = $tmp;
	if($href =~ m/<a (href="[^"]*").*/) {$href = $1;} else {$href="";} #")
	$href =~ s/(c=ed)|(c=cfm)/c=m2/s;
	if($color) { $tdcolor="bgcolor=$color";} 
	else {$color = $webcalConfig::r{'usrColors'}->[$ncols]; $tdcolor="bgcolor=$color";};

	if($row >= 0) {
	    if($dnd) {$dndid="id=\"$iwho:$sdate/$hr/$mn\""; }
	    if($kind == 1) {
		$cal = "<td valign=top rowspan=$span $tdcolor class=\"eb1\" $dndid $dndop><font size=1><a $href class=\"ztt1\"><font color=$::o{'tclra'}>$tim &nbsp;</font></a><br>$tmp</font></td>\n";
	    } elsif ($kind == 2) {
		if($mn == 99) { $tim = "<img src=\"$::o{'imgdirurl'}/larr.gif\" width=14 height=10 border=0 alt=\"\">";}
		$cal = "<td valign=top $tdcolor rowspan=$span class=\"eb2\" $dndid $dndop><font size=1><a $href class=\"ztt2\"><font color=$::o{'tclrt'}>$tim &nbsp;</font></a><br>$tmp</font></td>\n";
	    } elsif ($kind == 3) {
		$cal = "<td valign=top rowspan=$span $tdcolor class=\"eb3\" $dndid $dndop><font size=1><a $href class=\"ztt3\"><font color=$::o{'tclrm'}>$tim &nbsp;</font></a><br>$tmp</font></td>\n";
	    } 
	    $etable[$row][$col] = $cal;
	    for($i=$row+1; $i<$span+$row; $i++) { $etable[$i][$col] = "";}
	    for($i=$row; $i<$span+$row; $i++) { $ttable[$i]++;}
	    if($col > $ncols) { $ncols = $col;}
	    $cells[$cellcnt]=$row; $cells[$cellcnt+1]=$col; $cells[$cellcnt+2]=$span; $cellcnt += 3;
	} else {
	    if($kind == 1) {
		$cal = "<td valign=top $tdcolor class=\"eb1\"><font size=1><a $href class=\"ztt1\"><font color=$::o{'tclra'}>$tim &nbsp;</font></a>$tmp<br></font></td>\n";
	    } elsif ($kind == 2) {
		if($mn == 99) { $tim = "<img src=\"$::o{'imgdirurl'}/larr.gif\" width=14 height=10 border=0 alt=\"\">";}
		$cal = "<td valign=top $tdcolor class=\"eb2\"><font size=1><a $href class=\"ztt2\"><font color=$::o{'tclrt'}>$tim &nbsp;</font></a>$tmp<br></font></td>\n";
	    } elsif ($kind == 3) {
		$cal = "<td valign=top $tdcolor class=\"eb3\"><font size=1><a $href class=\"ztt3\"><font color=$::o{'tclrm'}>$tim &nbsp;</font></a>$tmp<br></font></td>\n";
	    } else {
		$cal = "<td valign=top $tdcolor class=\"eb4\"><font size=1><a $href class=\"ztt4\"><img src=\"$::o{'imgdirurl'}/sm.gif\" width=19 height=8 border=0 title=\"$::phr{'NoTimeEvent'}\" alt=\"$::phr{'NoTimeEvent'}\"></a>&nbsp;$tmp<br></font></td>\n";
	    }	    
	    if($row == -2) {
		$before .= $cal; $bcnt++; if($bcnt%2==0){$before .= "</tr><tr bgcolor=#ffffff>";;} 
	    } else {
		$after .= $cal;  $acnt++; if($acnt%2==0){$after  .= "</tr><tr bgcolor=#ffffff>";}
	    }
	} 
    }
    if($ncols > 1) { #
	my ($i, $j, $k, $r, $c, $s);
	for($i=0; $i<$cellcnt; $i+= 3) {
	    $r=$cells[$i];$c=$cells[$i+1];$s=$cells[$i+2];
	    $j=$c+1; if($j >=$ncols){ next;} 
	    my($done, $changed)=(0,0);
	    while(!$done and $j < $ncols){
		for($k=$r; $k<$r+$s; $k++) {if($etable[$k][$j] ne " ") {$done=1;last;}}
		if(!$done){$changed++;for($k=$r; $k<$r+$s; $k++){$etable[$k][$j] = "";}}
		$j++;
	    }
	    if($changed){$changed++; $etable[$r][$c]=~ s/^<td/<td colspan=$changed/;}
	}
    }
    $ncols++;
    $out =<<END;
<table border=0 cellpadding=0 cellspacing=0 width="100%" bgcolor="#c0ccff" class="backtbldvb"><tr><td width="100%" bgcolor="#c0cccf" class="backtbldvb">
<table class="ebanner" border=$border cellpadding=0 cellspacing=$spacing width="100%" bgcolor="#c0c0ff">
END
    ;
    if($before) {
	my $insert="";
	my $tmp = ($bcnt & 1);
	if($tmp and $bcnt>1) { $insert="<td class=\"dvOutsideTd1\">&nbsp;</td>";}
	$out .= "<tr bgcolor=#ffffff><td class=\"dvOutsideTd0\">&nbsp;</td><td colspan=$ncols valign=top class=\"dvOutsideTd1\"><table border=0 cellspacing=4 cellpadding=2 class=\"ebanner\" width=\"100%\"><tr class=\"dvOutsideTd1\">$before$insert</tr></table></td></tr>";
    }
    for($i = $rstart; $i <= $rend; $i++) {
	my ($tmp, $tclr,$events); $events="";
	$tmp = $i * $itv;
	$hr = $tmp/60; $mn = $tmp % 60; my $tm = hm_string($hr, $mn);
	if($i < $dayStart or $i >= $dayEnd) { $tclr = "bgcolor=#cccccc"; $j=0;} 
	else { $j=$ttable[$i]; $tmp=$webcalConfig::r{'otColors'}->[$j]; $tclr="bgcolor=$tmp";}
	if($nusers <= 1) {
	    if($editing) {
		$events .= <<END;
<a href="javascript:da('$iwho','$hr/$mn')"><img src="$::o{'imgdirurl'}/da.gif" width=50 height=12 border=0></a>
END
    ;
	    } else { $events .= <<END;
<img src="$::o{'imgdirurl'}/da.gif" width=50 height=12 border=0>
END
    ; 
		 }
	} else {
	    if($editing) {
		$events .= <<END;
<a href="javascript:db('$hr/$mn')"><img src="$::o{'imgdirurl'}/da.gif" width=50 height=12 border=0></a>
END
    ;
	    } else {
		$events .= <<END;
<img src="$::o{'imgdirurl'}/da.gif" width=50 height=12 border=0>
END
    ;
	    }
	} 

	my ($klass1, $klass2, @span, $scnt,$si, $sj, $uclr); @span = map("", (0..$ncols)); $si=0;
	while($si < $ncols) {
	    if($etable[$i][$si] eq " ") {
		$scnt=1; $sj = $si;
		while($si+1 < $ncols and $etable[$i][$si+1] eq " ") {
		    $scnt++; $etable[$i][$si+1] = ""; $si++;
		}
		if($scnt>1) {$span[$sj]="colspan=$scnt";}
	    } 
	    $si++;
	}
	if($i < $dayStart or $i >= $dayEnd) {
	    $klass1="dvOutsideTd0"; $klass2="dvOutsideTd1"; $uclr=$tclr;
	} else { $klass1="ebt$j"; $klass2="ebebnk"; $uclr="#ffffee";}

	if($dnd){$dndid="id=\"$iwho:$sdate/$hr/$mn\"";}
	$tmp = "<tr bgcolor=#ffffff><td width=\"2%\" $tclr class=\"$klass1\" $dndid $dndop><font size=1><span class=\"dvBT\">$tm</span></font></td>";
	for($j = 0; $j < $ncols; $j++) {
	    if($etable[$i][$j] eq " ") { $tmp .= "<td $uclr $span[$j] class=\"$klass2\" $dndid $dndop><font size=1>&nbsp;$events</font></td>";}
	    elsif($etable[$i][$j] ne "") {$tmp .= $etable[$i][$j];}
	}
	$tmp .= "</tr>";
	$out .= "$tmp";
    }
    $out .= "</td></tr>";
    if($after) { 
	my $insert="";
	my $tmp = ($acnt%2); 
	if($acnt>1 && $tmp) { $insert="<td class=\"dvOutsideTd1\">&nbsp;</td>";}
	$out .= "<tr bgcolor=#ffffff><td class=\"dvOutsideTd0\"><font size=1>&nbsp;</font></td><td colspan=$ncols valign=top class=\"dvOutsideTd1\"><table border=0 cellspacing=1 cellpadding=2 class=\"ebanner\"><tr>$after$insert</tr></table></td></tr>";
    }    
    $out .= "</table></td></tr></table>";
    
    return $out;
}
sub find_slot {
    use integer;
    my ($hr, $mn, $ehr, $emn, $rstart, $rend, $etable, $total, $itv, $cnt) = (@_);
    my $rs= ($hr * $cnt)  + ($mn)/$itv;
    my $re= ($ehr * $cnt) + ($emn+ $itv-1)/$itv; if($re == $rs) { $re=$rs+1;}
    my ($i, $j, $k);
    if($rs < $rstart) { $rs = $rstart;}
    if($re > $rend) { $re = 1+$rend;}
    for($i=0; $i< $total; $i++) {
	my $found = 1;
	for($j=$rs; $j<$re; $j++) { if($etable->[$j][$i] ne " ") { $found=0; last;}}
	last if $found;
    }
    return($rs,$i, $re - $rs);
}
#=====================================================================================================
sub oneDayDetailBannerA {
    use integer;
    my ($i, $j, $k,$iwho, $cal, $stmp, $t, $month, $day, $year, $out, $start, $end, $special,$diary,$href,
	@keys, $key, $tmp, $hr, $mn, $ehr, $emn, $ump, $tim, $kind, $tag, $todayc, $color, $tdcolor, $percent);
    my ($before, $after) = ("","");
    my ($dayStart, $dayEnd, $nevents, $nrows, $ncols, $wcode, $editing, $user, $nusers);
    my ($rstart, $rend, $usr, $bcnt,$acnt);
    my (%dayStart, %dayEnd, %befores, %afters,%diaries, %ncolns, %acnts, %bcnts, %etables,%ttables);
    my ($outa, $outb)=(0,0);
    my ($itv,$hccnt);
    ($month, $day, $year,$todayc) = (@_);
    $iwho = $::calinfo{'w'};
    $editing = ($::vm & 0x1000) ? 0 : 1;
    $out = "";
    $start = $::calinfo{'hourB'};
    $end = $::calinfo{'hourE'};
    $wcode= wday($month, $day, $year);
    my $dnd = $editing;
    my ($dndid, $dndop, $sdate)=("","","");
    if($::o{'dnd'} and $dnd) {
	$dndop ="ondragenter=\"dnden()\" ondragover=\"dndov()\" ondragleave=\"dndlv()\" ondrop=\"dnddp()\"" ;
	$sdate="$month/$day/$year";
    } else { $dnd = 0; }

    my ($spacing, $border); if($::calinfo{'pnt'}) { $spacing=0; $border=1;} else {$spacing=1; $border=0;}
    my @allusers = sort {uc($a) cmp uc($b) } split(/,/, $::d{'megaCal'}); $nusers = 0+@allusers;
    foreach $usr (@allusers) {
	$befores{$usr}="";$afters{$usr}="";$ncolns{$usr}=0;$etables{$usr}="";$ttables{$usr}="";
    }
    if($::calinfo{'interval'}) {$itv = $::calinfo{'interval'}; $itv=30 if $itv>30;} else {$itv=15;}  $hccnt = 60/$itv;
    foreach $usr (@allusers) {
	getWorkingHourTable($usr);
	$tmp = $::WorkingHours[$wcode]; $hr= $tmp/100; $mn=$tmp%100;
	$i = ($hr * 60 + $mn)/$itv;  $dayStart{$usr} = $i;
	$tmp = $::WorkingHours[8+$wcode]; $hr= $tmp/100; $mn=$tmp%100; 
	$i = ($hr * 60 + $mn)/$itv;  $dayEnd{$usr} = $i;
    }
    $rstart = $start * $hccnt;
    $rend   = $end * $hccnt;
    $nrows = $rend - $rstart + 1;
    getOneDayEvents($month, $day, $year, $todayc, 0);
    my @allkeys = keys %::oneDayEvents;

    foreach $usr (@allusers) {
	my %thash = (); my $total=0; 
	my($bcnt, $acnt)=(0,0);
	my ($before, $after) = ("","");
	my $ncols=0;
	my (@etable,@ttable);
	foreach $key (@allkeys) {
	    my $e = $::oneDayEvents{$key};
	    if( $e =~ s/<FoNt CoLoR=\#[0-9A-Fa-f]+>$usr:<\/FoNt>// ) { $thash{$key} = $e;} #
	}	
	@keys = sort sorttime (keys %thash);
	$nevents = 1 + @keys; 
	for($i=0; $i <= $rend; $i++) { $etable[$i] = [ map(" ", (0..$nevents)) ];}
	my @cells= [map(0,(0..3*$nevents))]; my $cellcnt=0;
	@ttable= map(0,(0..$rend));
	for $key (@keys) {
	    my ($row, $col, $span);
	    $cal = "";
	    ($hr,$mn, $ehr, $emn, $kind, $tag, $color)=split(/:/, $key);if($kind==4){$hr=~ s/^\(\d+\)//;}
	    if($kind == 4 or $ehr < $start or $ehr == $start and $emn == 0) {$row = -2; $span=1; $col=0;}
	    elsif($hr >= $end) { $row = -1; $span=1; $col=0; }
	    else {($row, $col, $span) = find_slot($hr, $mn, $ehr, $emn, $rstart, $rend, \@etable,$nevents,$itv, $hccnt);}
	    $tim = hm_hm_string($hr,$mn,$ehr,$emn);
	    $tmp = $thash{$key};
	    $href = $tmp;
	    if($href =~ m/<a (href="[^"]*").*/) {$href = $1;} else {$href="";} #")
	    $href =~ s/(c=ed)|(c=cfm)/c=m2/s;
	    if($color) { $tdcolor="bgcolor=$color";} 
	    else {$color = $webcalConfig::r{'usrColors'}->[$ncols]; $tdcolor="bgcolor=$color";};
	    if($dnd){$dndid="id=\"$usr:$sdate/$hr/$mn\"";} else { $dndid="";}

	    if($row >= 0) {
		if($kind == 1) {
		    $cal = "<td valign=top rowspan=$span $tdcolor class=\"eb1\" $dndid $dndop><font size=1><a $href class=\"ztt1\"><font color=$::o{'tclra'}>$tim &nbsp;</font></a><br>$tmp</font></td>\n";
		} elsif ($kind == 2) {
		    if($mn == 99) { $tim = "<img src=\"$::o{'imgdirurl'}/larr.gif\" width=14 height=10 border=0 alt=\"\">";}
		    $cal = "<td valign=top $tdcolor rowspan=$span class=\"eb2\" $dndid $dndop><font size=1><a $href class=\"ztt2\"><font color=$::o{'tclrt'}>$tim &nbsp;</font></a><br>$tmp</font></td>\n";
		} elsif ($kind == 3) {
		    $cal = "<td valign=top rowspan=$span $tdcolor class=\"eb3\" $dndid $dndop><font size=1><a $href class=\"ztt3\"><font color=$::o{'tclrm'}>$tim &nbsp;</font></a><br>$tmp</font></td>\n";
		} 
		$etable[$row][$col] = $cal;
		for($i=$row+1; $i<$span+$row; $i++) { $etable[$i][$col] = "";}
		for($i=$row; $i<$span+$row; $i++) { $ttable[$i]++;}
		if($col > $ncols) { $ncols = $col;}
		$cells[$cellcnt]=$row; $cells[$cellcnt+1]=$col; $cells[$cellcnt+2]=$span; $cellcnt += 3;
	    } else {
		if($kind == 1) {
		    $cal = "<td valign=top $tdcolor class=\"eb1\"><font size=1><a $href class=\"ztt1\"><font color=$::o{'tclra'}>$tim &nbsp;</font></a>$tmp<br></font></td>\n";
		} elsif ($kind == 2) {
		    if($mn == 99) { $tim = "<img src=\"$::o{'imgdirurl'}/larr.gif\" width=14 height=10 border=0 alt=\"\">";}
		    $cal = "<td valign=top $tdcolor class=\"eb2\"><font size=1><a $href class=\"ztt2\"><font color=$::o{'tclrt'}>$tim &nbsp;</font></a>$tmp<br></font></td>\n";
		} elsif ($kind == 3) {
		    $cal = "<td valign=top $tdcolor class=\"eb3\"><font size=1><a $href class=\"ztt3\"><font color=$::o{'tclrm'}>$tim &nbsp;</font></a>$tmp<br></font></td>\n";
		} else {
		    $cal = "<td valign=top $tdcolor class=\"eb4\"><font size=1><a $href class=\"ztt4\"><img src=\"$::o{'imgdirurl'}/sm.gif\" width=19 height=8 border=0 title=\"$::phr{'NoTimeEvent'}\" alt=\"$::phr{'NoTimeEvent'}\"></a>&nbsp;$tmp<br></font></td>\n";
		}	    
		if($row == -2) {
		    $before .= $cal; $bcnt++; if($bcnt%2==0){$before .= "</tr><tr bgcolor=#ffffff>";} $outb++;
		} else {
		    $after .= $cal;  $acnt++; if($acnt%2==0){$after  .= "</tr><tr bgcolor=#ffffff>";} $outa++;
		}
	    } 
	}
	$ncols++;
	if($ncols > 1) { #
	    my ($i, $j, $k, $r, $c, $s);
	    for($i=0; $i<$cellcnt; $i+= 3) {
		$r=$cells[$i];$c=$cells[$i+1];$s=$cells[$i+2];
		$j=$c+1; if($j >=$ncols){ next;} 
		my($done, $changed)=(0,0);
		while(!$done and $j < $ncols){
		    for($k=$r; $k<$r+$s; $k++) {if($etable[$k][$j] ne " ") {$done=1;last;}}
		    if(!$done){$changed++;for($k=$r; $k<$r+$s; $k++){$etable[$k][$j] = "";}}
		    $j++;
		}
		if($changed){$changed++; $etable[$r][$c]=~ s/^<td/<td colspan=$changed/;}
	    }
	}
	$etables{$usr}=\@etable;
	$ttables{$usr}=\@ttable;
	$befores{$usr}=$before;
	$afters{$usr}=$after;
	$bcnts{$usr}   =$bcnt;
	$acnts{$usr}   =$acnt;
	$ncolns{$usr}=$ncols;
    }
    
    $out =<<END;
<table border=0 cellpadding=0 cellspacing=0 width="100%" bgcolor="#c0ccff" class="backtbldvb"><tr><td width="100%" bgcolor="#c0cccf" class="backtbldvb">
<table class="ebanner" border=$border cellpadding=0 cellspacing=$spacing width="100%" bgcolor="#c0c0ff">
END
    ;
# the header 
    my $tcnt=0;
    my $ls = $::calinfo{'ls'};
    $percent = int(98/$nusers);
    $out .= "<tr bgcolor=#ffffff><td class=\"dbvhdr1\" width=\"2%\"><font size=1>&nbsp;</font></td>";    
    foreach $usr (@allusers) {
	my $ncols = $ncolns{$usr};
	my $p = $tcnt&1; $tcnt++;
	my $label = "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$usr&v=1&ddetail=b&d=$month/$day/$year/9/0$::vmg\"><b><span class=\"dbvhdr\">$usr</span></b></a>";
	$out .= "<td class=\"dbvhdr$p\" colspan=$ncols align=center nowrap width=\"$percent%\"><font size=-1>$label</font></td>";
    }
    $out .= "</tr>";    

# events outside of day start/end interval
    if($outb) {
	$out .= "<tr class=\"dbvRowOut0\"><td class=\"dbvOutsideTd0\">&nbsp;</td>";    
	foreach $usr (@allusers) {
	    my $acnt = $acnts{$usr};
	    my $bcnt = $bcnts{$usr};
	    my $before = $befores{$usr};
	    my $after = $afters{$usr};
	    my $ncols = $ncolns{$usr};
	    my $insert="";
	    if($before) {
		my $tmp = ($bcnt & 1);
		if($tmp and $bcnt>1) { $insert="<td class=\"dbvOutsideTd0\">&nbsp;</td>";}
		$out .= "<td colspan=$ncols valign=top class=\"dbvOutsideTd0\"><table border=0 cellspacing=4 cellpadding=2 class=\"ebanner\" width=\"100%\"><tr>$before$insert</tr></table></td>";
	    } else {
		$out .= "<td colspan=$ncols class=\"dbvOutsideTd0\">&nbsp;</td>";    
	    }
	}
	$out .= "</tr>";    
    }


# events within start/end interval
    my ($rowparity,$colparity);
    for($i = $rstart; $i <= $rend; $i++) {
	my $smp = $i * $itv;
	$hr = $smp/60; $mn = $smp % 60; my $tm = hm_string($hr, $mn); 
	$rowparity = $i&1;
	my $trow ="<td width=\"2%\" class=\"dbvdtm$rowparity\" $dndid $dndop><font size=1><span class=\"dbvBT\">$tm</span></font></td>";	
	$tcnt=0;	    
	foreach $usr (@allusers) {	
	    $colparity = $tcnt&1; $tcnt++;
	    my ($tmp, $tclr,$events); $events="";
	    my $ttable =$ttables{$usr};
	    my $etable =$etables{$usr};	    
	    my $ncols = $ncolns{$usr};
	    if($i < $dayStart{$usr} or $i >= $dayEnd{$usr}) {
		$tclr = "background=\"$::o{'imgdirurl'}/mask2.gif\""; $j=0;		
	    } else { $j=$ttable->[$i]; $tmp=$webcalConfig::r{'otColors'}->[$j]; $tclr="bgcolor=$tmp";}

	    if($editing) {
		$events .= <<END;
<a href="javascript:db('$hr/$mn')"><img src="$::o{'imgdirurl'}/db.gif" width=16 height=12 border=0></a>
END
    ;
	    } else {
		$events .= <<END;
<img src="$::o{'imgdirurl'}/db.gif" width=16 height=12 border=0>
END
    ;
	    }

	    my ($klass, @span, $scnt,$si, $sj, $uclr); @span = map("", (0..$ncols)); $si=0;
	    while($si < $ncols) {
		if($etable->[$i][$si] eq " ") {
		    $scnt=1; $sj = $si;
		    while($si+1 < $ncols and $etable->[$i][$si+1] eq " ") {
			$scnt++; $etable->[$i][$si+1] = ""; $si++;
		    }
		    if($scnt>1) {$span[$sj]="colspan=$scnt";}
		} 
		$si++;
	    }
	    if($i < $dayStart{$usr} or $i >= $dayEnd{$usr}) {$klass="dbvOutsideTd1";$uclr=$tclr;}
	    else{$klass="dbvdbnk$rowparity$colparity"; $uclr="#ffffcc";}
	    if($dnd) {$dndid="id=\"$usr:$sdate/$hr/$mn\"";} else {$dndid="";}
	    for($j = 0; $j < $ncols; $j++) {
		if($etable->[$i][$j] eq " "){$trow .= "<td $span[$j] $uclr class=\"$klass\" $dndid $dndop><font size=1>&nbsp;$events</font></td>";}
		elsif($etable->[$i][$j] ne "") {$trow .= $etable->[$i][$j];}
	    }
	}
	$out .= "<tr bgcolor=#ffffff>$trow</tr>";
    }
# events outside of day start/end interval
    if($outa) {
	$out .= "<tr class=\"dbvRowOut1\"><td class=\"dbvOutsideTd0\">&nbsp;</td>";    
	foreach $usr (@allusers) {
	    my $acnt = $acnts{$usr};
	    my $after = $afters{$usr};
	    my $ncols = $ncolns{$usr};
	    my $insert="";
	    if($after) {
		my $tmp = ($acnt & 2);
		if($tmp and $acnt>1) { $insert="<td class=\"dbvOutsideTd0\">&nbsp;</td>";}
		$out .= "<td colspan=$ncols valign=top class=\"dbvOutsideTd1\"><table border=0 cellspacing=4 cellpadding=2 class=\"ebanner\" width=\"100%\"><tr>$after$insert</tr></table></td>";
	    } else {
		$out .= "<td colspan=$ncols class=\"dbvOutsideTd0\">&nbsp;</td>";    
	    }
	}
	$out .= "</tr>";    
    }
    $out .= "</table></td></tr></table>"; 
    return $out;
}
#==========================================================================================================
sub oneDayDetailA {
    use integer;
    my($month, $day, $year, $todayc,$iwho) = (@_);
    my ($start, $end, @allusers, $nusers, $i, @cftable, @orderedusers, @emptyusers);
    my ($wcode, $tmp, $hr, $mn, %dayStart,%dayEnd, $havespecial, $usr);
    my (@ettb, @eetb,@ectb, @especial, %usertimetable, %usereventtable, %usercolortable, %userspecial);
    my ($itv,$hccnt);
    %usertimetable=(); %usereventtable=(); %userspecial=(); %usercolortable=(); my %userkindtable=();
    @ettb = map(1, (1..100));  @eetb = map("", (1..100));  @ectb = map("", (1..100)); my @ektb = map(0, (1..100));
    @especial =("","","");
    $start = $::calinfo{'hourB'};
    $end = $::calinfo{'hourE'};
    $wcode= wday($month, $day, $year);
    getOneDayEvents($month, $day, $year, $todayc, 0);    
    @cftable = map(0, (1..100));
    @orderedusers = (); @emptyusers = (); %dayStart = (); %dayEnd = (); $havespecial=0;
    if($::calinfo{'interval'}) {$itv = $::calinfo{'interval'}; $itv=30 if $itv>30;} else {$itv=15;}  $hccnt = 60/$itv;
    my $tccnt = $hccnt * 24;
    if($::d{'megaCal'}) {
	my (@keys, $key);
	@keys = keys %::oneDayEvents;
	@allusers = split(/,/, $::d{'megaCal'}); $nusers =  0+@allusers; 
	foreach $usr (@allusers) {
	    my %thash = ();
	    my $total= 0;
	    getWorkingHourTable($usr);
	    $tmp = $::WorkingHours[$wcode];   $hr= $tmp/100; $mn=$tmp%100;
	    $dayStart{$usr} = ($hr * 60 + $mn)/$itv;
	    $tmp = $::WorkingHours[8+$wcode]; $hr= $tmp/100; $mn=$tmp%100; 
	    $dayEnd{$usr} = ($hr * 60 + $mn)/$itv;
	    foreach $key (@keys) {
		my $e = $::oneDayEvents{$key};
		if( $e =~ s/<FoNt CoLoR=\#[0-9A-Fa-f]+>$usr:<\/FoNt>// ) { $thash{$key} = $e; $total++;} #
	    }	
	    if($total > 0) {
		my ($ttb, $etb, $ctb, $ktb,$special, $tmp) = mkOneDayTable(\%thash, $start, $end,$itv, $hccnt);
		$usertimetable{$usr} = $ttb; $usereventtable{$usr} = $etb; $userkindtable{$usr}=$ktb;
		$usercolortable{$usr} = $ctb; $userspecial{$usr} = $special;
		$havespecial += $tmp;
		for($i=0; $i<$tccnt; $i++) { $cftable[$i] ++ if $ttb->[$i] > 1; }
		&finalizeTable($ttb, $etb,$tccnt);
		push @orderedusers, $usr; 
	    } else {
		push @emptyusers, $usr; 
		$usertimetable{$usr} = \@ettb;  $usereventtable{$usr} = \@eetb; $userkindtable{$usr} = \@ektb; 
		$usercolortable{$usr} = \@ectb; $userspecial{$usr} = \@especial;
	    }
	}
    } else {
	my @keys = keys %::oneDayEvents;
	my $mem = $::calinfo{'w'};
	getWorkingHourTable($mem);
	$tmp = $::WorkingHours[$wcode];   $hr= $tmp/100; $mn=$tmp%100; 
	$dayStart{$mem} = ($hr * 60 + $mn)/$itv ;
	$tmp = $::WorkingHours[8+$wcode]; $hr= $tmp/100; $mn=$tmp%100; 
	$dayEnd{$mem} = ($hr * 60 + $mn)/$itv;
	if( 0+@keys > 0) {
	    my ($ttb, $etb, $ctb, $ktb,$special,$tmp) = mkOneDayTable(\%::oneDayEvents, $start, $end,$itv,$hccnt);
	    $usertimetable{$mem} = $ttb; $usereventtable{$mem} = $etb; $userkindtable{$mem} = $ktb; 
	    $usercolortable{$mem} = $ctb; $userspecial{$mem} = $special;
	    $havespecial += $tmp;
	    for($i=0; $i<$tccnt; $i++) { $cftable[$i]++ if $ttb->[$i] > 1; }
	    push @orderedusers, $mem; 
	    &finalizeTable($ttb, $etb, $tccnt);
	} else { 
	    push @emptyusers, $mem;
	    $usertimetable{$mem} = \@ettb;  $usereventtable{$mem} = \@eetb; $userkindtable{$mem} = \@ektb; 
	    $usercolortable{$mem} = \@ectb; $userspecial{$mem} = \@especial;
	}
    }
    for($i = 0; $i < $tccnt; $i++) { if($cftable[$i] > 5) {$cftable[$i] = 5;}}
    @allusers = sort {uc($a) cmp uc($b)} (@orderedusers, @emptyusers);
    my ($spacing, $border); if($::calinfo{'pnt'}) { $spacing=0; $border=1;} else {$spacing=1; $border=0;}
    my $offcolor = $webcalConfig::r{'oColors'}->[6];
    my $total = 0 + @allusers;
    my $cellwidth = 98/$total;
    my $out ="<table bgcolor=#c0c0ff border=0 cellspacing=0 cellpadding=0 width=\"100%\" class=\"backtbldvd\">
<tr><td bgcolor=#c0c0ff width=\"100%\" class=\"backtbldvd\">
<table class=\"edetail\" border=$border cellspacing=$spacing cellpadding=0 width=\"100%\" bgcolor=#c0c0ff>";

    my $editing = ($::vm & 0x1000) ? 0 : 1;

    if($total > 1) {
	my $mg=""; my $ls=$::calinfo{'ls'}; my $cnt=0; 
	if($::d{'megaCal'} ne "") { $mg="&mg=$::d{'megaCal'}";}
	$out .= "<tr bgcolor=#cccc99><td class=\"dvDRow0Td1\"><span class=\"dvDRow0Txtt\">&nbsp;</span></td>";
	foreach $usr (@allusers) {
	    my $parity=$cnt&1;$cnt++;
	    $out .= "<td align=center width=\"$cellwidth%\" class=\"dvDRow0Td$parity\"><span class=\"dvDRow0Txt\">
<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$usr&v=1&ddetail=d&d=$month/$day/$year/9/0$mg$::vmg\">$usr</a>
</span></td>";
	}
	$out .= "</tr>\n";
    }
    # special events and events occurs outside [$start, $end]
    if($havespecial) {
	$out .= "<tr bgcolor=#ffffff><td class=\"dvOutsideTd0\" bgcolor=\"#cccccc\"><br></td>";
	foreach $usr (@allusers) {
	    my $ref = $userspecial{$usr};
	    my $tmp = join("", @$ref);
	    $out .= <<END;
<td width="$cellwidth%" class="dvOutsideTd1" valign=top>
<table border=0 cellspacing=2 cellpadding=0  class="edetailNested" 
width="100%" bgcolor="#ffffff">$tmp</table></td>
END
    ;
	}
	$out .= "</tr>\n";	
    }
    my $dnd = $editing;
    my ($dndid, $dndop, $sdate)=("","","");
    if($::o{'dnd'} and $dnd) {
        $sdate="$month/$day/$year";
	$dndop ="ondragenter=\"dnden()\" ondragover=\"dndov()\" ondragleave=\"dndlv()\" ondrop=\"dnddp()\"" ;
    } else { $dnd=0;}
    
    #output events
    $start = $start * $hccnt; $end = $end * $hccnt;
    my ($rowparity, $colparity);
    for($i = $start; $i < $end; $i++) { $rowparity=$i&1;
	my ($hr, $mn, $tm, $cclr, $tcnt,$parity);
	$tmp = $i * $itv;
	$hr = $tmp/60; $mn = $tmp % 60; $tm = hm_string($hr, $mn);
	$out .= "<tr bgcolor=#ffffff valign=top>";
	$tmp = $cftable[$i];
	$cclr = $webcalConfig::r{'otColors'}->[$tmp]; 
	if($dnd){ $dndid="id=\"$iwho:$sdate/$hr/$mn\"";}
	if($mn == 0){$out .= "<td width=\"2%\" class=\"ebt$tmp\" bgcolor=$cclr align=right $dndid $dndop><font size=1><b><span class=\"dvDT\">$tm</span></b></font></td>";}
	else {$out .= "<td width=\"2%\" class=\"ebt$tmp\" bgcolor=$cclr align=right $dndid $dndop><font size=1 color=#666666><span class=\"dvDT\">$tm</span></font></td>";}
	$tcnt=0;
	foreach $usr (@allusers) {
	    my $tref = $usertimetable{$usr};
	    my $eref = $usereventtable{$usr};
	    my $cref = $usercolortable{$usr};
	    my $kref = $userkindtable{$usr};
	    my $rowspan = $tref->[$i];
	    my $events = $eref->[$i];
	    my $bclr=""; my $ekd = $kref->[$i];
	    $colparity=$tcnt&1; $tcnt++;
	    if($i < $dayStart{$usr} or $i >= $dayEnd{$usr}) {
		if(!$events) {
		    $bclr = "background=\"$::o{'imgdirurl'}/mask2.gif\"";
                    if($editing) {
                        $events = "<a href=\"javascript:da('$usr','$hr/$mn')\"><img src=\"$::o{'imgdirurl'}/da.gif\" width=50 height=12 border=0></a>";
                    } else { 
			$events = "<font size=1>&nbsp;</font>";
		    }
                } else {
		    if($cref->[$i] ne "") { $bclr = "bgcolor=$cref->[$i]";}else{$bclr = "background=\"#eeeecc\"";}
		}
	    } 
	    elsif($cref->[$i] ne "") { $bclr = "bgcolor=$cref->[$i]";} elsif($events) {$bclr = "bgcolor=#eeeecc";}
	    if(!$events) { 
		if($editing) {
		    $events = "<a href=\"javascript:da('$usr','$hr/$mn')\"><img src=\"$::o{'imgdirurl'}/da.gif\" width=50 height=12 border=0></a>";
		} else {$events ="<img src=\"$::o{'imgdirurl'}/da.gif\" width=50 height=12 border=0>";}
	    }
	    if($rowspan > 0) {
		my $class;
		if($dnd){$dndid="id=\"$usr:$sdate/$hr/$mn\"";}
		if($ekd == 0) { $class="ed$rowparity$colparity";} else {$class="ed$ekd";}
		$out .= "<td class=\"$class\" $bclr rowspan=$rowspan width=\"$cellwidth%\" $dndid $dndop>$events</td>";
	    }
	}
	$out .="</tr>\n";
    }
    $out .= "</table></td></tr></table>";
    return $out;
}

sub finalizeTable {
    my ($ttb, $etb, $cellcnt) = (@_);
    my ($i, $start);
    $i = 0;
    while(1) {
	my $v = $ttb->[$i];
	my $what = $etb->[$i];
	$start = $i;
	$i++;
	while($i < $cellcnt and $ttb->[$i] >= $v and $etb->[$i] eq "") { 
	    $ttb->[$i] = 0 if $what or $v > 1;
	    $i++;
	}
	if($what or $v > 1) { $ttb->[$start] = $i - $start; }
	if($i >= $cellcnt) { last;}
    }
} 

sub mkOneDayTable {
    use integer;
    my ($ehash, $start, $end, $itv, $ccnt) = (@_);  
    my $total = 24 * $ccnt;
    my @timetb = map(1, (1 .. $total));
    my @kindtb = map(0, (1 .. $total));
    my @eventtb = map("", (1.. $total));
    my @colortb = map("", (1.. $total));
    my @keys = keys( %$ehash);
    my ($key, $hr, $mn, $ehr, $emn,$kind, $tag, $color, $tim, $tmp, $href, $cal, $havespecial, $count);
    my (@special) = ("", "", "");
    $havespecial = 0; $count = 2;
    foreach $key (sort @keys)  {
	($hr,$mn, $ehr, $emn, $kind, $tag, $color)=split(/:/, $key);if($kind==4){$hr=~ s/^\(\d+\)//;}
	my ($sb, $se)=("","");
	#if($color) { $sb="<span style=\"background-color:$color\">"; $se="</span>";} 
	if($hr eq "" or $kind == 4 ) { # notime event
	    my $bcr=""; if($color) {$bcr="bgcolor=$color";}
	    $tmp = $ehash->{$key};
	    $special[0] .= <<END;
<tr><td class="ed4" $bcr><img src="$::o{'imgdirurl'}/sm.gif" width=19 height=8 border=0 title="$::phr{'NoTimeEvent'}" alt="$::phr{'NoTimeEvent'}"><font size=1>&nbsp;$sb$tmp$se</font></td></tr>
END
    ;
	    $havespecial=1;
	} else {
	    $cal = "";
	    $tim = hm_hm_string($hr,$mn,$ehr,$emn);
	    #$tmp = $::oneDayEvents{$key};
	    $tmp = $ehash->{$key};
	    $href = $tmp;
	    if($href =~ m/<a (href="[^"]*").*/) {$href = $1;} else {$href="";} #")
	    $href =~ s/(c=ed)|(c=cfm)/c=m2/s;
	    if($color) {$tmp = "$sb$tmp$se";}
	    if($kind == 1) {
		$cal = "<font size=1><a $href class=\"ztt1\"><font color=$::o{'tclra'}>$tim &nbsp;</font></a>$tmp<br></font>";
	    } elsif ($kind == 2) {
		if($mn == 99) { $tim = "<img src=\"$::o{'imgdirurl'}/larr.gif\" width=14 height=10 border=0 alt=\"\">";}
		$cal = "<font size=1><a $href class=\"ztt2\"><font color=$::o{'tclrt'}>$tim &nbsp;</font></a>$tmp<br></font>";
	    } elsif ($kind == 3) {
		$cal = "<font size=1><a $href class=\"ztt3\"><font color=$::o{'tclrm'}>$tim &nbsp;</font></a>$tmp<br></font>";
	    }
	    if($ehr < $start or ($ehr == $start and $emn == 0))  {
		my $bcr=""; if($color) {$bcr="bgcolor=$color";}
		$special[1] .= "<tr><td class=\"ed$kind\"$bcr>$cal</td></tr>"; 
		$havespecial=1;
	    } 
	    elsif($hr >= $end) {
		my $bcr=""; if($color) {$bcr="bgcolor=$color";}
		$special[2] .= "<tr><td class=\"ed$kind\" $bcr>$cal</td></tr>";  
		$havespecial=1; 
	    } 
	    else  {
		my($bb, $ee, $bidx, $duration, $r, $i, $j);
		if($hr < $start) { $bb = $start  * 60;} else {$bb = $hr  * 60 + $mn;}
		$ee = $ehr * 60 + $emn;
		$bidx = $bb/$itv;
		$eventtb[$bidx] .= "$cal";
		if( $color) { $colortb[$bidx] = $color;}
		if($ee > $bb) {
		    $duration = $ee - $bidx * $itv + $itv-1;
		    $r = $duration/$itv;
		    for($i=0; $i<$r; $i++) {
			$j = $bidx+$i;
			if($timetb[$j] and $timetb[$j] == 1) { $timetb[$j] = $count;}
			if($color and ! $eventtb[$j]) {$colortb[$j] = $color;}
			$kindtb[$j]=$kind;
		    }
		} else {
		    $j = $bidx;
		    if($timetb[$j] == 1) { $timetb[$j] = $count;}
		    if($color and ! $eventtb[$j]) {$colortb[$j] = $color;}
		    if($kindtb[$j]== 0) { $kindtb[$j]=$kind;}
		}
	    }
	} 
	$count++;
    }
    return( \@timetb, \@eventtb, \@colortb, \@kindtb, \@special, $havespecial);
}
#=====================================================================================================
sub getWorkingHourTable {
    my ($who) = (@_);
    my ($cal, $fname);
    $cal = "$::o{'spooldir'}/$who";
    $fname = "$cal/WorkingHours";
    if( -d "$cal" and -f "$fname") { &doReadFile("$fname");}
    else { @::WorkingHours=(0,0,0,0,0,0,0,0,2500,2500,2500,2500,2500,2500,2500,2500,0);}
}
#=====================================================================================================
sub weekCal {
    my ($month, $day, $year) = (@_);   
    my ($search, $vmg, $mg);
    if(!($::vm & 0x300000) and $::calinfo{'weekview'} and ! $::calinfo{'wdetail'}) { $::vm |= (0+$::calinfo{'weekview'});}    
    if(! $::calinfo{'pnt'}) {
	if($::d{'megaCal'}){$vmg="<input type=hidden name=mg value=\"$::d{'megaCal'}\">";$mg="&mg=$::d{'megaCal'}";} else {$vmg=$mg="";}	
	$search = <<END;
<table border=0 cellpadding=0 cellspacing=0 class="calSearch"><tr><td nowrap>
<Form name=csearch action="$::o{'cginame'}" method=GET  class="searchform">
<input type=hidden name=c value="dosearch">
<input type=hidden name=searchRange value="all">
<input type=hidden name=w value="$::calinfo{'w'}">
<input type=hidden name=v value=2>
<input type=hidden name=d value="$month/$day/$year">
$::vmp$vmg
$::srchi<a href="$::o{'cginame'}?c=search&w=$::calinfo{'w'}&v=2$mg$::vmg"><font size=1><span class="fmLabelSa">$::phr{'Search'}:</span></font></a>
<font size=1><input type=text name=stopic size=10 maxlength=128 value="$::srchftrptn" class="fmEntrySa"></font>
<font size=1><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font>
</Form>
</td></tr></table>
END
    ;
    } else {$search ="";}
    if($::vm & 0x100000) {  return weekCalBanner(@_, $search);}
    else {  return weekCalSummary(@_, $search);}
}
#=====================================================================================================
sub weekViewOptions {
    my ($ls,$iwho,$month,$day,$year,$mg) = (@_);
    my ($detail, $summary, $fb);

    if($::vm & 0x100000) { # in detailed column view
	$detail=<<END;
<a href="$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=2&wdetail=n&d=$month/$day/$year/9/0$mg$::vmg"><img src="$::o{'imgdirurl'}/ew.gif" width=11 height=11 border=0 title="$::phr{'CombinedView'}" alt="$::phr{'CombinedView'}"></a><font size=1>&nbsp;</font>
<img src="$::o{'imgdirurl'}/edd.gif" width=11 height=11 border=0 title="$::phr{'DetailedView'}" alt="$::phr{'DetailedView'}"><font size=1>&nbsp;</font>
END
    ;
    } else {
	$detail=<<END;
<img src="$::o{'imgdirurl'}/eww.gif" width=11 height=11 border=0 title="$::phr{'CombinedView'}" alt="$::phr{'CombinedView'}"><font size=1>&nbsp;</font>
<a href="$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=2&wdetail=d&d=$month/$day/$year/9/0$mg$::vmg"><img src="$::o{'imgdirurl'}/ed.gif" width=11 height=11 border=0 title="$::phr{'DetailedView'}" alt="$::phr{'DetailedView'}"></a><font size=1>&nbsp;</font>
END
    ;
    }
    if($mg) {
	$month++;
	$fb = <<END;
<a href="javascript:pdll('$::o{'cginame'}?c=docompare&action=cft&w=$iwho&v=2&ls=$ls&d=$month/$day/$year$::vmg&cfd=0$mg&inpopup=1')"><img src="$::o{'imgdirurl'}/clr.gif" width=20 height=9 border=0 alt=""></a>&nbsp;&nbsp;
END
    ;
    } else { $fb = "";}
    return ($detail, $fb);
}
#=====================================================================================================

sub weekCalBanner {
    my ($month, $day, $year, $searchf) = (@_);   
    use integer;
    my ($i, $j, $k,$iwho, $cal, $stmp, $t,  $out, $start, $end, $special,$diary,$href,$tday,$z,$ls,
	@keys, $key, $tmp, $hr, $mn, $ehr, $emn, $ump, $tim, $kind, $tag, $todayc, $color, $tdcolor);
    my ($nevents, $nrows, $ncols, $wcode, $editing, $user, $nusers, @etables, @ttables, $mg,
	@befores, @afters, @ncolns, $rstart, $rend, $usr, $bcnt,$acnt, $wklen, $zz, @bcnts, @acnts, @labels,
	@dayEnd, @dayStart, @diaries, $pst, $psta, @days); 
    my ($outa, $outb)=(0,0);
    my ($itv,$hccnt);

    if($::d{'megaCal'} ne "") { $mg="&mg=$::d{'megaCal'}";}
    else {$mg="";}

    if(not $searchf) { $searchf="&nbsp;"; }
    
    $wcode= wday($month, $day, $year);
    if($wcode == 0 && $::o{'weekstart'}) {$wcode = 7;}
    $tday = $day - $wcode;
    if($tday<=0){
	if($month == 0){$month = 11;  $year -= 1; $tday = 31 + $tday;}
	else {$month -= 1; if($month == 1){if(isleap($year)){$::mdays[1]=29;}else{$::mdays[1] = 28;}} $tday=$::mdays[$month]+$tday;}
    }

    $iwho = $::calinfo{'w'};
    $ls = $::calinfo{'ls'};
    $todayc = printDate( $::now{'month'}, $::now{'day'}, $::now{'year'});
    $iwho = $::calinfo{'w'};
    $editing = ($::vm & 0x1000) ? 0 : 1;
    $out = "";
    my $dnd = $editing;
    my($dndid, $dndop)=("","");
    if($::o{'dnd'} and $dnd){
	$dndop ="ondragenter=\"dnden()\" ondragover=\"dndov()\" ondragleave=\"dndlv()\" ondrop=\"dnddp()\"" ;
    } else {$dnd = 0;}
  
    my ($options, $fb) = weekViewOptions($ls,$iwho,$month,$day,$year,$mg);

    if($::o{'excludeWeekend'}) {$wklen = 5; $psta=19; $pst=5;} else {$wklen=7; $psta=14; $pst=2;} 
    $start = $::calinfo{'hourB'};  $end = $::calinfo{'hourE'};

    my ($spacing, $border); if($::calinfo{'pnt'}) { $spacing=0; $border=1;} else {$spacing=1; $border=0;}

    if($::calinfo{'interval'}) {$itv = $::calinfo{'interval'}; $itv=30 if $itv>30;} else {$itv=15;}  $hccnt = 60/$itv;

    @dayStart =(0,0,0,0,0,0,0,0,0,0,0);
    @dayEnd   =(999,999,999,999,999,999,999,999,999,999);

    if($::d{'megaCal'}) {
	my @allusers = split(/,/, $::d{'megaCal'}); $nusers = 0+@allusers;
	foreach $usr (@allusers) {
	    getWorkingHourTable($usr);
	    for($z=0; $z< $wklen; $z++) {
		$wcode = $z+$::o{'weekstart'};
		$tmp = $::WorkingHours[$wcode];   $hr= $tmp/100; $mn=$tmp%100;
		$k = ($hr * 60 + $mn)/$itv; if($k > $dayStart[$z]) { $dayStart[$z]=$k;}
		$tmp = $::WorkingHours[8+$wcode]; $hr= $tmp/100; $mn=$tmp%100; 
		$k = ($hr * 60 + $mn)/$itv;  if($k < $dayEnd[$z]) { $dayEnd[$z]=$k;}
	    }
	}
    } else {
	$nusers = 1;
	getWorkingHourTable($iwho);
	for($z=0; $z< $wklen; $z++) {
	    $wcode = $z+$::o{'weekstart'};
	    $tmp = $::WorkingHours[$wcode];   $hr= $tmp/100; $mn=$tmp%100;  
	    $k = ($hr * 60 + $mn)/$itv; if($k > $dayStart[$z]) { $dayStart[$z]=$k;}
	    $tmp = $::WorkingHours[8+$wcode];  $hr= $tmp/100; $mn=$tmp%100;  
	    $k = ($hr * 60 + $mn)/$itv;  if($k < $dayEnd[$z]) { $dayEnd[$z]=$k;}
	}
    }
   
    $rstart = $start * $hccnt ;
    $rend   = $end * $hccnt;
    $nrows = $rend - $rstart + 1;
    @etables = ("","","","","","","","","","","","","","");
    @ttables = ("","","","","","","","","","","","","","");
    @befores = ("","","","","","","","","","","","","","");
    @afters  = ("","","","","","","","","","","","","","");
    @diaries = ("","","","","","","","","","","","","","");
    @ncolns  = (0,0,0,0,0,0,0,0,0,0,0,0,0,0);
    @days=("","","","","","","","","","");
    my $wknum = weekNum($month,$tday+1,$year, $::o{'weekstart'});    
    if($::o{'weekstart'}) { ($month, $tday, $year)=canDate($month, 1+$tday, $year);}
    my ($nmonth, $nday, $nyear)=($month, $tday, $year);

    for($z=0; $z < $wklen; $z++) {
	getOneDayEvents($month, $tday, $year, $todayc, 0);
	$days[$z]="$month/$tday/$year/";
	if($nusers <=1) {
	    my $sdate= printDate0($month, $tday, $year);
	    if(hasdiary($iwho, $sdate)) {
		$diaries[$z]="<a href=\"$::o{'cginame'}?c=diary&vd=1&w=$iwho&v=2&ls=$ls&d=$sdate$::vmg\"><img src=\"$::o{'imgdirurl'}/diary.gif\" width=16 height=14 border=0 align=right></a>";
	    }
	}
	@keys = sort sorttime (keys %::oneDayEvents);
	$nevents = 1 + @keys; 
	my(@etable, @ttable);
	my($bcnt, $acnt)=(0,0);
	my ($before, $after) = ("","");
	my $ncols=0;
	for($i=0;$i<=$rend;$i++){$etable[$i]=[map(" ",(0..$nevents))];}@ttable= map(0,(0..$rend));
	my @cells= [map(0,(0..3*$nevents))]; my $cellcnt=0;
	for $key (@keys) {
	    my ($row, $col, $span);
	    $cal = "";
	    ($hr,$mn, $ehr, $emn, $kind, $tag, $color)=split(/:/, $key);if($kind==4){$hr=~ s/^\(\d+\)//;}
	    if($kind == 4 or $ehr < $start or $ehr == $start and $emn == 0) {$row = -2; $span=1; $col=0;}
	    elsif($hr >= $end) {$row = -1; $span=1; $col=0;}
	    else{($row, $col, $span) = find_slot($hr, $mn, $ehr, $emn, $rstart, $rend, \@etable,$nevents,$itv,$hccnt);}
	    $tim = hm_hm_string($hr,$mn,$ehr,$emn);
	    $tmp = $::oneDayEvents{$key};
	    $href = $tmp;
	    if($href =~ m/<a (href="[^"]*").*/) {$href = $1;} else {$href="";} #")
	    $href =~ s/(c=ed)|(c=cfm)/c=m2/s;
	    if($color) { $tdcolor="bgcolor=$color";} 
	    else {$color = $webcalConfig::r{'usrColors'}->[$ncols]; $tdcolor="bgcolor=$color";};
	    
	    if($row >= 0) {
		if($dnd){$dndid="id=\"$iwho:$days[$z]$hr/$mn\"";}
		if($kind == 1) {
		    $cal = "<td valign=top rowspan=$span $tdcolor class=\"eb1\" $dndid $dndop><font size=1><a $href class=\"ztt1\"><font color=$::o{'tclra'}>$tim &nbsp;</font></a><br>$tmp</font></td>\n";
		} elsif ($kind == 2) {
		    if($mn == 99) { $tim = "<img src=\"$::o{'imgdirurl'}/larr.gif\" width=14 height=10 border=0 alt=\"\">";}
		    $cal = "<td valign=top $tdcolor rowspan=$span class=\"eb2\" $dndid $dndop><font size=1><a $href class=\"ztt2\"><font color=$::o{'tclrt'}>$tim &nbsp;</font></a><br>$tmp</font></td>\n";
		} elsif ($kind == 3) {
		    $cal = "<td valign=top rowspan=$span $tdcolor class=\"eb3\" $dndid $dndop><font size=1><a $href class=\"ztt3\"><font color=$::o{'tclrm'}>$tim &nbsp;</font></a><br>$tmp</font></td>\n";
		} 
		$etable[$row][$col] = $cal;
		for($i=$row+1; $i<$span+$row; $i++) { $etable[$i][$col] = "";}
		for($i=$row; $i<$span+$row; $i++) { $ttable[$i]++;}
		if($col > $ncols) { $ncols = $col;}
		$cells[$cellcnt]=$row; $cells[$cellcnt+1]=$col; $cells[$cellcnt+2]=$span; $cellcnt += 3;
	    } else {
		if($kind == 1) {
		    $cal = "<td valign=top $tdcolor class=\"eb1\"><font size=1><a $href class=\"ztt1\"><font color=$::o{'tclra'}>$tim &nbsp;</font></a>$tmp<br></font></td>\n";
		} elsif ($kind == 2) {
		    if($mn == 99) { $tim = "<img src=\"$::o{'imgdirurl'}/larr.gif\" width=14 height=10 border=0 alt=\"\">";}
		    $cal = "<td valign=top $tdcolor class=\"eb2\"><font size=1><a $href class=\"ztt2\"><font color=$::o{'tclrt'}>$tim &nbsp;</font></a>$tmp<br></font></td>\n";
		} elsif ($kind == 3) {
		    $cal = "<td valign=top $tdcolor class=\"eb3\"><font size=1><a $href class=\"ztt3\"><font color=$::o{'tclrm'}>$tim &nbsp;</font></a>$tmp<br></font></td>\n";
		} else {
		    $cal = "<td valign=top $tdcolor class=\"eb4\"><font size=1><a $href class=\"ztt4\"><img src=\"$::o{'imgdirurl'}/sm.gif\" width=19 height=8 border=0 title=\"$::phr{'NoTimeEvent'}\" alt=\"$::phr{'NoTimeEvent'}\"></a>&nbsp;$tmp<br></font></td>\n";
		}	    
		if($row == -2) {
		    $before .= $cal; $bcnt++; if($bcnt%2==0){$before .= "</tr><tr bgcolor=#ffffff>";} $outb++;
		} else {
		    $after .= $cal;  $acnt++; if($acnt%2==0){$after  .= "</tr><tr bgcolor=#ffffff>";}  $outa++;
		}
	    } 
	}
	$ncols++;
	if($ncols > 1) { #
	    my ($i, $j, $k, $r, $c, $s);
	    for($i=0; $i<$cellcnt; $i+= 3) {
		$r=$cells[$i];$c=$cells[$i+1];$s=$cells[$i+2];
		$j=$c+1; if($j >=$ncols){ next;} 
		my($done, $changed)=(0,0);
		while(!$done and $j < $ncols){
		    for($k=$r; $k<$r+$s; $k++) {if($etable[$k][$j] ne " ") {$done=1;last;}}
		    if(!$done){$changed++;for($k=$r; $k<$r+$s; $k++){$etable[$k][$j] = "";}}
		    $j++;
		}
		if($changed){$changed++; $etable[$r][$c]=~ s/^<td/<td colspan=$changed/;}
	    }
	}
	$etables[$z] =\@etable;
	$ttables[$z] =\@ttable;
	$befores[$z] =$before;
	$afters[$z]  =$after;
	$ncolns[$z]  =$ncols;
	$bcnts[$z]   =$bcnt;
	$acnts[$z]   =$acnt;
	my $datestr= md_nstring(1+$month,$tday);
	$labels[$z] = "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=1&d=$month/$tday/$year$mg$::vmg\"><b><span class=\"wvdWday\">$::wdays[$::o{'weekstart'}+$z]</span></b><b><font size=-1 color=#ff0000><span class=\"wvdDay\">&nbsp;$datestr</span></font></b></a>";
	($month, $tday, $year) = canDate($month, $tday+1, $year);
    }

    $out =<<END;
<table border=0 cellpadding=0 cellspacing=0 width="100%" bgcolor="#c0ccff" class="backtblwvb">
<tr><td width="100%" bgcolor="#c0cccf" class="backtblwvb">
 <table class="ebanner" border=$border cellpadding=0 cellspacing=$spacing width="100%" bgcolor="#c0c0ff">
END
    ;

# the header 
    $out .= "<tr bgcolor=#ffffff><td class=\"wvdayhdr1\" width=\"$pst%\"><font size=1>&nbsp;</font></td>";    
    for($z=0; $z<$wklen; $z++) {
	my $ncols = $ncolns[$z];
	my $label = $labels[$z];
	my $diary = $diaries[$z];
	my $p = $z&1;
	$out .= "<td class=\"wvdayhdr$p\" colspan=$ncols align=center nowrap width=\"$psta%\"><font size=-1>$diary&nbsp;$label</td>";
    }
    $out .= "</tr>";    
# events outside of day start/end interval
    if($outb) {
	$out .= "<tr class=\"wvRowOut0\"><td class=\"wvOutsideTd0\">&nbsp;</td>";    
	for($z=0; $z<$wklen; $z++) {
	    my $bcnt = $bcnts[$z];
	    my $before = $befores[$z];
	    my $ncols = $ncolns[$z];
	    my $insert="";
	    if($before) {
		my $tmp = ($bcnt & 1);
		if($tmp and $bcnt>1) { $insert="<td class=\"wvOutsideTd0\">&nbsp;</td>";}
		$out .= "<td colspan=$ncols valign=top class=\"wvOutsideTd0\"><table border=0 cellspacing=4 cellpadding=2 class=\"ebanner\" width=\"100%\"><tr>$before$insert</tr></table></td>";
	    } else {
		$out .= "<td colspan=$ncols class=\"wvOutsideTd0\">&nbsp;</td>";    
	    }
	}
	$out .= "</tr>";    
    }

# events within start/end interval
    my ($rowparity,$colparity);
    for($i = $rstart; $i <= $rend; $i++) {
	my $smp = $i * $itv;
	$hr = $smp/60; $mn = $smp % 60; my $tm = hm_string($hr, $mn); 
	$rowparity = $i&1;
	my $trow ="<td width=\"2%\" class=\"wvdtm$rowparity\"><font size=1><span class=\"wvBT\">$tm</span></font></td>";
	for($z=0; $z<$wklen; $z++) {
	    $colparity = $z&1;
	    my ($tmp, $tclr,$events); $events="";
	    my $ttable =$ttables[$z];
	    my $etable =$etables[$z];	    
	    my $ncols = $ncolns[$z];
	    if($i < $dayStart[$z] or $i >= $dayEnd[$z]) {
		#$tclr = "bgcolor=#cccccc"; $j=0;
		$tclr = "background=\"$::o{'imgdirurl'}/mask2.gif\""; 
	    } else { $j=$ttable->[$i]; $smp=$webcalConfig::r{'otColors'}->[$j]; $tclr="bgcolor=$smp";}
	    if($nusers <= 1) {
		if($editing) {
		    $events .= <<END;
<a href="javascript:da('$iwho','$days[$z]','$hr/$mn')"><img src="$::o{'imgdirurl'}/db.gif" width=16 height=12 border=0></a>
END
    ;
		} else {
		    $events .= <<END;
<img src="$::o{'imgdirurl'}/db.gif" width=16 height=12 border=0>
END
    ; 
		}
	    } else {
		if($editing) {
		    $events .= <<END;
<a href="javascript:db('$days[$z]','$hr/$mn')"><img src="$::o{'imgdirurl'}/db.gif" width=16 height=12 border=0></a>
END
    ;
		} else {
		    $events .= <<END;
<img src="$::o{'imgdirurl'}/db.gif" width=16 height=12 border=0>
END
    ;
		}
	    }
	    if($dnd) {$dndid="id=\"$iwho:$days[$z]$hr/$mn\"";}
	    my ($klass, @span, $scnt,$si, $sj, $uclr); @span = map("", (0..$ncols)); $si=0;
	    while($si < $ncols) {
		if($etable->[$i][$si] eq " ") {
		    $scnt=1; $sj = $si;
		    while($si+1 < $ncols and $etable->[$i][$si+1] eq " ") {
			$scnt++; $etable->[$i][$si+1] = ""; $si++;
		    }
		    if($scnt>1) {$span[$sj]="colspan=$scnt";}
		} 
		$si++;
	    }
	    if($i < $dayStart[$z] or $i >= $dayEnd[$z]) { $klass="wvOutsideTd1";} else {$klass="wvdbnk$rowparity$colparity";}
	    for($j = 0; $j < $ncols; $j++) {
		if($etable->[$i][$j] eq " ") {$trow .="<td $tclr $span[$j] class=\"$klass\" $dndid $dndop><font size=1>&nbsp;$events</font></td>";}
		elsif($etable->[$i][$j] ne "") {$trow .= $etable->[$i][$j];}
	    }
	}
	$out .= "<tr bgcolor=#ffffff>$trow</tr>";
    }


# events outside of day start/end interval
    if($outa) {
	$out .= "<tr class=\"wvRowOut1\"><td class=\"wvOutsideTd1\">&nbsp;</td>";    
	for($z=0; $z<$wklen; $z++) {
	    my $acnt = $acnts[$z];
	    my $after = $afters[$z];
	    my $ncols = $ncolns[$z];
	    my $insert="";
	    if($after) {
		my $tmp = ($acnt & 2);
		if($tmp and $acnt>1) { $insert="<td class=\"wvOutsideTd1\">&nbsp;</td>";}
		$out .= "<td colspan=$ncols valign=top class=\"wvOutsideTd1\"><table border=0 cellspacing=4 cellpadding=2 class=\"ebanner\" width=\"100%\"><tr class=\"wvOutsideTd1\">$after$insert</tr></table></td>";
	    } else {
		$out .= "<td colspan=$ncols class=\"wvOutsideTd1\">&nbsp;</td>";    
	    }
	}
	$out .= "</tr>";    
    }
    $out .= "</table></td></tr></table>"; 

    my ($nextc, $prevc);
    if(! $::calinfo{'pnt'}) {
	$nextc = "&nbsp;&nbsp;<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=2&d=$::o{'nextc'}/9/0$mg$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/rright.gif\" width=10 height=12 border=0></a>";
	$prevc = "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=2&d=$::o{'previousc'}/9/0$mg$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/rleft.gif\" width=10 height=12 border=0></a>&nbsp;&nbsp;";	  
    } else { $nextc = $prevc = "";}
    $stmp = "$::phr{'Week_starts_on'} ".mdy_string($nmonth,$nday,$nyear);

    return <<END;
<script language=Javascript type="text/javascript">
function da(u,d,t){
 var url="$::o{'cginame'}?c=ne&k=1&ls=$ls&v=2&w=" + u + "$::vmg&d="+d+t;
 document.location = url;
}
function db(d,t){
 var url="$::o{'cginame'}?c=ctd&k=1&ls=$ls&v=2$mg&w=$iwho$::vmg&d="+d+t;
 document.location = url;
}
</script>
<center>
<table border=0 cellspacing=0 cellpadding=1 width="$::o{'tw'}%"><tr><td width="25%" align=center>$::o{'qadd'}&nbsp;</td><td width="50%" align=center nowrap>
$fb $::mnbar<b><font color="#ff0000"><span class="wvTitle">$prevc$::srchn$stmp</span></font></b><font color="#009900"><span class="wvTitle">&nbsp;(# $wknum)$nextc</span></font>$::vnbar&nbsp;&nbsp;$options
</td><td width="25%" align=right nowrap valign=top>$searchf</td></tr></table>
</center>
$out
END
    ;
}

#==================================================================================

sub weekCalSummary {
    my ($d,$i, $j, $k, $m, $n, $itv, $cal, $iwho, $stmp, $ttmp,$table, $wcode, $tday, $month, $day, $year,$ls,$searchf,
	$sdate, $tdate, $out, @summary, $todayc, $todayc0, $chr, $cmn, $start, $end, $cmin, $color, $tag, $kind, $pnt, $wa, $wb,
	@wevents, $nday,$nmonth, $nyear, $bcnt, $etmp, $wklen, $percent, $wknum, $etype,$mg, $md, $ee, $diary, $key, $htb, $ppp, $borderwidth, $spacing);

    if($::d{'megaCal'} ne "") { $mg="&mg=$::d{'megaCal'}"; $etype="3&$::d{'editorState'}"; $ee=1;}
    else {$mg=""; $etype = 1; $ee=0;}
    ($month, $day, $year, $searchf) = (@_);
    if(not $searchf) {$searchf="&nbsp;";}
    @summary=(" ", " ", " ", " ", " ", " ", " ", " ", " ");
    @wevents=();
    $wcode= wday($month, $day, $year);
    if($wcode == 0 && $::o{'weekstart'}) {$wcode = 7;}
    $tday = $day - $wcode;
    $iwho = $::calinfo{'w'};
    $ls = $::calinfo{'ls'};
    $todayc = printDate( $::now{'month'}, $::now{'day'}, $::now{'year'});
    $todayc0 = printDate0( $::now{'month'}, $::now{'day'}, $::now{'year'});
    $chr = $::now{'hour'}; $cmin = $::now{'min'};
    my $dnd = ($::vm & 0x1000) ? 0 : 1;
    my ($dndid,$dndop)=("","");
    if($::o{'dnd'} and $dnd){
	$dndop ="ondragenter=\"dnden()\" ondragover=\"dndov()\" ondragleave=\"dndlv()\" ondrop=\"dnddp()\"" ;
    } else {$dnd = 0;}

    my ($options, $fb) = weekViewOptions($ls,$iwho,$month,$day,$year,$mg);

    my $dbgclr= $webcalConfig::r{'backgroundColor'};

    if($tday <= 0) {
	if($month == 0) {
	    $month = 11;  $year -= 1; $tday = 31 + $tday;
	} else {
	    $month -= 1;
	    if($month == 1) { if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}}
	    $tday = $::mdays[$month] + $tday;
	}
    }
    $::scntr=1;
#    my $wkendclr=""; 
    $wknum = weekNum($month,$tday+1,$year, $::o{'weekstart'});
    if($::o{'excludeWeekend'}) { $wklen = 5; $ppp=33;} 
    else { $wklen = 7; $ppp=25;}
#    else { $wklen = 7; $ppp=25; if($::calinfo{'wkendclr'}) {$wkendclr=$::calinfo{'wkendclr'};} }
    for($i = 0; $i < $wklen; $i++) {
	my $oi=$i +$::o{'weekstart'};
	$j=$tday+$oi;
	$tdate= printDate($month, $j, $year);
	$sdate= printDate0($month, $j, $year);
	($nmonth, $nday, $nyear) = canDate($month, $j, $year);
	$etmp = oneDaySummary($nmonth, $nday, $nyear, $todayc, $webcalConfig::fontsize{'wdsummary'}, 1);
	$diary = hasdiary($iwho, $sdate);
	if($diary){$diary="<a href=\"$::o{'cginame'}?c=diary&vd=1&w=$iwho&v=2&ls=$ls&d=$sdate$::vmg\"><img src=\"$::o{'imgdirurl'}/diary.gif\" width=16 height=14 border=0 align=right></a>";} else {$diary="";}
	$stmp = "$diary<center><a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=1&d=$sdate$mg$::vmg\">
<b><span class=\"wvWday\">$::wdays[$::o{'weekstart'}+$i]</span></b></a><font size=-2 color=#ff0000><span class=\"wvDay\">&nbsp;$nday</span></font></center>";
	$stmp .= "<br><font size=-2>" . $etmp . "</font>" if ($etmp);
	if($dnd){$dndid ="id=\"$iwho:$sdate\"";}
	if( $tdate eq $todayc) {
	    my $cbg=""; if($::cell_bg){ $cbg=&hack_cell_bg_style($webcalConfig::r{'todayHcolor'});}
	    $summary[$i] = "<td height=200 width=\"$ppp%\" bgcolor=$webcalConfig::r{'todayHcolor'} valign=top$cbg class=\"wvTdToday\" $dndid $dndop>$stmp</td>";
	  } else {
 	    my $bclr="#ffffff"; my $wknd=""; if($oi == 0 or $oi >=6){$wknd="wknd";}
	    #if($wkendclr and ($oi == 0 or $oi >=6)) { $bclr = $wkendclr;} else { $bclr="#ffffff";}
	    my $cbg=""; if($::cell_bg){ $cbg=&hack_cell_bg_style($bclr);}	    
	    $summary[$i] = "<td height=200 width=\"$ppp%\" bgcolor=$bclr valign=top$cbg class=\"wvTd$wknd\" $dndid $dndop>$stmp</td>";
	}

	# create summary for this day (getOneDayEvents done by oneDaySummary!)
	$htb={};
	for $key (keys %::oneDayEvents) {
	    $htb->{$key} = $::oneDayEvents{$key};
	}
	push @wevents, $htb;
	%::oneDayEvents =();
    }

    if($::calinfo{'interval'}) {$itv = $::calinfo{'interval'};} else {$itv=30;}

    if($::o{'weekstart'})   { ($nmonth, $nday, $nyear) = canDate($month, $tday+1, $year);}
    else { ($nmonth, $nday, $nyear) = ($month, $tday, $year);}
    $stmp = "$::phr{'Week_starts_on'} ".mdy_string($nmonth,$nday,$nyear);
    
    $pnt = $::calinfo{'pnt'};
    if($pnt){$borderwidth=1; $spacing=0;}else{$borderwidth=0;$spacing=1;} 
if($pnt or ($::vm & 0x80) ) { $table = "<br>"; $wa=99; $wb=1; }
else {
    my $no_editing = $::vm & 0x1000;
    $wa=70; $wb=30;
    $table= <<END;
<table border=0 cellpadding=0 cellspacing=0 width="100%" bgcolor="#909c9f" class="wvcftblHolder"><tr>
<td width="100%" bgcolor="#909c9f" class="wvcftblHolderTd">
<table border=$borderwidth cellpadding=0 class="wvcftbl" cellspacing=$spacing width="100%">
<tr><td bgcolor=$dbgclr class="wvCftRow1Td"><font size=1>&nbsp;</font></td>
END
    ;
    if($::o{'excludeWeekend'}) { $i = 16; } else { $i = 12;}
    for ($d=0; $d < $wklen; $d++) {
	$table .= "<td width=\"$i%\" align=center bgcolor=$dbgclr class=\"wvCftRow1Td\"><font size=-1><span class=\"wvCftRow1Txt\">$::swd[$::o{'weekstart'}+$d]</span></font></td>";
    }
    $table .= "</tr>\n";
    $start = $::calinfo{'hourB'};
    $end = $::calinfo{'hourE'};

    &getWorkingHourTable($iwho); 
    my($ztmp1, $ztmp2, $ztmp, $zbgn, $zend); 
    for($i = $start; $i < $end; $i++) {
	$ttmp=""; $ztmp = $i * 100;
	for($n=0; $n < 60; $n +=$itv) {
	    $ztmp1 = $ztmp + $n; $ztmp2 = $ztmp1 +$itv;
	    $ttmp .= "<tr><td align=center bgcolor=$dbgclr class=\"wvCftCol1Td\"><font size=-1><span class=\"wvCftCol1Txt\">".hm_string($i,$n)."</span></font></td>";
	    for($d=0; $d < $wklen; $d++) {
		my $zz = $d+$::o{'weekstart'};
		$m=$tday+$zz;
		$tdate= printDate0($month, $m, $year);
		$zbgn = $::WorkingHours[$zz]; $zend = $::WorkingHours[8+$zz];
		# compute the busy count
		$bcnt = 0;
		my $tip="";
		my ($htb, $key, $ihr, $imn, $fhr, $fmn);
		$htb= $wevents[$d];
		for $key (keys %{$htb}) {
		    ($ihr, $imn, $fhr, $fmn, $kind, $tag, $color) = split(/:/, $key);if($kind==4){$ihr=~ s/^\(\d+\)//;}
		    if($kind != 4) {
			my $tmp = intersectTimeinterval($ihr, $imn, $fhr, $fmn, $i, $n, $i, $n+$itv);
			if($tmp) {
			    $bcnt += $tmp;
			    my ($tcolor, $tim);
			    if($kind == 1) { $tcolor="$::o{'tclra'}"; $tim = hm_hm_string($ihr,$imn,$fhr,$fmn);}
			    elsif($kind == 2) { $tcolor="$::o{'tclrt'}"; $tim = hm_string($ihr,$imn);} 
			    elsif($kind == 3) { $tcolor="$::o{'tclrm'}"; $tim = hm_hm_string($ihr,$imn,$fhr,$fmn);} 
			    my $smp = $htb->{$key};
			    $tip .= "<font color=$tcolor>$tim:</font> $smp<br><br clear=\"all\">";
			}
		    }
		}
		my $bgc = "";
		if( $ztmp2 <= $zbgn or $ztmp1 >= $zend) { 
		    my $img; if ($bcnt == 0) { $bcnt = 6; $img="mask.gif";} else { $img="mask1.gif";}
		    $bgc = "background=\"$::o{'imgdirurl'}/$img\"";
		}
		if($tip) { 
		    my $tpid = addtip($tip);  
		    $tip = "onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"";
		}
		$k = $bcnt;
		if($k and $ee) {$md='ctd';}else{$md='ne';}
		if($tdate eq $todayc0) {
		    my $cclr= $webcalConfig::r{'otColors'}->[$k];
		    $cclr = $webcalConfig::r{'otColors'}->[5] if !defined $cclr;
		    if(!$bgc) { $bgc = "bgcolor=$cclr";}
		    if($no_editing) {
			$ttmp .= "<td $bgc class=\"cftdy$k\"><font size=-1 color=$cclr>&nbsp;&nbsp;&nbsp;&nbsp;</font></td>";
		    } else {
			my $href="$::o{'cginame'}?c=$md&k=$etype&w=$iwho&d=$tdate/$i/$n$mg$::vmg";
			if($dnd){$dndid="id=\"$iwho:$tdate/$i/$n\"";}
			$ttmp .= "<td $bgc class=\"cftdy$k\" align=center onclick=\"ngoto(this,'$href')\" $dndid $dndop>
<a href=\"$href\" $tip><font size=-1 color=$cclr>&nbsp;&nbsp;&nbsp;&nbsp;</font></a></td>";
		    }
		} else {
		    my $cclr= $webcalConfig::r{'oColors'}->[$k];
		    $cclr = $webcalConfig::r{'oColors'}->[5] if !defined $cclr;
		    if(!$bgc) { $bgc = "bgcolor=$cclr";}
		    if($no_editing) {
			$ttmp .= "<td $bgc class=\"cftd$k\"><font size=-1 color=$cclr>&nbsp;&nbsp;&nbsp;&nbsp;</font></td>";
		    } else {
			if($dnd){$dndid="id=\"$iwho:$tdate/$i/$n\"";}
			my $href="$::o{'cginame'}?c=$md&k=$etype&w=$iwho&d=$tdate/$i/$n$mg$::vmg";
			$ttmp .= "<td $bgc class=\"cftd$k\" align=center onclick=\"ngoto(this,'$href')\" $dndid $dndop>
<a href=\"$href\" $tip><font size=-1 color=$cclr>&nbsp;&nbsp;&nbsp;&nbsp;</font></a></td>";
		    }
		}
	    }
	    $ttmp .= "</tr>\n";
	    if($i == $end) { last;}
	}
	$table .= $ttmp . "\n";
    }
    $table .= "</table></td></tr></table>\n";
   } # not print
    my ($nextc, $prevc);
    if(! $::calinfo{'pnt'}) {
	$nextc = "&nbsp;&nbsp;<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=2&d=$::o{'nextc'}/9/0$mg$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/rright.gif\" width=10 height=12 border=0></a>";
	$prevc = "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$iwho&v=2&d=$::o{'previousc'}/9/0$mg$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/rleft.gif\" width=10 height=12 border=0></a>&nbsp;&nbsp;";	  
    } else { $nextc = $prevc = "";}
    if($::o{'excludeWeekend'}) {
	$out= <<END;
<center>
<table border=0 cellspacing=0 cellpadding=1 width="$::o{'tw'}%"><tr><td width="25%" align=center>$::o{'qadd'}&nbsp;</td><td width="50%" align=center nowrap>
$fb $::mnbar<b><font color="#ff0000"><span class="wvTitle">$prevc$stmp</span></font></b><font color="#009900"><span class="wvTitle">&nbsp;(# $wknum)$nextc</span></font>$::vnbar&nbsp;&nbsp;$options
</td><td width="25%" align=right nowrap valign=top>$searchf</td></tr></table>
</center>
<table border=0 cellpadding=2 cellspacing=0 width="$::o{'tw'}%"><tr valign=top><td width="$wa%">
<table border=0 cellpadding=0 cellspacing=0 width="100%" bgcolor="#c0cccf" class="backtblwcal">
<tr><td width="100%" bgcolor="#c0cccf" class="backtblwcal">
<table border=$borderwidth cellpadding=0 cellspacing=$spacing width="100%" class="wvtbl">
<tr> $summary[0]
     $summary[1]
     $summary[2]
</tr>
<tr> $summary[3]
     $summary[4]
    <td width="17%" align=center bgcolor=$webcalConfig::r{'dkbackground'} valign=middle class="wvTd">$webcalConfig::r{'cgiInfoA'}</td>
</tr>
</table></td></tr></table>
</td><td width="$wb%">
$table
</td></tr></table>
END
;
  } else {
      $out= <<END;
<center>
<table border=0 cellspacing=0 cellpadding=1 width="$::o{'tw'}%"><tr><td width="25%" align=center>$::o{'qadd'}&nbsp;</td><td width="50%" align=center nowrap>
$fb $::mnbar<b><font color="#ff0000"><span class="wvTitle">$prevc$::srchn$stmp</span></font><font color="#009900"><span class="wvTitle">&nbsp;(# $wknum)</font>$nextc</span>$::vnbar&nbsp;&nbsp;$options
</td><td width="25%" align=right nowrap valign=top>$searchf</td></tr></table>
</center>
<table border=0 cellpadding=2 cellspacing=0 width="$::o{'tw'}%"><tr valign=top><td width="$wa%">
<table border=0 cellpadding=0 cellspacing=0 width="100%" bgcolor="#c0cccf" class="backtblwcal">
<tr><td width="100%" bgcolor="#c0cccf" class="backtblwcal">
<table border=$borderwidth cellpadding=2 cellspacing=$spacing width="100%" class="wvtbl">
<tr> $summary[0]
     $summary[1]
     $summary[2]
     $summary[3]
</tr>
<tr> $summary[4]
     $summary[5]
     $summary[6]
    <td width="17%" align=center valign=middle bgcolor=$webcalConfig::r{'dkbackground'} class="wvTd">$webcalConfig::r{'cgiInfoA'}</td>
</tr>
</table></td></tr></table>
</td><td width="$wb%">
$table
</td></tr></table>
END
;
    }
    return $out;
}

#=====================================================================================================
#
sub oneDayDetail {
    my ($i, $j, $k,$iwho, $cal, $stmp, $t, $month, $day, $year, $out, $start, $end, $special,$diary,$href,
	@keys, $key, $tmp, $hr, $mn, $ehr, $emn, $ump, $tim, $kind, $tag, $todayc, $color, $tdcolor, $percent);
    my ($before, $after) = ("","");
    ($month, $day, $year,$todayc) = (@_);
    $iwho = $::calinfo{'w'};

    $out = "";
    $start = $::calinfo{'hourB'};
    $end = $::calinfo{'hourE'};
    getOneDayEvents($month, $day, $year, $todayc, 0);
    @keys = sort sorttime (keys %::oneDayEvents);
    my $dnd = ($::vm & 0x1000) ? 0 : 1;
    my ($dndid, $dndop, $sdate)=("","","");
    if($::o{'dnd'} and $dnd){
        $sdate="$month/$day/$year";
	$dndop ="ondragenter=\"dnden()\" ondragover=\"dndov()\" ondragleave=\"dndlv()\" ondrop=\"dnddp()\"" ;
    } else {$dnd = 0;}
    # events before $start and after $end;
    for $key (@keys) {
	$cal = "";
	($hr,$mn, $ehr, $emn, $kind, $tag, $color)=split(/:/, $key);if($kind==4){$hr=~ s/^\(\d+\)//;}
	if($hr ne "" and ($hr < $start or $hr > $end)) {
	    $tim = hm_hm_string($hr,$mn,$ehr,$emn);
	    $tmp = $::oneDayEvents{$key};
	    $href = $tmp;
	    if($href =~ m/<a (href="[^"]*").*/) {$href = $1;} else {$href="";} #")
	    $href =~ s/(c=ed)|(c=cfm)/c=m2/s;
	    if($color) { $tdcolor="bgcolor=$color";} else {$tdcolor="";};
	    if($kind == 1) {
		$cal = "<tr class=\"et1\"><td class=\"ec1\" width=\"4%\" noWrap $tdcolor><font size=-1><a $href class=\"ztt1\"><font color=$::o{'tclra'}>$tim &nbsp;</font></a></font></td><td class=\"ec1\" align=left $tdcolor><font size=-1>$tmp</font></td></tr>\n";
	    } elsif ($kind == 2) {
		if($mn == 99) { $tim = "<img src=\"$::o{'imgdirurl'}/larr.gif\" width=14 height=10 border=0 alt=\"\">";}
		$cal = "<tr class=\"et2\"><td class=\"ec2\" width=\"4%\" noWrap $tdcolor><font size=-1><a $href class=\"ztt2\"><font color=$::o{'tclrt'}>$tim &nbsp;</font></a></font></td><td class=\"ec2\" align=left $tdcolor><font size=-1>$tmp</font></td></tr>\n";
	    } elsif ($kind == 3) {
		$cal = "<tr class=\"et3\"><td class=\"ec3\" width=\"4%\" noWrap $tdcolor><font size=-1><a $href class=\"ztt3\"><font color=$::o{'tclrm'}>$tim &nbsp;</font></a></font></td><td class=\"ec3\" align=left $tdcolor><font size=-1>$tmp</font></td></tr>\n";
	    }
	    if($hr < $start) { $before .= $cal;} else {$after .= $cal;}
	}
    }
    if($before) {
	$out .= "<tr bgcolor=$webcalConfig::r{'dkbackground'}><td class=\"dvOutsideTd0\">&nbsp;</td><td class=\"dvOutsideTd1\"><table border=0 cellspacing=0 cellpadding=0 class=\"dvetc\">$before</table></td></tr>"; 
    }

    # events in [$start, $end]
    for($i = $start; $i <= $end; $i++) {
	if (not $::o{'hourformat'}) {
	  if($i <12) { $j = $i; $k = "am";}
	  elsif ($i> 12) { $j = $i-12; if($j<12) {$k="pm";} else { $k="am";}}
	  else {$j = $i; $k="pm";}
	}
	else { $j = $i; $k=""; } $j=sprintf "%02d", $j;
	$cal="";
	my $nes = 0;
	for $key (@keys) {
	    ($hr,$mn, $ehr, $emn, $kind, $tag, $color)=split(/:/, $key);if($kind==4){$hr=~ s/^\(\d+\)//;}
	    if($hr ne "" and $hr == $i) {
		$tim = hm_hm_string($hr,$mn,$ehr,$emn);
		$tmp = $::oneDayEvents{$key};
		$href = $tmp;
		if($href =~ m/<a (href="[^"]*").*/) {$href = $1;} else {$href="";} #")
		#$href =~ s/<a (href="[^"]*").*/$1/s; #"
		$href =~ s/(c=ed)|(c=cfm)/c=m2/s;
		if($color) { $tdcolor="bgcolor=$color";} else {$tdcolor="";};
		if($kind == 1) { $nes++;
		    $cal .= "<tr class=\"et1\"><td class=\"ec$kind\" width=\"4%\" noWrap $tdcolor><font size=-1><a $href class=\"ztt1\"><font color=$::o{'tclra'}>$tim &nbsp;</font></a></font></td><td class=\"ec$kind\" align=left width=\"96%\" $tdcolor><font size=-1>$tmp</font></td></tr>\n";
		} elsif ($kind == 2) { $nes++;
		    if($mn == 99) { $tim = "<img src=\"$::o{'imgdirurl'}/larr.gif\" width=14 height=10 border=0 alt=\"\">";}
		    $cal .= "<tr class=\"et2\"><td class=\"ec$kind\" width=\"4%\" noWrap $tdcolor><font size=-1><a $href class=\"ztt2\"><font color=$::o{'tclrt'}>$tim &nbsp;</font></a></font></td><td class=\"ec$kind\" align=left width=\"96%\"  $tdcolor><font size=-1>$tmp</font></td></tr>\n";
		} elsif ($kind == 3) { $nes++;
		    $cal .= "<tr class=\"et3\"><td class=\"ec$kind\" width=\"4%\" noWrap $tdcolor><font size=-1><a $href class=\"ztt3\"><font color=$::o{'tclrm'}>$tim &nbsp;</font></a></font></td><td class=\"ec$kind\" align=left width=\"96%\"  $tdcolor><font size=-1>$tmp</font></td></tr>\n";
		}
	    }
	}
	if($cal) {
	    $cal = "<table class=\"ecombined\" border=0 cellpadding=0 cellspacing=0 width=\"100%\">\n" . $cal . "</table>\n";
	} else { $cal = "<br>";}
	if($dnd) {$dndid="id=\"$iwho:$sdate/$i/0\"";} else {$dndid="";}
	my $cclr= $webcalConfig::r{'oColors'}->[$nes];
	$out .= "<tr><td width=\"4%\" class=\"ebt$nes\" bgcolor=$cclr height=36 $dndid $dndop><span class=\"dvT\">$j$k</span></td><td class=\"ec0\" bgcolor=#ffffff width=\"96%\" $dndid $dndop>$cal</td></tr>\n";
    }
    $special="";
    for $key (@keys) {
      ($hr,$mn, $ehr, $emn, $kind, $tag, $color)=split(/:/, $key);if($kind==4){$hr=~ s/^\(\d+\)//;}
      if($kind == 4) {
	if($color) { $tdcolor=" bgcolor=$color\"";} else {$tdcolor="";};
	$tmp = $::oneDayEvents{$key};
	$special .= "<tr class=\"et4\"><td width=\"4%\" class=\"ec4\" $tdcolor><font size=-1>&nbsp;</td><td align=left class=\"ec4\" $tdcolor width=\"96%\"><font size=-1>$tmp</font></td></tr>\n";
    }
  }
    if($after) {
	$out .= "<tr bgcolor=#ffffff><td class=\"dvOutsideTd0\">&nbsp;</td><td class=\"dvOutsideTd1\"><table border=0 cellspacing=0 cellpadding=0 class=\"dvetc\">$after</table></td></tr>" ;
    }
    if($special) {$out =  "<tr bgcolor=#ffffff><td class=\"dvOutsideTd0\"><img src=\"$::o{'imgdirurl'}/sm.gif\" width=19 height=8 border=0 alt=\"\"></td><td class=\"dvOutsideTd1\"><font size=1><br></font><table class=\"dvetc\" border=0 cellspacing=0 cellpadding=0 width=\"100%\">$special</table>
<font size=1><br></font></td></tr>" . $out; }
    $out .= "</table>\n";

    my($spacing, $border); if($::calinfo{'pnt'}) {$border=1; $spacing=0;}else{$border=0;$spacing=1;}
    return  <<END;
<table border=0 cellpadding=0 cellspacing=0 width="100%" bgcolor="#c0ccff" class="backtbldvc"><tr><td class="backtbldvc" width="100%" bgcolor="#c0cccf">
<table border=$border cellpadding=0 cellspacing=$spacing width="100%" bgcolor="#c0c0ff" class="dvcHolder">$out
</td></tr></table>
END

; 
}
#=====================================================================================================
sub oneDayList {
  my ($i, $j, $k,$iwho, $cal, $stmp, $t, $month, $day, $year, $out, $detail, $count, $bclr,$view, $ls, $jj, $kk,$jnk,
      @keys, $key, $tmp, $hr, $mn, $ehr, $emn, $ump, $tim, $kind, $tag, $todayc, $color, $tdcolor, $tcolor, $href);
  ($month, $day, $year,$todayc, $jj) = (@_);
  $iwho = $::calinfo{'w'};
  $view = $::calinfo{'v'};
  $ls = $::calinfo{'ls'};
  $stmp = mdy_wstring($month,$day,$year);
  if($ls < 0) {  $::oneDayDetails  = 2;} else {   $::oneDayDetails  = 1;}
  getOneDayEvents($month, $day, $year, $todayc, 0);
  $::oneDayDetails  = 0;
  @keys = sort sorttime (keys %::oneDayEvents);
  $count = scalar @keys;
  $out="";
  if($count > 0 ) {
      if($ls >=0) {
	  my ($dateinfo, $mname, $wname, $wcode, $diary, $sep);
	  $wcode= wday($month,$day,$year);
	  $mname=$::mNames[$month];
	  $wname=$::swd[$wcode];
	  if($::d{'megaCal'} ne "") { $sep=1;} else {$sep=0;}
	  $diary=hasdiary($iwho, "$month/$day/$year");
	  if($diary) {
	      $diary = "<a href=\"$::o{'cginame'}?c=diary&vd=1&w=$iwho&v=$view&ls=$ls&d=$month/$day/$year$::vmg\"><img src=\"$::o{'imgdirurl'}/diary.gif\" width=16 height=14 border=0></a>";
	  } else {$diary="";}

	  $bclr = $webcalConfig::r{'rowColors'}->[$jj];
	  $dateinfo = "<td nowrap width=\"5%\" class=\"v2DateTd$jj\" bgcolor=$bclr rowspan=$count align=center valign=middle><span class=\"v2Date\">$mname $day<br></span><font color=#cc6633>$diary<b><span class=\"v2Day\">$wname</span></font></td>";
	  $kk = 0;
	  for $key (@keys) {
	      ($hr,$mn, $ehr, $emn, $kind, $tag, $color)=split(/:/, $key);if($kind==4){$hr=~ s/^\(\d+\)//;}
	      $tim = hm_hm_string($hr,$mn,$ehr,$emn) if($kind != 4);
	      $cal="";
	      $tmp = $::oneDayEvents{$key};
	      $detail = $::oneDayDetails{$key};
	      $detail = "<br>" unless $detail;
	      if($color) { $tdcolor="bgcolor=$color"; } 
	      else {
		  my $clr = $webcalConfig::r{'rowColors'}->[$jj+$kk];
		  if(!$clr) {$clr = $webcalConfig::r{'rowColors'}->[($jj ? 1: 0)];}
		  $tdcolor="bgcolor=$clr";
		  $kk = ($kk)? 0 : 3;
	      }
	      $href = $tmp;
	      if($::calinfo{'dmode'}){
		  if($href =~ m/<a href="([^"]*)".*/) {$href = $1;} else {$href="";} #"
	          $href =~ s/(c=ed)|(c=cfm)/c=m2/s;
	          if($href=~/^javascript/i) { $href="href=\"$href\"";}
	          else {$href="href=\"javascript:pdl('$href')\"";}
	      } else {
		  if($href =~ m/<a (href="[^"]*").*/) {$href = $1;} else {$href="";} #")
		  $href =~ s/(c=ed)|(c=cfm)/c=m2/s;
	      }
	      if($kind == 1) {
		  $tcolor=$::o{'tclra'};
	      } elsif ($kind == 2) {
		  if($mn == 99) { $tim = "<img src=\"$::o{'imgdirurl'}/larr.gif\" width=14 height=10 border=0 alt=\"\">";}
		  $tcolor=$::o{'tclrt'};
	      } elsif ($kind == 3) {
		  $tcolor=$::o{'tclrm'};
	      } elsif ($kind == 4) {
		  $tcolor=$::o{'tclrs'};
		  #$tim="###";
		  #$tim = "<img src=\"$::o{'imgdirurl'}/sm.gif\" width=19 height=8 border=0 alt=\"\">";
		  $tim = "$::phr{'AllDay'}";
		  $tmp = "<b>$tmp</b>";
	      }
	      $out .= "<tr>$dateinfo<td class=\"v2eTd1$jj\" width=\"10%\" noWrap $tdcolor><font size=-1><a $href class=\"ztt$kind\"><font color=$tcolor>$tim</font></a></font></td><td class=\"v2eTd2$jj\" width=\"40%\" $tdcolor><font size=-1><span class=\"v2Title\">$tmp</span></font></td><td class=\"v2eTd3$jj\"width=\"45%\" $tdcolor><font size=-1><span class=\"v2Detail\">$detail</span></font></td></tr>\n";
	      $dateinfo="";
	  }
	  if($sep) {
	      $out .= "<tr><td colspan=4 class=\"v2filler\" bgcolor=#0099cc><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=1 height=1 border=0></td></tr>";
	  }
	  return(1, $out);
      } else { #ls < 0; print detailed view
	  my ($diary, $tmp, $dstyle, $mode, $mdy, $privacy, $jj);
	  $diary=hasdiary($iwho, "$month/$day/$year");
	  if($diary) {
	      $diary = "<a href=\"$::o{'cginame'}?c=diary&vd=1&w=$iwho&v=$view&ls=$ls&d=$month/$day/$year$::vmg\"><img src=\"$::o{'imgdirurl'}/diary.gif\" width=16 height=14 border=0></a>";
	  } else {$diary="";}
	  $mdy = mdy_wstring($month, $day, $year);
	  $mode = $::vm & 0x200;
	  if($mode) {
	      @keys = sort sorttime (keys %::oneDayEventRefs);
	      $out .= "<tr><td colspan=4 height=2><img src=\"$::o{'imgdirurl'}/blue.gif\" width=\"100%\" height=2 border=0></td></tr>";
	      if($view != 1) { $out .= "<tr><td class=\"v3td0\" colspan=4 bgcolor=#eeeeff><font color=#666699><span class=\"v34Date\">$mdy</span></font>$diary</td></tr>";}
	      for $key (@keys) {
		  ($hr,$mn, $ehr, $emn, $kind, $tag, $color, $privacy)=split(/:/, $key);if($kind==4){$hr=~ s/^\(\d+\)//;}
		  if(!$privacy) { $privacy = $color;}
		  my $eref = $::oneDayEventRefs{$key};
		  $tmp = printEvent($eref, $privacy, 2, 1, "$month/$day/$year");
		  $out .= <<END;
<tr><td colspan=4 height=1><img src="$::o{'imgdirurl'}/blu.gif" width="100%" height=1 border=0></td></tr>
<tr><td colspan=4 align=center>$tmp</td></tr>
<tr><td colspan=4 align=center><br></td></tr>
END
;
	      }
	  } else {
	      if($::d{'estyle'}) { $dstyle = $::d{'estyle'};} else {$dstyle = 0;}
	      $out .= "<tr><td colspan=4 height=2><img src=\"$::o{'imgdirurl'}/blue.gif\" width=\"100%\" height=2 border=0></td></tr>";
	      if($view != 1) { $out .= "<tr><td colspan=4 bgcolor=#eeeeff class=\"v3td0\"><font color=#666699><span class=\"v34Date\">$mdy</span></font>$diary </td></tr>";}
	      $out .= <<END;
<tr><td colspan=4 height=2><img src="$::o{'imgdirurl'}/blu.gif" width="100%" height=2 border=0></td></tr>
<tr><td><font color="#96969f" size=1><span class="v3Label">$::phr{'Time'}</span></font></td><td><font color="#96969f" size=1><span class="v3Label">$::phr{'Event'}</span></font></td><td><font color="#96969f" size=1><span class="v3Label">$::phr{'Location'}</span></font></td><td><font color="#96969f" size=1><span class="v3Label">$::phr{'Category'}</span></font></td></tr>
END
;
	      
	      $kk = 0;
	      for $key (@keys) {
		  my($stim, $tip) = ("", "");
		  ($hr,$mn, $ehr, $emn, $kind, $tag, $color)=split(/:/, $key);if($kind==4){$hr=~ s/^\(\d+\)//;}
		  if($color) { $tdcolor="bgcolor=$color"; } else {$tdcolor="";}
		  $tim = hm_string($hr, $mn);
		  if($kind != 4 and $kind != 2) {
		      $stim = hm_hm_string($hr,$mn,$ehr,$emn);
		      if($dstyle) { $tim = $stim;}
		      elsif($hr ne $ehr or $mn ne $emn) {
			  my $tpid = add3tip($stim);
			  $tip = " onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"";
		      }
		  }
		  my ($misc, $troom, $tspkr, $tcat) = ("","<br>","<br>","<br>"); 
		  if(exists $::oneDayRooms{$key}) { $troom = $::oneDayRooms{$key}; }
		  if(exists $::oneDayCats{$key}) { $tcat = $::oneDayCats{$key}; }
		  if(exists $::oneDaySpkrs{$key}) { $tspkr .= $::oneDaySpkrs{$key}; }
		  $tmp = $::oneDayEvents{$key};
		  $detail = $::oneDayDetails{$key};
		  $detail = "<br>" unless $detail;
		  $href = $tmp;
		  if($::calinfo{'dmode'}){
		      if($href =~ m/<a href="([^"]*)".*/) {$href = $1;} else {$href="";} #"
		      $href =~ s/(c=ed)|(c=cfm)|(c=ec)/c=m2/s;
	              if($href=~/^javascript/i) { $href="href=\"$href\"";}
  	              else {$href="href=\"javascript:pdl('$href')\"";}
	          } else {
		      if($href =~ m/<a (href="[^"]*").*/) {$href = $1;} else {$href="";} #")
		      $href =~ s/(c=ed)|(c=cfm)|(c=ec)/c=m2/s;
		  }
		  #$tmp=~ s/<font color=/<font clr=/g;
		  if($kind == 1) {
		      $tcolor=$::o{'tclra'};
		  } elsif ($kind == 2) {
		      if($mn == 99) { $tim = "<img src=\"$::o{'imgdirurl'}/larr.gif\" width=14 height=10 border=0 alt=\"\">";}
		      $tcolor=$::o{'tclrt'};
		  } elsif ($kind == 3) {
		      $tcolor=$::o{'tclrm'};
		  } elsif ($kind == 4) {
		      $tcolor=$::o{'tclrs'};
		      $tim = "$::phr{'AllDay'}";
		  }
#      print "<tr><td colspan=4 bgcolor=#006498 height=1><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=10 height=1 border=0></td></tr>";
	      $out .= <<END;
<tr><td colspan=4 height=1><img src="$::o{'imgdirurl'}/blu.gif" width="100%" height=1 border=0></td></tr>
<tr><td valign=top class="v3td$kind"><font size=-1><a $href $tip class="ztt$kind"><font color=$tcolor>$tim</font></a></font></td>
<td class="v3td$kind" valign=top $tdcolor><font size=-1><b><span class="v3title">$tmp</span></b></font><font size=-2><span class="v3Speaker">$tspkr</span></font></td>
<td class="v3td$kind" valign=top><font size=-1><span class="v3Location">$troom</span></font></td>
<td class="v3td$kind" valign=top><font size=-1><span class="v3Category">$tcat</span></font></td>
</tr>
END
;
	      }
	  }
	  return ($count, $out);
      }
  }
  return(0,"");
}
#=====================================================================================================
sub oneDaySummary {
    my ($key, $out, $tmp, $tim, $hr, $mn, $kind, $eh, $em, $dstyle,
	$color, $tcolor, $tip, $href, $tag, $tdcolor, @allkeys);
    my ($month, $day, $year, $todayc, $size, $flag) = (@_);

    getOneDayEvents( $month, $day, $year, $todayc, 0);
    
    if($::d{'estyle'}) { $dstyle = $::d{'estyle'};} else {$dstyle = 0;}

    if($::scntr) {
	my @k4=(); my @k1=();
	for $key (keys %::oneDayEvents) {
	    if($key =~ /^\(/) {	push @k4, $key; }
	    else { push @k1, $key;}
	}
	@allkeys = ((sort @k4), (sort sorttime @k1));
    } else {
	@allkeys = (sort sorttime keys %::oneDayEvents);
    }
    $out= "";
    for $key (@allkeys) {
	($hr,$mn,$eh,$em,$kind,$tag,$color)=split(/:/, $key);if($kind==4){$hr=~ s/^\(\d+\)//;}
	$tip = undef;
	$tim = hm_string($hr,$mn);
	$tmp = $::oneDayEvents{$key};
	my $cstyle="et$kind";
	if($color) { $tdcolor=" bgcolor=$color";} else {$tdcolor="";}
	if($kind == 1) {
	    $tcolor=$::o{'tclra'};
	    if($hr ne $eh or $mn ne $em) {$tip = hm_hm_string($hr,$mn,$eh,$em);}
	} elsif ($kind == 2) {
	    if($mn == 99) { $tim = "<img src=\"$::o{'imgdirurl'}/larr.gif\" width=14 height=10 border=0 alt=\"\">";}
	    $tcolor=$::o{'tclrt'};
	} elsif ($kind == 3) {
	    $tcolor=$::o{'tclrm'};
	    if($hr ne $eh or $mn ne $em) {$tip = hm_hm_string($hr,$mn,$eh,$em);}
	} else {
	    $tcolor=$::o{'tclrs'};
	    #$tim="###";
	    my $imgf;
	    if($::cell_bg_t and $::cell_bg_t eq $tag) {
		$imgf="spacer"; $cstyle="special";
	    } else {$imgf="sm";}
	    $tim = "<img src=\"$::o{'imgdirurl'}/${imgf}.gif\" width=19 height=8 border=0 alt=\"\">";
	}
	# my $class=""; if($tmp =~ /(class=\"[^\"]+\")/) { $class = $1;} #"
	$href = $tmp;
	if($::calinfo{'dmode'}){
	    if($href =~ m/<a href="([^"]*)".*/) {$href = $1;} else {$href="";} #"
            $href =~ s/(c=ed)|(c=cfm)/c=m2/s;
	    if($href=~/^javascript/i) { $href="href=\"$href\"";}
	    else {$href="href=\"javascript:pdl('$href')\"";}
	} else {
	    if($href =~ m/<a (href="[^"]*").*/) {$href = $1;} else {$href="";} #")
	    $href =~ s/(c=ed)|(c=cfm)/c=m2/s;
	}
	if($dstyle) {
	    if($tip) { 
		if($tip =~ /\-/) {
		    $tim="<font $size><a $href class=\"ztt$kind\"><font color=$tcolor>$tip</font></a></font>";
		    $out .= "<tr class=\"$cstyle\"><td$tdcolor class=\"$cstyle\" colspan=2>$tim</td></tr><tr><td$tdcolor class=\"$cstyle\" width=\"10%\"><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=20 height=1 border=0></td><td$tdcolor class=\"$cstyle\"><font $size>$tmp</font></td></tr>\n";
		} else {
		    $tim="<font $size><a $href class=\"ztt$kind\"><font color=$tcolor>$tip&nbsp;</font></a></font>";
		    $out .= "<tr class=\"$cstyle\"><td$tdcolor class=\"$cstyle\" valign=top width=\"10%\" noWrap>$tim</td><td$tdcolor class=\"$cstyle\"><font $size>$tmp</font></td></tr>\n";
		}
	    } else {
		$tim="<font $size><a $href class=\"ztt$kind\"><font color=$tcolor>$tim&nbsp;</font></a></font>";
		$out .= "<tr class=\"$cstyle\"><td$tdcolor class=\"$cstyle\" valign=top width=\"10%\" noWrap>$tim</td><td$tdcolor class=\"$cstyle\"><font $size>$tmp</font></td></tr>\n";
	    }
	} else {
	    if ($tip) {
		my $tpid=add3tip($tip);
		$tim = "<font $size><a $href class=\"ztt$kind\" onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"><font color=$tcolor>$tim</font></a>&nbsp;</font>";
	    } else {
		$tim = "<font $size><a $href class=\"ztt$kind\"><font color=$tcolor>$tim&nbsp;</font></a></font>";
	    }
	    $out .= "<tr class=\"$cstyle\"><td$tdcolor class=\"$cstyle\" valign=top width=\"10%\" noWrap>$tim</td><td$tdcolor class=\"$cstyle\"><font $size>$tmp</font></td></tr>\n";
	}
    }
    if($out) { $out = "<table class=\"et\" border=0 cellpadding=0 cellspacing=0 width=\"100%\" background=\"\">" . $out . "</table>";}
    return $out;
}

#======================================================================================================
sub getPrivacy {
    my ($flag) =(@_);
    my ($mg, $gprivacy, $tmp, $who);
    $who = $::calinfo{'w'};

    if($flag and $::d{'megaCal'}) { # MegaCal uses event based privacy.
	$mg="&mg=$::d{'megaCal'}"; 
        $gprivacy=3;
    } else {
	$mg="";
	$gprivacy = $::d{'authResult'} | $::d{'ispublic'};
	if($gprivacy != 4) {
	    if(isre($::d{'remote_user'}, $who, 'readers')) { $gprivacy = 4;}
	    else {
		if($::calinfo{'privacy'}) {$tmp=$::calinfo{'privacy'}; $gprivacy = $::privacyTable{$tmp} - 1;}
	    }
	}
    }
    return ($gprivacy, $mg);
}
#===============================================================================================
sub precedence {
    # See occurenceHash for definitions
    #               0  1 2 3  4  5  6  7  8  9  10 11 12 13 14 15 16 17
    my (@table) = (80,80,0,80,80,80,80,80,10,40,60,80,20,30,70,70,80,80); 
    my ($rule)=(@_); my $v = 0;
    my $aref = $::occurenceHash{$rule};
    if($aref) { $v = $aref->[0];}
    return $table[$v];
}
#===============================================================================================
sub getOneDayEvents {
    use integer;
    my ($date, $repeat, $today, $i, $month, $day, $year, $kind, $smp, $tim,$cfm,
	$dmonth, $duration, $ehr, $emn,$utmp, $hr, $mn, $key, $who, $view,$edate, $href, $mg,
	$nowM, $nowD, $nowY, $nowH, $nowN, $nowS, $warning, $timenow, $gprivacy, $todayc,$ls,
	$endM, $endD, $endY, $cflag, $ed, $srefs,$istoday,$overdue, $overdueDate, $pop,$popa,$popb,
	$hour, $min, $reminder, $mail,$mailu, $maili, $maily, $flash, $flashi, $flashu, $flashy, $matched, $detail,
	$popup, $popupi, $popupu, $popupy, $chime, $chimei, $chimeu, $chimey, $junk, $rurl, $URL, $eprivacy, $tc, $bg);

    ($month, $day, $year, $todayc, $cflag) = (@_);
    $dmonth = $month + 1;
    $today= "$dmonth/$day/$year";
    $who = $::calinfo{'w'};
    $view = $::calinfo{'v'};
    $ls = $::calinfo{'ls'} || 0;
    $pop=1 if $::calinfo{'dmode'};
    if($::vm & 0x40) { $ed = "m2";} elsif($ls < 0) { $ed="ec";} else {$ed="ed";$pop=0;}
    if($pop){$popa="javascript:pdl('";$popb="')";}else{$popa=$popb="";}
    $nowM = $::now{'month'}; $nowD = $::now{'day'}; $nowY = $::now{'year'};
    $nowH = $::now{'hour'}; $nowN = $::now{'min'};  $nowS = $::now{'sec'};
    if($nowM == $month and $nowD == $day and $nowY == $year) { $istoday = 1;} else {$istoday = 0;}
    
    ($gprivacy, $mg) = &getPrivacy(1);
    
    $srefs = ($::vm & 0x200); $duration=0;
    %::oneDayEvents=();
    %::oneDayDetails = ();
    %::oneDayMisc = ();
    %::oneDayRooms = ();
    %::oneDaySpkrs = ();
    %::oneDayCats = ();
    %::oneDayEventRefs = ();
    $::cell_bg=""; $::cell_bg_t="";
    
    $timenow = timeLocal($nowS,$nowN,$nowH,$nowD,$nowM,$nowY);
    $hour = $::now{'hour'};  $min = $::now{'min'};
    my $irepository = "$::o{'imgdirurl'}/$::o{'uploadsubdir'}";

    my $dnd = ($::vm & 0x1000) ? 0 : 1;
    if(not ($::o{'dnd'} and $dnd)) { $dnd = 0;}
    
    for $href (@::caldata) {
	next if $href->{'deleted'};
	if( $href->{'pnd'}) {
	    next if not $::d{'ceditor'};
	    next if $href->{'pnd'} ne $who;
	}
	if($gprivacy > 3) { $eprivacy = 3;}
	else {
	    if(defined $href->{'e'} or (defined $href->{'w'} and $href->{'w'} eq $::d{'remote_user'})) { $eprivacy = 3;} #for megaCalendar
	    elsif(defined $href->{'privacy'}) { $eprivacy = $::privacyTable{$href->{'privacy'}} -1;}
	    else {$eprivacy = $gprivacy;}
	}
	next if $eprivacy == 0;
	next if not &$::catfiltersub($href->{'cat'});
	if($::srchftrptn) { next if not match_search_words($href,$eprivacy);}
	$kind =  $href->{'kind'};
	if($href->{'end'}) {
	    my $ckend = 1;
	    if($kind == 2) {
		my $done = $href->{'done'};
		if(!$::calinfo{'dctoc'} and defined $done && $done eq 'y') { next;} 
		else { my $forward = $href->{'forward'};  if(defined $forward && $forward eq 'y') { $ckend = 0;} }
	    }
	    if($ckend) {
		($endM, $endD, $endY) = split(/\//, $href->{'end'}); $endM--;
		next if $endY and $year > $endY;
		if ($year == $endY) {
		    next if $month > $endM;
		    next if $month == $endM and $day > $endD;
		}
	    }
	}
	$date = $href->{'date'};
	$reminder=""; 
	my $done="";
	if( $href->{'repeat'}) {$repeat = $href->{'repeat'};} else {$repeat = 0;}
	$matched = 0; $overdue = ""; $overdueDate="";
	if($kind == 2 or $kind == 4) {			# todo event,
	    next if $cflag;       # cflag is set when searching for conflicts. ToDo and Special Events does not contribute to that.
	    my ($forward, $dm,$dd,$dy, $before);
	    $done = $href->{'done'}; $done = (defined $done && $done eq 'y');
	    if((!$::calinfo{'dctoc'} or $kind == 4) and $done ) { next;}	# do not display completed tasks
	    if(!$done and $repeat < 2) {	# for nonrepeating tasks, check if we need to remind forward
		$forward = $href->{'forward'};
		if(defined $forward and $forward eq 'y') {
		    ($dm, $dd, $dy) = split(/\//, $date);  $dm--;
		    $before = mdyAafterB($dm,$dd, $dy,$month,$day,$year);
		    if($before > 1) {
			my($bdate, $bm, $bd, $by);
			if($href->{'bdate'}) {$bdate = $href->{'bdate'};} else {$bdate=$href->{'date'};}
			($bm, $bd, $by) = split(/\//, $bdate);  $bm--;
			if(mdyAafterB($nowM,$nowD,$nowY, $bm, $bd, $by) and mdyAafterB($month,$day,$year,$nowM,$nowD,$nowY))
			{ $matched = 1; $edate = "$dm/$dd/$dy"; $reminder="rf:n:5:m,rm:n:5:m,rp:n:5:m,rc:n:5:m";}
		    } elsif($istoday and $before == 1) { 
			my ($tim, $hr,$mn);
			$tim=$href->{'start'};
			($hr,$mn)=split(/:/,$tim);
			if($nowH > $hr or $nowH == $hr and $nowN > $mn) {
			    $overdue= hm_string($hr, $mn) . " <iMg src=\"$::o{'imgdirurl'}/at.gif\" width=9 height=9>";
			    $overdueDate="$::phr{'Today'} \@ ";
			    $matched=1; $edate = "$dm/$dd/$dy"; $reminder="rf:n:5:m,rm:n:5:m,rp:n:5:m,rc:n:5:m";
			}
		    } elsif($istoday and $before == 0) { # overdue
			$overdue= md_string($dm, $dd); 
			$overdueDate= mdy_wstring($dm,$dd,$dy); 
			$matched = 1; $edate = "$dm/$dd/$dy"; $reminder="rf:n:5:m,rm:n:5:m,rp:n:5:m,rc:n:5:m";
		    }
		}
	    }
        }
	my $mkind; if($::calinfo{'dctoc'}) { $mkind = $kind;} else {$mkind = 0;}
	my ($cmatch, $mtag); $cmatch=0;
	if($matched or ($cmatch=calmatch($today, $date, $href->{'occurs'}, $repeat, $href->{'exception'}, $mkind))) { 
	    $URL = "";
	    $warning="";
	    $detail="";
	    $cfm="";
	    $mtag = "";
	    if( $href->{'fg'}) {$tc = $href->{'fg'};} else { $tc="";}
	    if($href->{'bg'}){$bg = $href->{'bg'};} else {$bg="";}
	    #================================================
	    if($kind == 4 and $href->{'cbg'}) {$::cell_bg=$href->{'cbg'}; $::cell_bg_t =$href->{'key'};}
	    #================================================
	    $tim = $junk = $href->{'start'};
	    $junk =~ s/:/\//g;
	    if($matched) { $edate .= "/$junk";}
	    else { $edate = "$month/$day/$year/$junk";}
	    $key = $href->{'key'};
	    if($matched) {
		($hr,$mn)=split(/:/,$tim);
		if($overdue) { $tim = "23:99:23:99:$kind:$key"; $overdueDate .= " " . hm_string($hr, $mn);}
		else { $tim = "$hr:$mn:$hr:$mn:$kind:$key";}
  	    } else {
		if($href->{'duration'}) {$duration = $href->{'duration'};} else {$duration =0;} 
		next if $duration == 0 and $cflag; # cflag is set when called from findConflict.
		($hr,$mn)=split(/:/,$tim);
		$utmp=$mn+$duration;
		$ehr= int($utmp/60);
		$ehr += $hr if ($hr ne "");
		$emn = $utmp % 60; if($emn < 10) { $emn="0$emn";}
		$tim .= ":$ehr:$emn:$kind:$key";
	    }
	    if($bg) { $tim .= ":$bg";}
	    elsif($::d{'ispublic'}) {
		my ($name, $cnt, $clr);
		$name=$href->{'author'}; if(!$name) {$name='nobody';}
		if(! exists $::namehash{$name}) { $cnt = ($::d{'namecounter'}++)%16;  $::namehash{$name} = $cnt;}
		$cnt = $::namehash{$name};
		$clr=$webcalConfig::r{'usrColors'}->[$cnt];
		$tim .= ":$clr";
	    }
	    if($kind == 4 and $repeat > 1 and $::scntr) {
		my $seq = $href->{'seq'};
		if(not $::scntr{$seq}) {
		    my ($m,$d,$y)=($month, $day, $year); #split(/\//,$href->{'date'});
		    my $weight=precedence($href->{'occurs'});
		    $::scntr{$seq} = sprintf "%02d%02d%04d%02d", $m,$d,$y,$weight + $::scntr++;
		}
		my $tg = $::scntr{$seq};
		$tim = "($tg)$tim";
	    }
	    my ($di1, $di2)=("","");
	    if($eprivacy >= 2) {
	      $smp = $href->{'what'};
	      if( not $smp) {
		  if($kind == 4 and $href->{'cbg'}) { $smp="&nbsp;&nbsp;";}
		  else { $smp = 'no subject';}
	      }
	      $smp = &substImages($smp);
	      if($eprivacy >= 3) {		
		if($href->{'detail'}) { $detail = "$href->{'detail'}";} else {$detail ="";}
		if($kind == 2 and $::calinfo{'dctoc'}) {                
		    my ($cs1, $cs2) =("","");
		    if( $repeat > 1 ) { # completed tasks
			($cs1, $cs2) = getCompletionInfo($href, -$cmatch);    
			$mtag="__$cmatch";
		    } elsif($done) {
			($cs1, $cs2) = getCompletionInfo($href, 0);    
		    } 
		    if($cs1) {if($detail) {$detail .= "<br>$cs1"} else {$detail=$cs1;}; $di2 = "<br>$cs2";}
		}
		if($overdue) {
		    $di1 = "<b><font color=#ff0000>$::phr{'Overdue'}:</font> $overdue</b><br>";
		    $detail = "<b><span class=\"overdue\"><font color=#ff0000>$::phr{'Overdue'}:</font> $overdueDate</span><b><br><br>" . $detail;
		    $href->{'overdue'} = 1;
		}
		my ($misc, $troom, $tspkr, $tcat, $trest)  = getMiscInfo($href);

		if($::oneDayDetails > 1) {
		    $::oneDayRooms{$tim} = $troom if $troom;
		    $::oneDayCats{$tim} = $tcat if $tcat;
		    $::oneDaySpkrs{$tim} = $tspkr if $tcat; 
		    $::oneDayMisc{$tim} = $misc  if $misc;
		    if($trest) { if($detail) { $detail .= " <br>";}  $detail .= $trest; }
		} else {
		    if($misc) {
			if($detail) { $detail .= " <br>";}	                          
			$detail .= $misc;
		    }
		}
		$URL="";
		$rurl= $href->{'url'};
		if($rurl) {
		    my (@urls, $a, $b); @urls = split(/\s+/, $rurl); 
		    foreach $a (@urls) {
			my $icon = select_url_icon($a);
			$a =~ s/\\?\^o\^\//$irepository\//g;
			$URL .= "<A HREF=\"$a\" target=i><img src=\"$::o{'imgdirurl'}/$icon\" width=20 height=9 border=0></A> " ;
		    }
		} 
	    
		if(!$::d{'megaCal'} and 
		   (! $href->{'r1'} or ($href->{'r1'} and $cmatch <2) ) ) {
		    $reminder = $href->{'rem'} unless $reminder;
		    ($flash,$mail,$popup, $chime)=split(/,/, $reminder);
		    (undef, $maily, $maili,$mailu) = split(/:/, $mail);
		    (undef, $flashy, $flashi,$flashu) = split(/:/, $flash);
		    (undef, $popupy, $popupi,$popupu) = split(/:/, $popup);
		    (undef, $chimey, $chimei,$chimeu) = split(/:/, $chime);
		    
		    if(($flashy eq 'y' or $popupy eq 'y' or $chimey eq 'y') and
		       dtAafterB($month,$day,$year,$hr,$mn, $nowM, $nowD,$nowY,$nowH,$nowN)){
			my ($timeevent, $left, $right, $diff, $pkey, $tmonth);
			$timeevent = timeLocal(0,$mn,$hr,$day,$month,$year);
			if(not $::calinfo{'NPR'} and $popupy eq 'y' and defined $popupi and $popupi ne "") {
			    my $junk = 1+($webcalConfig::r{'refreshInterval'} >> 1);
			    my @pws = split(/;/,$popupi);
			    foreach $popupi (@pws) {
				$right = warntime($popupi,$popupu) + $junk;
				if( $right < $webcalConfig::r{'refreshInterval'} + 2) { $right = $webcalConfig::r{'refreshInterval'} + 2; }
				$left = $right -$webcalConfig::r{'refreshInterval'};
				$diff = $timeevent - $timenow;	# number of seconds between now and event.
				if($diff >= $left and $diff <= $right) {	# ok
				    $tmonth = $month+1;
				    $pkey="$tmonth/$day/$year/$tim";
				    $::popupEvents{$pkey} =
					"<a href=$::o{'cginame'}?w=$who&c=ed&v=$view&ls=$ls&t=$key&k=$kind&d=$edate$::vmg>$smp</a>";
				    last;
				}
			    }
			}
			if( not $::calinfo{'NFR'} and $flashy eq 'y' and defined $flashi and $flashi ne "") {
			    my $junk = 1+($webcalConfig::r{'refreshInterval'} >> 1);
			    my @pws = split(/;/,$flashi);
			    foreach $flashi (@pws) {
				$right = warntime($flashi,$flashu) + $junk;
				if( $right < $webcalConfig::r{'refreshInterval'} + 2) { $right = $webcalConfig::r{'refreshInterval'} + 2; }
				$left = $right -$webcalConfig::r{'refreshInterval'};
				$diff = $timeevent - $timenow;	# number of seconds between now and event.
				if($diff >= $left and $diff <= $right) {	# ok
				    $warning="&nbsp;<img border=0 width=24 height=12 src=\"$::o{'imgdirurl'}/flashs.gif\">";
				    if($::o{'save_reminding_events'}) {
					my ($tmonth, $pkey); $tmonth = $month+1; $pkey="$tmonth/$day/$year/$tim";
					$::blinkEvents{$pkey} =
					    "<a href=$::o{'cginame'}?w=$who&c=ed&v=$view&ls=$ls&t=$key&k=$kind&d=$edate$::vmg>$smp</a>";
				    }
				    last;
				}
			    }
			}
			if(not $::calinfo{'NCR'} and $chimey eq 'y' and defined $chimei and $chimei ne "") {
			    my $junk = 1+($webcalConfig::r{'refreshInterval'} >> 1);
			    my @pws = split(/;/,$chimei);
			    foreach $chimei (@pws) {
				$right = warntime($chimei,$chimeu) + $junk;
				if( $right < $webcalConfig::r{'refreshInterval'} + 2) { $right = $webcalConfig::r{'refreshInterval'} + 2; }
				$left = $right - $webcalConfig::r{'refreshInterval'};
				$diff = $timeevent - $timenow;	# number of seconds between now and event.
				if($diff >= $left and $diff <= $right) {	# ok
				    $::d{'doChimeCount'}++;
				    if($::o{'save_reminding_events'}) {
					my ($tmonth, $pkey); $tmonth = $month+1; $pkey="$tmonth/$day/$year/$tim";
					$::chimeEvents{$pkey} =
					    "<a href=$::o{'cginame'}?w=$who&c=ed&v=$view&ls=$ls&t=$key&k=$kind&d=$edate$::vmg>$smp</a>";
				    }
				    last;
				}
			    }
			}
		    }
		}
		# --- moved to DoConfirmMeeting1
		$cfm = DoConfirmMeeting1($href, $edate, $mg);
		# ---
	      }
	    } else {
		if(defined $href->{'w'}) {$smp = "<FoNt CoLoR=#0000Ff>" . $href->{'w'} . ":</FoNt> " . "$::phr{'Protected'}";}
		else {$smp = "$::phr{'Protected'}";}
	    }
	    my $dndid = "";
	    if($dnd) {
		if($href->{'seq'} !~ /^C/ and not $href->{'pnd'}) {
		    my $ddt=""; if($repeat > 1) {$ddt="$today";}
		    if($href->{'w'}) {
			my $zd=$href->{'w'}; $dndid="id=\"_:$zd:t=$key:$ddt\" onmousemove=\"dndmv()\" ondragstart=\"dndst()\"";
		    } else {
			$dndid="id=\"_:$who:t=$key:$ddt\" onmousemove=\"dndmv()\" ondragstart=\"dndst()\"";
		    }
		}
	    }
	    my $tip ="";
	    $detail = &substImages($detail);
	    my $class=""; 
	    if($href->{'cs'}) {	$class="class=\"$href->{'cs'}\""; } else { $class ="class=\"zet$kind\"";}
	    if($eprivacy >= 3 and $::oneDayDetails) { $::oneDayDetails{$tim} = $detail;}
	    if($href->{'seq'} and $href->{'seq'} =~ /^C/) { $URL="<img src=\"$::o{'imgdirurl'}/pd.gif\" align=middle width=8 height=8> " . $URL;}
	    if($::d{'megaCal'}) {
		my $owner = $href->{'w'};
		if($detail) {
		    my $zz = $owner; $zz =~ s/[^A-Za-z0-9]//g;
		    $detail =~ s/\n/<br>/g if ($detail =~ tr/\n/\n/) <20;
		    my $tpid = add4tip("$key$zz$mtag", $detail, $overdue);
		    $tip = " onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"";
		} 
		if($tc) {
		    $::oneDayEvents{$tim} = $URL . $cfm . $di1 .
			"<a href=\"$popa$::o{'cginame'}?w=$owner&c=$ed&v=$view&ls=$ls&t=$key&k=$kind&d=$edate$mg$::vmg$popb\"$tip $class $dndid><font color=$tc><span $class>$smp</span></font>$warning</a>" . $di2;
		} else {
		    $::oneDayEvents{$tim} = $URL . $cfm . $di1 .
			"<a href=\"$popa$::o{'cginame'}?w=$owner&c=$ed&v=$view&ls=$ls&t=$key&k=$kind&d=$edate$mg$::vmg$popb\"$tip $class $dndid>$smp$warning</a>" . $di2;
		}
	    } else {
		my $pending=""; my $tag="a";
		if($href->{'pnd'}) { 
		    $pending = " <a Href=\"$::o{'cginame'}?w=$who&c=pending&v=$view&ls=$ls$::vmg\"><blink><font color=red>$::phr{'Pending'}</font></blink></a>"; $tag="b";
		}
		if($detail) {
		    $detail =~ s/\n/<br>/g if ($detail =~ tr/\n/\n/) <20;
		    my $tpid = add4tip("$key$mtag", $detail, $overdue);
		    $tip = " onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"";
		} 
		if($tc) {
		    $::oneDayEvents{$tim} = $URL . $cfm . $di1 .
			"<$tag href=\"$popa$::o{'cginame'}?w=$who&c=$ed&v=$view&ls=$ls&t=$key&k=$kind&d=$edate$::vmg$popb\"$tip $class $dndid><font color=$tc><span $class>$smp</span></font>$warning</$tag>" . $di2 . $pending;
		} else {
		    $::oneDayEvents{$tim} = $URL . $cfm . $di1 .
			"<$tag href=\"$popa$::o{'cginame'}?w=$who&c=$ed&v=$view&ls=$ls&t=$key&k=$kind&d=$edate$::vmg$popb\"$tip $class $dndid>$smp$warning</$tag>" . $di2 . $pending;
		}
	    }
	    if($srefs) { my $tmp ="$tim:$eprivacy"; $::oneDayEventRefs{$tmp} = $href;}
	}
    }
}
#=====================================================================================================
sub DoConfirmMeeting1 {
    my ($href,$edate, $mg) = (@_);
    my ($ls, $view, $cfm, $cfmd, $zz); $ls=$::calinfo{'ls'}; $view=$::calinfo{'v'};
    ($cfm, $cfmd) = confirmMeeting($href, 0);

    if($cfmd) { $cfmd = "<br><br>$cfmd"}
    my $key = $href->{'key'};
    my $owner; if( $href->{'w'}) {$owner = $href->{'w'}; $zz = $owner; $zz=~ s/[^A-Za-z0-9]//g;}
    else { $owner=$::calinfo{'w'}; $zz="";}
    if($cfm eq 'a')  {
	my $tpid = add2tip("$key$zz", "<font color=#ff0000><b>$::phr{'invitationAccepted'}</b></font>$cfmd");
	$cfm = "<a href=\"$::o{'cginame'}?w=$owner&c=cfm&cfm=a&v=$view&ls=$ls&t=$key&d=$edate$mg$::vmg\"
onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\">
<img src=\"$::o{'imgdirurl'}/ai.gif\" border=0 width=10 height=8></a>";
    } elsif ($cfm eq 'd') {
	my $tpid = add2tip("$key$zz", "<font color=#ff0000><b>$::phr{'invitationDeclined'}</b></font>$cfmd");
	$cfm = "<a href=\"$::o{'cginame'}?w=$owner&c=cfm&cfm=d&v=$view&ls=$ls&t=$key&d=$edate$mg$::vmg\"
onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\">
<img src=\"$::o{'imgdirurl'}/di.gif\" border=0 width=10 height=8></a>";		      
    } elsif($cfm eq 'r') {
	my $tpid = add2tip("$key$zz","<font color=#ff0000><b>$::phr{'RequestRSVP'}</b></font>$cfmd");
	$cfm = "<a href=\"$::o{'cginame'}?w=$owner&c=cfm&cfm=r&v=$view&ls=$ls&t=$key&d=$edate$mg$::vmg\"
onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\">
<img src=\"$::o{'imgdirurl'}/ri.gif\" border=0 width=10 height=8></a>";
    }

    return($cfm);
}
#=====================================================================================================

sub confirmMeeting {
    my ($href, $flag, $txt) = (@_);
    if($href->{'rsvp'} and defined $href->{'attendants'} and $href->{'attendants'} ne "" ) {
	my (@list, $m, $name, $acc, $dec, $tmp, $w, $cfmd, $decd, $att, $status, $author, $mkey, $total, %hash, $val, $k);
	$total = 0; %hash = ();
	if($href->{'w'}) { $w = $href->{'w'};} else {$w = $::calinfo{'w'};}

	$mkey = $href->{'mkey'}; $mkey =~ s/_eMe_\d+//g;
	$att = $href->{'attendants'};  $att =~ s/[,; ]+/:/g;  $att =~ s/:$//g;
	$att = expandMeetingGroups($mkey, $att); @list = split(/:/, $att); $total = scalar @list;
	return ("", "") if $total <= 1 ;

	foreach $m (@list) { $hash{$m} = 0;}

	$acc= $dec ="";  $status = 'r';
	$cfmd = $href->{'acc'};
	if($cfmd) {
	    $cfmd =~ s/[,; ]+/:/g;
	    @list = split(/:/, $cfmd);
	    foreach $m (@list) {if($m eq $w) {$status = 'a';} $hash{$m} = 2;  }
	}
	$decd = $href->{'dec'};
	if($decd) {
	    $decd =~ s/[,; ]+/:/g;
	    @list = split(/:/, $decd);
	    foreach $m (@list) {if($m eq $w) {$status = 'd';} $hash{$m} = 1;  }
	}
	if($txt) {
	    my ($acpt, $dend, $oth) = ("", "", "");
	    foreach $m (sort keys %hash) {
		$val = $hash{$m};
		$name = getinfo($m, 'name'); $name = "" if !$name; 
		if($val == 2) { $acpt .= "$name ($m), ";}
		elsif($val == 1) { $dend .= "$name ($m), ";}
		else { $oth .= "$name ($m), ";}
	    }
	    return ($status, $acpt, $dend, $oth);
	} else {
	    $tmp=""; $acc=""; $k=0;
	    if($flag==0 and $total > 20) { $total=20; $tmp =" .... <font size=1>click on the icon to see the complete list.</font>";}

	    foreach $m (sort keys %hash) {
		$val = $hash{$m};
		$name = getinfo($m, 'name'); $name = "" if !$name; 
		if($val == 2) { $acc .= "<span class=\"cfmName\">$name ($m):</span> <b><span class=\"cfmAcpt\">$::phr{'invitationAccepted'}</span></b><br>";}
		elsif($val == 1) { $acc .= "<font color=#ff0000><span class=\"cfmName\">$name ($m):</span> <b><span class=\"cfmDced\">$::phr{'invitationDeclined'}</span></b></font><br>";}
		else { $acc .= "<font color=#669999><span class=\"cfmName\">$name ($m):</span></font><br>";}
		$k++; if($k >= $total) { last;}
	    }
	    if($tmp) { $acc .= $tmp;}
	    return ($status, $acc);
	}
    }
    return ("", "");
}
#=====================================================================================================
#
sub get_motd {
    my ($alink, $motd) = ("", ""); 
    my $isadmin=isadmin($::d{'remote_user'});
    
    if($isadmin) {
	$alink =<<END;
<a href="$::o{'cginame'}?c=motd"><img src="$::o{'imgdirurl'}/new.gif" width=10 height=10 border=0 align=bottom title="Edit motd" alt="Edit motd"></a>
END
    ;
    }
    if($::o{'allowImageUpload'} and $::o{'reviewImageUpload'}) {
	if($isadmin or ismember($::d{'remote_user'}, $::o{'ImageUploadReviewer'})) {
	    my @list = listImgDirContents("$::o{'imgdir'}/$::o{'uploadtmpsubdir'}", 0);
	    if(0+@list > 0) {
		$alink .="<a href=\"$::o{'cginame'}?c=reviewUI\" target=rvuis><img src=\"$::o{'imgdirurl'}/blinkeye.gif\" border=0 width=14 height=14></a>";
	    }
	}
    }

    if( -f "$::o{'spooldir'}/.motd" and -r "$::o{'spooldir'}/.motd") {
	my $fh = gensym;
	local($/) = (undef);
	my $tmp="";
	if(open($fh, "<$::o{'spooldir'}/.motd") ) {	
	    $tmp=<$fh>;
	    close $fh;
	    my $irepository = "$::o{'imgdirurl'}/$::o{'uploadsubdir'}";
	    $tmp =~ s/\\?\^o\^\/([^\s]+?)\.(gif|jpg|png|jpeg|bmp)/<img src=\"$irepository\/$1\.$2\" border=0>/ig;
	} #"
	$motd=$tmp;
    }
    return ($alink, $motd);
}
#=======================================================================================================================
sub truncate_pm_file {
    my ($filename)=(@_);
    write_file($filename, "1;\n"); 
}   
#=======================================================================================================================
sub calendar {
    my ($who, $view, $month, $day, $year, $hour, $min, $stmp, $name, $homepage, $today, $out, $savedname, $dofooter,
	$prevc, $nextc, $todayc, $warnname, @othercals, $tmp, $dname, $mg, $vmg, $ls, $script, $bscript, $body, $pnt, $qscript);
    $who = $::calinfo{'w'};
    $view = $::calinfo{'v'};
    $ls = $::calinfo{'ls'}; 
    $pnt = $::calinfo{'pnt'};
    $month= $::calinfo{'month'};
    $day  = $::calinfo{'day'};
    $year = $::calinfo{'year'};
    $hour = $::calinfo{'hour'};
    $min  = $::calinfo{'min'};
    $name = $::calinfo{'dname'};
    $name = $::calinfo{'name'} unless $name;
    $name = $who unless $name;
    $homepage = $::calinfo{'homepage'};
    $dofooter=1;
    #if($::d{'remote_user'} eq 'anonymous') {$::o{'listAllCals'} = 1;}

    if($view == 1) { $prevc = printDate0( $month, $day -1, $year); $nextc = printDate0( $month, $day +1, $year); }
    elsif($view == 2) { $prevc = printDate0( $month, $day -7, $year); $nextc = printDate0( $month, $day +7, $year); }
    elsif($view == 3) { $prevc = printDate0( $month-1, 1, $year); $nextc = printDate0( $month+1, 1, $year); }
    elsif($view == 4) { $prevc = printDate0( $month, 1, $year-1); $nextc = printDate0( $month, 1, $year+1); }
    $::o{'previousc'} = $prevc; $::o{'nextc'} = $nextc;
    $todayc = printDate0( $::now{'month'}, $::now{'day'}, $::now{'year'});
    if(!defined $hour or $hour == 0) {  $hour = $::now{'hour'}; $min =$::now{'min'};}
    
    $qscript="function qa(){q=window.open(\"$::o{'cginame'}?c=qa&w=$who&v=$view&ls=$ls&d=$month/$day/$year$::vmg&mg=$::calinfo{'mg'}\",\"qa\", \"scrollbars=yes,resizable=yes,width=600,height=300\");if(window.focus){q.window.focus(); }}";

    if($::d{'megaCal'} ne "") {
	$mg="&mg=$::d{'megaCal'}"; $vmg="<input type=hidden name=mg value=\"$::d{'megaCal'}\">";
    } else {$mg=$vmg="";}
    # clear warning
    $warnname = "$::o{'spooldir'}/$who/warn";    &truncate_pm_file($warnname);

    $dname="$::phr{'Calendar'}-$who";
    $body = "";
  if($pnt) {
        my $cn; $::d{'estyle'} = 1;
	$::o{'tw'} = 100;
	$::o{'qadd'} = "";
	$body .= " onLoad=\"window.print()\"";
	&headers("$::phr{'Calendar'} $name","",0,0,1,$body);
	if($::d{'megaCal'} ne "") {
	    my ($memb, @mlist);
	    @mlist = split(',',$::d{'megaCal'});
	    $cn="$::phr{'CombinedCalendar'}<br>";
	    for $memb (@mlist) {
		$memb =~ s/[ ]+//g;
		my $tmp = getinfo($memb, 'name'); $tmp=$memb if not $tmp;
		$cn .= "<span class=\"memberInTitle\">$tmp, </span> ";
	    }
	    $cn =~ s/, $//g;
        } else {$cn = "<span class=\"calendarTitle\">$name</span>";}
        if($ls >= 0) {	print "<center><h2>$cn</h2></center>";}
        else {$savedname = $cn;}
  } elsif($ls < 0) { #detailed list view,
	if($::d{'megaCal'} ne "") {
	    my ($memb, @mlist, $sdate);
            $sdate="=$month/$day/$year";
	    @mlist = split(',',$::d{'megaCal'});
	    $savedname="";
	    for $memb (@mlist) {
		$memb =~ s/[ ]+//g;
                $savedname .= "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$memb&v=$view&d=$sdate$::vmg\"><span class=\"memberInTitle\">&nbsp;$memb&nbsp;</span></a>";
	    }
	    $savedname =~ s/, $//g;
        } else {
            if($homepage) { $savedname = "<a href=\"$homepage\"><span class=\"calendarTitle\">$name</span></a>";}
            else {$savedname = "<span class=\"calendarTitle\">$name</span>"; }
        }
	($bscript, $script) = &getClockScript();
	&headers("$::phr{'Calendar'} $name", $script . $qscript,$webcalConfig::r{'refreshInterval'},1,1,$body . $bscript);
 } else { # not printer, not detailed list view
    ($bscript, $script) = &getClockScript();
    $body .= $bscript;

    &headers("$::phr{'Calendar'} $name",$script . $qscript,$webcalConfig::r{'refreshInterval'},1,1,$body);
    print "<a name=t></a>";

    my $headerForm=&newHeader('get', 1);
    print $headerForm;

 if(!($::vm & 0x8) and $view > 0) {
    print "<table width=\"$::o{'tw'}%\" border=0 cellpadding=0 cellspacing=0 bgcolor=\"#ffcc66\" class=\"dnbar\">";

    print "<tr><td height=16 align=left noWrap width=\"2%\" class=\"dnbarTd\">";
    print "<font size=-2><a class=\"dbtn\" href=\"$::o{'cginame'}?c=compare&ls=$ls&w=$who&v=$view&d=$month/$day/$year$mg$::vmg\"><span class=\"dnbarTxt\">&nbsp;$::phr{'Compare'}</span></a></font>";
    print "</td><td align=center noWrap width=\"80%\" colspan=13 class=\"dnbarTd\"><font size=-2>";
    
    &ndbar('get', $month, $day, $year,  $who, $view, $ls, $mg);
    
    print "</font></td>\n";

    print " <td align=left valign=middle noWrap width=\"16%\" class=\"dnbarTd\"><font size=-2><a class=\"dbtn\" href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$prevc/$hour/$min$mg$::vmg\"><span class=\"dnbarTxt\"><b>&lt;&lt;</b></span></a>
<a class=\"dbtn\" href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$todayc/$hour/$min$mg$::vmg\"><span class=\"dnbarTxt\">$::phr{'Today'}</span></a>
<a class=\"dbtn\" href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$nextc/$hour/$min$mg$::vmg\"><span class=\"dnbarTxt\"><b>&gt;&gt;</b></span></a>&nbsp;</font></td>\n";


    my $gotoA="<font size=-2><a class=\"dbtn\" href=\"$::o{'cginame'}?c=gotod&w=$who&v=$view&ls=$ls&d=$month/$day/$year/$hour/$min$mg$::vmg\"><span class=\"dnbarTxt\">$::phr{'Goto_Date'}&nbsp;<span></a></font>";

    print "<td align=right noWrap width=\"2%\" class=\"dnbarTd\">$gotoA</td>";
    print "</tr>";
    print <<END;
<tr><td colspan=16 bgcolor="#666633"><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=1 border=0></td></tr>
END
    ;
    print "</table>";
    $|=1; print "\n"; $|=0;
  }
} # not print


if($ls) {
  if($ls > 0) {
      my $bclr=$webcalConfig::r{'bluebar'}; 
      my $lvheader=<<END;
<table border=0 cellpadding=0 cellspacing=0 bgcolor="#999999" width="$::o{'tw'}%" class="v2etHolder"><tr><td width="100%">
<table border=0 cellpadding=2 cellspacing=1 width="100%" class="v2tbl">
<tr><td align=center width="5%" bgcolor=$bclr class="v2Row1Td"><font color="#ffffff"><span class="v2Row1Txt">$::phr{'Date'}</span></font></td>
<td align=center width="10%" bgcolor=$bclr class="v2Row1Td"><font color="#ffffff"><span class="v2Row1Txt">$::phr{'Time'}</span></font></td>
<td align=center width="40%" bgcolor=$bclr class="v2Row1Td"><font color="#ffffff"><span class="v2Row1Txt">$::phr{'What'}</span></font></td>
<td align=center width="45%" bgcolor=$bclr class="v2Row1Td"><font color="#ffffff"><span class="v2Row1Txt">$::phr{'Details'}</span></font></td></tr>
END
    ;
      #"
      my ($nextc, $prevc);
      if(! $::calinfo{'pnt'}) {
	  $nextc = "<img src=\"$::o{'imgdirurl'}/spacer.gif\" width=4 height=1 border=0><a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$::o{'nextc'}/9/0$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/rright.gif\" width=10 height=12 border=0></a>";
	  $prevc = "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$::o{'previousc'}/9/0$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/rleft.gif\" width=10 height=12 border=0></a><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=4 height=1 border=0>";
      } else { $nextc = $prevc = "";}

      if($view == 3) { #month view
	my($ndays, $ii, $jj);
        my $ismy = ($month == $::now{'month'} and  $year == $::now{'year'});
	if($month ==1 and isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}
	$ndays = $::mdays[$month];
	if(! $pnt) {
	    print <<END;
<center>
<table border=0 cellspacing=0 cellpadding=1 width="$::o{'tw'}%"><tr><td width="25%" align=center>$::o{'qadd'}&nbsp;</td><td width="50%" align=center nowrap>
$::mnbar $prevc <font color="#ff0000"><b><span class="mvTitle2">$::srchn$::mname[$month] $year</span></b></font> $nextc $::vnbar 
</td><td width="25%" align=right nowrap valign=top>
<Form name=csearch action="$::o{'cginame'}" method=GET  class="searchform">
<input type=hidden name=c value="dosearch">
<input type=hidden name=searchRange value="all">
<input type=hidden name=w value="$who">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$month/$day/$year">
$::vmp$vmg
$::srchi<font size=1><span class="fmLabelSa">$::phr{'Search'}:</span></font>
<font size=1><input type=text name=stopic size=10 maxlength=128 value="$::srchftrptn" class="fmEntrySa"></font>
<font size=1><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font>
</Form>
</td></tr></table>
</center>
END
 ;
    } else {
	print <<END;
<center>
$::mnbar $prevc <font color="#ff0000"><b><span class="mvTitle2">$::srchn$::mname[$month] $year</span></b></font> $nextc $::vnbar $::o{'qadd'}
</center>
END
    ;
    }
	
	print $lvheader;
	$day = 1; $ii=0;
	while($day <= $ndays) {
	  my $clr;
          if($ismy and $day == $::now{'day'}) { $jj = 2;}
          else { $jj = ($ii & 1);}
	  my ($ecnt, $elst) = oneDayList($month, $day, $year, "", $jj);
	  $ii += $ecnt; print $elst;
	  $day++;
        }
	print "</table>\n";
	print "</td></tr></table>";	  
	if($ii == 0) { print "<h2>$::phr{'NoEvents'}</h2>";}
      } elsif ($view == 2) { # week view
	my ($wcode,$tday, $wknum, $stmp, $i, $j, $nmonth, $nday, $nyear, $wklen, $ii);
	$wcode= wday($month, $day, $year);
	if($wcode == 0 && $::o{'weekstart'}) {$wcode = 7;}
	$tday = $day = $day - $wcode;
	if($tday <= 0) {
	  if($month == 0) { $month = 11;  $year -= 1; $tday = 31 + $tday;}
	} else {
	  $month -= 1;
	  if($month == 1) { if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}}
	  $tday = $::mdays[$month] + $tday;
	}
	$wknum = weekNum($month,$tday+1,$year, $::o{'weekstart'});
	if($::o{'weekstart'})   { ($nmonth, $nday, $nyear) = canDate($month, $tday+1, $year);}
	else { ($nmonth, $nday, $nyear) = canDate($month, $tday, $year);}
	$stmp = "$::phr{'Week_starts_on'} ".mdy_string($nmonth,$nday,$nyear);
	if(! $pnt) {
	    print <<END;
<center>
<table border=0 cellspacing=0 cellpadding=1 width="$::o{'tw'}%"><tr><td width="25%" align=center>$::o{'qadd'}&nbsp;</td>
<td width="50%" align=center nowrap>
$::mnbar $prevc <font color="#ff0000"><b><span class="wvTitle2">$::srchn$stmp</span></b></font><font color="#009900"><span class="wvTitle2">&nbsp;(# $wknum)</span></font> $nextc $::vnbar
</td><td width="25%" align=right nowrap valign=top>
<Form name=csearch action="$::o{'cginame'}" method=GET  class="searchform">
<input type=hidden name=c value="dosearch">
<input type=hidden name=searchRange value="all">
<input type=hidden name=w value="$who">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$month/$day/$year">
$::vmp$vmg
$::srchi<font size=1><span class="fmLabelSa">$::phr{'Search'}:</span></font>
<font size=1><input type=text name=stopic size=10 maxlength=128 value="$::srchftrptn" class="fmEntrySa"></font>
<font size=1><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font>
</Form>
</td></tr></table>
</center>
END
 ;
    } else {
	print "<center>$::mnbar $prevc <font color=#ff0000><b><span class=\"wvTitle2\">$::srchn$stmp</span></b></font><font color=#009900><span class=\"wvTitle2\">&nbsp;(# $wknum)</span></font> $nextc $::vnbar $::o{'qadd'}</center>\n";
    }
	print $lvheader;
	if($::o{'excludeWeekend'}) { $wklen = 5; } else { $wklen = 7;}
	$ii = 0;
	for($i = 0; $i < $wklen; $i++) {
	  my $jj; 
	  $j=$tday+$i +$::o{'weekstart'};
	  ($nmonth, $nday, $nyear) = canDate($month, $j, $year);
          if ($nmonth == $::now{'month'} and  $nyear == $::now{'year'} and $nday == $::now{'day'}) {$jj=2;}
          else {$jj = $ii & 1;}
	  my ($ecnt, $elst) = oneDayList($nmonth, $nday, $nyear, "", $jj);
	  $ii += $ecnt; print $elst;
	}
	print "</table>\n";
	print "</td></tr></table>";	  
	if($ii == 0) { print "<h2>$::phr{'NoEvents'}</h2>";}	    
      } elsif($view == 1) { #dayview
	my $stmp = mdy_wstring($month,$day,$year);

	if(! $pnt) {
	    print <<END;
<center>
<table border=0 cellspacing=0 cellpadding=1 width="$::o{'tw'}%"><tr><td width="25%" align=center>$::o{'qadd'}&nbsp;</td><td width="50%" align=center nowrap>
$::mnbar $prevc <font color="#ff0000"><b><span class="dvTitle2">$::srchn$stmp</span></b></font> $nextc $::vnbar 
</td><td width="25%" align=right nowrap valign=top>
<Form name=csearch action="$::o{'cginame'}" method=GET  class="searchform">
<input type=hidden name=c value="dosearch">
<input type=hidden name=searchRange value="all">
<input type=hidden name=w value="$who">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$month/$day/$year">
$::vmp$vmg
$::srchi<font size=1><span class="fmLabelSa">$::phr{'Search'}:</span></font>
<font size=1><input type=text name=stopic size=10 maxlength=128 value="$::srchftrptn" class="fmEntrySa"></font>
<font size=1><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font>
</Form>
</td></tr></table>
</center>
END
 ;
    } else {
	print "<center>$::mnbar $prevc <font color=#ff0000><b><span class=\"dvTitle2\">$::srchn$stmp</span></b></font> $nextc $::vnbar $::o{'qadd'}</center>\n";
    }
	print $lvheader;
	my ($ecnt, $elst) = oneDayList($month, $day, $year, "", 0); print $elst;
	print "</table>\n";
	print "</td></tr></table>";	  
	if($ecnt == 0) { print "<h2>$::phr{'NoEvents'}</h2>";}
      } else { #year view
	if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}
	my ($i, $j, $nmonth, $nday, $nyear, $total, $ii);
	# read the whole thing in
	if(! $::d{'megaCal'}) {
	    my $df = "$::o{'spooldir'}/$who/data";
	    if( -f "$df") { &doReadFile("$df");};
	}
	my $search=<<END;
<Form name=csearch action="$::o{'cginame'}" method=GET  class="searchform">
<input type=hidden name=c value="dosearch">
<input type=hidden name=searchRange value="all">
<input type=hidden name=w value="$who">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$month/$day/$year">
$::vmp$vmg
$::srchi<font size=1><span class="fmLabelSa">$::phr{'Search'}:</span></font>
<font size=1><input type=text name=stopic size=10 maxlength=128 value="$::srchftrptn" class="fmEntrySa"></font>
<font size=1><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font>
</Form>
END
    ;
	if($pnt) { $search = "&nbsp;";}
	my $tcnt = 0;
	for($nmonth = 0; $nmonth < 12; $nmonth++) {
          $ii = 0;
	  my $events="";

	  $total = $::mdays[$nmonth];
	  for($i=1; $i<=$total; $i++) {
	    my $jj= $ii & 1;
	    my ($ecnt, $elst) = oneDayList($nmonth, $i, $year, "", $jj);
	    $ii += $ecnt; $events .= $elst;
	  }
	  if($ii) {
	      print <<END;
<table border=0 cellspacing=0 cellpadding=1 width="$::o{'tw'}%"><tr><td width="25%">&nbsp;</td><td width="50%" align=center nowrap>
<font color="#ff0000"><b><span class="yvTitle2">$::srchn$::mname[$nmonth] $year</span></b></font>
</td><td width="25%" align=right nowrap valign=top>$search</td></tr></table>
END
;
	      $search = "&nbsp;";
	      print $lvheader;
	      print $events;
	      print "</table>\n";
	      print "</td></tr></table>";	  
	      $tcnt += $ii;
	  }
      }
	if($tcnt == 0) {
	    print <<END;
<table border=0 cellspacing=0 cellpadding=1 width="$::o{'tw'}%"><tr><td width="25%">&nbsp;</td><td width="50%" align=center nowrap>
<font color="#ff0000"><b><span class="yvTitle2">$::srchn$::mname[$nmonth] $year</span></b></font>
</td><td width="25%" align=right nowrap valign=top>$search</td></tr></table>
$lvheader
</table></td></tr></table>
<br>
<h2>$::phr{'NoEvents'}</h2>
END
;
	}
    }
 } else  { # detailed listview
      my ($header, $footer, $ww, $xx, $nav, $hcr, $clockApplet, $mdy_string, $motd);
      if($pnt) { $nav = ""; } else {   $nav = &navigationTable(1);} 
      ($header, $footer, $hcr) = getHdrFtr($savedname);
      my ($alink, $mot) = get_motd();
      if($alink or $mot) {
	  my $tmp = int(32* rand()); 
	  my $mclr = $webcalConfig::r{'txtColors'}->[$tmp];
	  $motd = "<img src=\"$::o{'imgdirurl'}/spacer.gif\" width=32 height=1 border=0><font color=$mclr><span class=\"motd\">$mot </span></font>$alink";
      } else { $motd="";}
      
      if( ($::vm & 0x6)  == 0) {
	  $clockApplet = &getClockApplet();
	  $mdy_string = mdy_wstring($::now{'month'}, $::now{'day'}, $::now{'year'});      
	  print "<table border=0 cellpadding=0 cellspacing=2 width=\"$::o{'tw'}%\"><tr><td width=4%><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=20 height=30></td><td nowrap width=\"80%\"$hcr>$header</td><td nowrap width=\"16%\" align=center>
$clockApplet<font size=1 color=#999999><span class=\"datetime\">$mdy_string</span></font></td></tr></table><br>";
      } elsif($::vm & 0x4) {
	  print "<table border=0 cellpadding=0 cellspacing=2 width=\"$::o{'tw'}%\"><tr>
<td width=4% rowspan=800><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=16 height=8 border=0></td>
<td width=\"95%\">$header</td>
</tr></table>";
      }

      print "<table border=0 cellpadding=0 cellspacing=1 width=\"$::o{'tw'}%\" class=\"v34tbl\">";
      print "<tr><td width=3% class=\"v34vfiller\" rowspan=5000><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=20 height=8 border=0></td>
<td width=10%><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=40 height=1 border=0></td>
<td width=30%><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=140 height=1 border=0></td>
<td width=20%><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=80 height=1 border=0></td>
<td width=16%><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=70 height=1 border=0></td>
<td width=1% class=\"v34vfiller\" rowspan=5000><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=8 height=8 border=0></td>
<td width=20% rowspan=800 valign=top class=\"v3tdBIG\">$nav</td></tr>";

      $ww = 0;
      if($view == 3) { #month view
	  my( $day, $ndays, $ii, $jj, $nbar);
	  if ($month ==1 and isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}
	  $ndays = $::mdays[$month];
	  $nbar="";

	  my $mname = "$::mname[$month] $year";
          print "<tr valign=bottom><td colspan=3 nowrap><font color=#999999><b><span class=\"mvTitle34\">$::srchn$mname</span></b></font>$motd</td><td valign=bottom align=right>$::o{'qadd'}</td></tr>";	  
#	if( ($::vm & 0x400) == 0) {
	  if(!$::calinfo{'pnt'} ) {
	      $nbar= "<tr><td colspan=4 align=center bgcolor=#006498 class=\"dnbar34Td\"><font size=-2>";
	      my($m, $rm, $y, $tt);
	      for($m = $month - 6; $m < $month + 6; $m++) {
		  $rm = $m;
		  if($rm < 0) { $y = $year -1; $rm += 12;}  elsif($rm > 11) { $y = $year +1; $rm -= 12;}  else { $y = $year;}
		  $tt = $::mNames[$rm];
		  if($rm == $month) {$nbar .= "<font color=#cccccc><span class=\"dnbar34Txt\">&nbsp;&nbsp;$tt&nbsp;&nbsp;</span></font>";}
		  else {$nbar .= "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=3&d=$rm/1/$y$mg$::vmg\"><font color=#ffff00><span class=\"dnbar34Txt\">&nbsp;&nbsp;$tt&nbsp;&nbsp;</span></font></a>";}
	      }
	      $nbar .= "</font></td></tr>";
	  }
	  print $nbar, "\n";
	  $day = 1;
	  while($day <= $ndays) {
	      my ($ecnt, $elst) = &oneDayList($month, $day, $year, "",0); $ww += $ecnt; print $elst;
              if($ecnt) {
                print "<tr><td colspan=4 height=8><img src=\"$::o{'imgdirurl'}/spacer.gif\" height=8 width=1 border=0></td></tr>";
            }
	      $day++;
	  }
	  if($ww == 0) {
	      print "<tr><td colspan=4 bgcolor=#006498 height=1><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=10 height=1 border=0></td></tr>";
	      print "<tr><td colspan=4><h1>$::phr{'NoEvents'}</h1></td></tr>";
	  }
          print "<tr><td colspan=4 bgcolor=#006498 height=1><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=10 height=1 border=0></td></tr>";
	  print $nbar, "\n";
	  if($ww < 20) {   print "<tr><td><br></td></tr>" x (20 - $ww);}
	  print "</table>\n";
      } elsif ($view == 2) { # week view
	my ($wcode,$tday, $wknum, $stmp, $i, $j, $nmonth, $nday, $nyear, $wklen, $ii, $nbar);
	$nbar ="";
#	if( ($::vm & 0x400) == 0) {
        if(!$::calinfo{'pnt'} ) {
	    my($rm, $rd, $ry, $rr, $wd);
	    $nbar= "<tr><td colspan=4 align=center bgcolor=#006498 class=\"dnbar34Td\"><font size=-2>";	    
	    $wd = wday($month, $day, $year) -$::o{'weekstart'};
	    $wd = 6 if $wd < 0;
	    for($rr = -28-$wd; $rr <= 35; $rr += 7) {
		($rm, $rd, $ry) = canDate($month, $day+$rr, $year);
		if($rr== -$wd) {
		    $nbar .= "<font color=#cccccc><span class=\"dnbar34Txt\">&nbsp;&nbsp;". md_string($rm,$rd) . "&nbsp;&nbsp;</span></font>";
		} else {
		    $nbar .= "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=2&d=$rm/$rd/$ry$mg$::vmg\"><font color=#ffff00><span class=\"dnbar34Txt\">&nbsp;&nbsp;". md_string($rm,$rd). "&nbsp;&nbsp;</span></font></a>";
		}
	    }
	    $nbar .= "</font></td></tr>";
	}

	$wcode= wday($month, $day, $year);
	if($wcode == 0 && $::o{'weekstart'}) {$wcode = 7;}
	$tday = $day = $day - $wcode;
	if($tday <= 0) {
	  if($month == 0) { $month = 11;  $year -= 1; $tday = 31 + $tday;}
	} else {
	  $month -= 1;
	  if($month == 1) { if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}}
	  $tday = $::mdays[$month] + $tday;
	}
	if($::o{'weekstart'})   { ($nmonth, $nday, $nyear) = canDate($month, $tday+1, $year);}
	else { ($nmonth, $nday, $nyear) = canDate($month, $tday, $year);}

	my $mname = "$::phr{'Week_starts_on'} ".mdy_string($nmonth,$nday,$nyear);
	print "<tr valign=bottom><td colspan=3 nowrap><font color=#999999><b><span class=\"wvTitle34\">$::srchn$mname</span></b></font>$motd</td><td valign=bottom align=right>$::o{'qadd'}</td></tr>";	  
	print $nbar, "\n";
	if($::o{'excludeWeekend'}) { $wklen = 5; } else { $wklen = 7;}
	for($i = 0; $i < $wklen; $i++) {
	  $j=$tday+$i +$::o{'weekstart'};
	  ($nmonth, $nday, $nyear) = canDate($month, $j, $year);
	  my ($ecnt, $elst) = oneDayList($nmonth, $nday, $nyear, "", 0); $ww += $ecnt; print $elst;
          if($ecnt) {
              print "<tr><td colspan=4 height=8><img src=\"$::o{'imgdirurl'}/spacer.gif\" height=8 width=1 border=0></td></tr>";
          }
	}
	if($ww == 0) {
	    print "<tr><td colspan=4 bgcolor=#006498 height=1><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=10 height=1 border=0></td></tr>";
	    print "<tr><td colspan=4><h1>$::phr{'NoEvents'}</h1></td></tr>";
	}
        print "<tr><td colspan=4 bgcolor=#006498 height=1><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=10 height=1 border=0></td></tr>";
	print $nbar, "\n";
	if($ww < 20) {  print "<tr><td><br></td></tr>" x (20 - $ww);}
	print "</table>\n";
      } elsif($view == 1) { #dayview
	  my $mname = mdy_string($month,$day,$year);
	  my $nbar ="";
#	  if(($::vm & 0x400) == 0) {
          if(!$::calinfo{'pnt'} ) {
	      my($rm, $rd, $ry, $rr, $wd);
	      $nbar= "<tr><td colspan=4 align=center bgcolor=#006498 class=\"dnbar34Td\"><font size=-2>";
	      for($rr = -5; $rr <= 5; $rr++) {
		  ($rm, $rd, $ry) = canDate($month, $day+$rr, $year);
		  if($rd == $day) {
		      $nbar .= "<font color=#cccccc><span class=\"dnbar34Txt\">&nbsp;&nbsp;" . md_string($rm,$rd) . "&nbsp;&nbsp;</span></font>";
		  } else {
		      $nbar .= "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=1&d=$rm/$rd/$ry$mg$::vmg\"><font color=#ffff00><span class=\"dnbar34Txt\">&nbsp;&nbsp;" . md_string($rm,$rd) . "&nbsp;&nbsp;</span></font></a>";
		  }
	      }
	      $nbar .= "</font></td></tr>";
	  }
	  print "<tr valign=bottom><td colspan=3 nowrap><font color=#999999><b><span class=\"dvTitle34\">$::srchn$mname</span></b></font>$motd</td><td valign=bottom align=right>$::o{'qadd'}</td></tr>";	  
	  print $nbar, "\n";
	  my ($ww, $elst) = oneDayList($month, $day, $year, "", 0); print $elst;
	  if($ww == 0) {
	      print "<tr><td colspan=4 bgcolor=#006498 height=1><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=10 height=1 border=0></td></tr>";
	      print "<tr><td colspan=4><h1>$::phr{'NoEvents'}</h1></td></tr>";
	  }
	  print "<tr><td colspan=4 bgcolor=#006498 height=1><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=10 height=1 border=0></td></tr>";
	  print $nbar, "\n";
	  if($ww < 20) {  print "<tr><td><br></td></tr>" x (20 - $ww);}
	  print "</table>\n";
      } else { #year view
	if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}
	my ($i, $j, $nmonth, $nday, $nyear, $total, $ii, $nbar);
	# read the whole thing in
	$nbar = "";
#	if( ($::vm & 0x400) == 0) {
        if(!$::calinfo{'pnt'} ) {
	    my($y);
	    $nbar= "<tr><td colspan=4 align=center bgcolor=#006498 class=\"dnbar34Td\"><font size=-2>";
	    for($y= $year-5; $y <= $year+5; $y++) {
		if($y == $year) { $nbar .= "<font color=#cccccc><span class=\"dnbar34Txt\">&nbsp;&nbsp;$y&nbsp;&nbsp;</span></font>";}
		else {$nbar .= "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=4&d=$month/$day/$y$mg$::vmg\"><font color=#ffff00><span class=\"dnbar34Txt\">&nbsp;&nbsp;$y&nbsp;&nbsp;</span></font></a>";}
	    }
	    $nbar .= "</font></td></tr>";
	}
	print "<tr valign=bottom><td colspan=3 nowrap><font color=#999999><b><span class=\"yvTitle34\">$::srchn$year</span></b></font>$motd</td><td valign=bottom align=right>$motd$::o{'qadd'}</td></tr>"; 
	print $nbar, "\n";
	if(! $::d{'megaCal'}) {
	    my $df = "$::o{'spooldir'}/$who/data";
	    if( -f "$df") { &doReadFile("$df");};
	}
	for($nmonth = 0; $nmonth < 12; $nmonth++) {
	    $total = $::mdays[$nmonth];
	    for($i=1; $i<=$total; $i++) {
		my ($ecnt, $elst) = oneDayList($nmonth, $i, $year, "", 0);
		$ww += $ecnt; print $elst; 
	    }
	}
	if($ww == 0) {
	    print "<tr><td colspan=4 bgcolor=#006498 height=1><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=10 height=1 border=0></td></tr>";
	    print "<tr><td colspan=4><h1>$::phr{'NoEvents'}</h1></td></tr>";
	}
        print "<tr><td colspan=4 bgcolor=#006498 height=1><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=10 height=1 border=0></td></tr>";
	print $nbar, "\n";
	if($ww < 20) {  print "<tr><td><p><br></td></tr>" x (20 - $ww);}
        print "</table>\n";
    }
      $dofooter=0;
      print "<br>";
      print "<table border=0 cellspacing=0 width=\"$::o{'tw'}%\"><tr><td width=5%><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=20 height=30></td><td nowrap align=center>$footer</td><td width=20%><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=100 height=30></td></tr></table>";
  }
} else {
      if($view == 4) {		# year view
	$out = yearCal( $month, $day, $year, 3);
	print "$out\n";
      } elsif($view == 3) {	# month view
	$out = monthCal( $month, $day, $year, 3, 0);
	print "$out\n";
      } elsif($view == 2) {
	$out = weekCal( $month, $day, $year);
	print "$out\n";
      } else {
	$out = dayCal( $month, $day, $year);
	print "$out\n";
      }

      # create warning
      $stmp = 0;
      $warnname = "$::o{'spooldir'}/$who/warn";
      {
	  my $fhb = gensym;
	  if(sysopen($fhb, "$warnname", O_WRONLY | O_CREAT, 0644)) {
	      &webcalLock::doflock( \*$fhb, LOCK_EX, "$warnname") or calerror("Cannot lock file '$warnname': $!\n",1);
	      truncate($fhb, 0);
	      my ($key, $value);
	      print $fhb '%::warnEvents = (',"\n";
	      for $key (keys %::popupEvents) {
		  $value = $::popupEvents{$key};
		  $value =~ s/\\//g; $value =~ s/\'//g;
		  print $fhb "\'$key\' => \'$value\',\n";
		  $stmp++;
	      };
	      print $fhb ");\n1;\n";
	      &webcalLock::doflock( \*$fhb, LOCK_UN, "$warnname") or calerror("Cannot unlock file '$warnname': $!\n",1);     
	      close $fhb;
	  }
      }
      if($::d{'doChimeCount'} > 0) {
	print "<SCRIPT LANGUAGE=\"JavaScript\" type=\"text/javascript\">\n<!--\n";
	print "var y=window.open(\'$::o{'imgdirurl'}/chimes.au\',\'preview\',\'width=1,height=1,menubar=no,scrollbars=no,resizable=no,location=0,top=9999,left=9999\');setTimeout(\"y.close();\", 3000);\n";
	print "// -->\n</SCRIPT>;\n";
      }
      if($stmp > 0) {
	print "<SCRIPT LANGUAGE=\"JavaScript\" type=\"text/javascript\">\n<!--\n";
	print "var x=window.open(\'$::o{'cginame'}?w=$who&c=warn\',\'popup\',\'width=400,height=256,menubar=no,scrollbars=yes,resizable=yes,location=0,top=0,left=0\');x.focus();\n";
	print "// -->\n</SCRIPT>;\n";
      }
    }
    &trailer(1,$dofooter);
    # move cache computations to cleanup handler.
    # Since myexit() clears most global variables. The following hash 
    # records the variables needed for computing the cache. 
    %::cache_info=('spooldir'=> $::o{'spooldir'},  'w' => $::calinfo{'w'}, 
                   'v' => $::calinfo{'v'},         'weekstart' =>$::o{'weekstart'},
                   'day' => $::calinfo{'day'}, 'month' => $::calinfo{'month'}, 'year'=> $::calinfo{'year'},
                   'megaCal' => $::d{'megaCal'}, 'dctoc' => $::calinfo{'dctoc'},
                   );
    if($::this_request and $ENV{'MOD_PERL'} =~ /mod_perl\/([\d|\.]+)/) {
        my $version = $1;
        if($version > 1.9) {
          require APR::Pool;
          $::this_request->pool->cleanup_register( \&cacheData ); 
        } else {
            $::this_request->register_cleanup( \&cacheData ); 
        }
    } else { &cacheData();}
}
#=====================================================================================================
sub ndbar {
    my ( $cmd, $month, $day, $year, $who, $view, $ls, $mg)= (@_);
    my $result = "";
    if($view == 4) {	# year view
	my($y,);
	for($y= $year-5; $y <= $year+5; $y++) {
	    if($y == $year) {print "<span class=\"dnbarTxt\">&nbsp;&nbsp;<b>$y</b>&nbsp;&nbsp;</span>";}
	    else {print "<a class=\"dbtn\" href=\"$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=4&d=$month/$day/$y$mg$::vmg\"><span class=\"dnbarTxt\">&nbsp;&nbsp;$y&nbsp;&nbsp;</span></a>";}
	}
    } elsif ($view == 3) {	# month view
	my($m, $rm, $y, $tt);
	for($m = $month - 6; $m < $month + 6; $m++) {
	    $rm = $m;
	    if($rm < 0) { $y = $year -1; $rm += 12;}
	    elsif($rm > 11) { $y = $year +1; $rm -= 12;}
	    else { $y = $year;}
	    $tt = $::mNames[$rm];
	    if($rm == $month) {print "<span class=\"dnbarTxt\">&nbsp;&nbsp;<b>$tt</b>&nbsp;&nbsp;</span>";}
	    else {print "<a class=\"dbtn\" href=\"$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=3&d=$rm/$day/$y$mg$::vmg\"><span class=\"dnbarTxt\">&nbsp;&nbsp;$tt&nbsp;&nbsp;</span></a>";}
	}
    } elsif ($view == 2) {	# week view
	my($rm, $rd, $ry, $rr, $wd);
	$wd = wday($month, $day, $year) -$::o{'weekstart'};
	$wd = 6 if $wd < 0;
	for($rr = -28-$wd; $rr <= 35; $rr += 7) {
	    ($rm, $rd, $ry) = canDate($month, $day+$rr, $year);
	    if($rr== -$wd) {
		print "<span class=\"dnbarTxt\">&nbsp;&nbsp;<b>",md_string($rm,$rd),"</b>&nbsp;&nbsp;</span>";
	    } else {
		print "<a class=\"dbtn\" href=\"$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=2&d=$rm/$rd/$ry$mg$::vmg\"><span class=\"dnbarTxt\">&nbsp;&nbsp;",md_string($rm,$rd),"&nbsp;&nbsp;</span></a>";
	    }
	}
    } else {			# day view
	my($rm, $rd, $ry, $rr, $wd);
	for($rr = -5; $rr <= 5; $rr++) {
	    ($rm, $rd, $ry) = canDate($month, $day+$rr, $year);
	    if($rd == $day) {
		print "<span class=\"dnbarTxt\">&nbsp;&nbsp;<b>",md_string($rm,$rd),"</b>&nbsp;&nbsp;</span>";
	    } else {
		print "<a class=\"dbtn\" href=\"$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=1&d=$rm/$rd/$ry$mg$::vmg\"><span class=\"dnbarTxt\">&nbsp;&nbsp;",md_string($rm,$rd),"&nbsp;&nbsp;</span></a>";
	    }
	}
    }
}
#=========================================================================================================================
sub print1Entry {
    my $href = shift;
    my $out = "{\n";
    my ($role, $tmp, $ee);
    if(! $href->{'seq'}) { $href->{'seq'} = int(999999999*rand());} # for old events.
    for $role (keys %$href) {
	if($role eq 'exception') {
	    $out .= "exception=>[";
	    $tmp=$href->{$role};
	    if($tmp) {  $ee = join(',', @{$tmp});} else {$ee="";}
	    $out .=  $ee;
	    $out .= "],\n";
	} elsif($role ne 'in') {
	    $tmp="$href->{$role}";
	    $tmp =~ s/\\//g; $tmp =~ s/\'/\\\'/g; 
	    if($role eq 'cs') { $tmp =~ s/_/\-/g;}
	    if($tmp ne '') {   $out .= "$role=>\'$tmp\',\n"; }

	}
    }
    $out .= "},\n";
    return $out;
}
#=====================================================================================================
sub getHdrFtr {
    my ($name) = (@_);
    my ($header, $footer, $hcr, $this_day, $imgfile);
    $hcr="";
    if($::calinfo{'hdr'}) { $header = customize_header(substImages($::calinfo{'hdr'}));}
    elsif($::o{'headerCode34'}) { $header = customize_header(substImages($::o{'headerCode34'}));}#
    else {
	my ($localdocA, $localdocB) = &getdocURL();
	$this_day = &getThemeColor;
	$imgfile = "webcalendar00${this_day}.gif";
	$header = "$localdocA<img src=\"$::o{'imgdirurl'}/$imgfile\" width=331 height=47 border=0>$localdocB&nbsp;<b><span class=\"calendarTitle\">$name</span></b>"; 
    }

    if($::calinfo{'ftr'}) { $footer = customize_header(substImages($::calinfo{'ftr'}));}
    elsif($::o{'footerCode'}) { $footer = customize_header(substImages($::o{'footerCode'}));}      
    else { 
	my $tmp = $webcalConfig::r{'cgiInfoA'};
	$tmp =~ s/<br>/&nbsp;/g;
	$footer ="<br>$tmp<br>";
    }
    return ($header, $footer, $hcr);
}

sub select_Month {
    my ($name,$value,$v,$ret, $i);
    ($name,$value) = (@_);
    $ret = "<select name=\"$name\" class=\"fmListS\">";

    for($i = 1; $i <= 12; $i++) {
	my $n = $::mNames[$i-1];
	$ret .= "<option value=\"$i\"";
	$ret .= " selected" if ($i eq $value);
	$ret .= ">$n";
    }
    $ret .= "</select>";
    return $ret;
}
sub select_Day {
    my ($name,$value,$v,$ret, $i);
    ($name,$value) = (@_);
    $ret = "<select name=\"$name\" class=\"fmListS\">";

    for($i = 1; $i <= 31; $i++) {
	$ret .= "<option value=\"$i\"";
	$ret .= " selected" if ($i eq $value);
	$ret .= ">$i";
    }
    $ret .= "</select>";
    return $ret;
}

sub navigationTable {
    my ($who, $view, $month, $day, $year, $ls, $mg, $table, $today, $mview, $wview, $tomorrow, $date, $goto, $n, $mgg);
    my ($prevc, $nextc, $left, $right, $middle, $date1, $tmm, $tmd, $tmy, $nls);
    my ($flag, $fm, $fd, $tm, $td) = (@_);
    my ($hclr, $dclr, $vclr, $lclr);
    $hclr= $webcalConfig::r{'v34clr_h'};   $dclr = $webcalConfig::r{'v34clr_b'};  $vclr= $webcalConfig::r{'v34clr_v'};
    $lclr = $webcalConfig::r{'v34clr_t'};
    $who = $::calinfo{'w'};
    if($::d{'megaCal'} ne "") {
        $mg="&mg=$::d{'megaCal'}"; $mgg="<input type=hidden name=mg value=\"$::calinfo{'mg'}\">";        
    } else {$mgg=$mg="";}
    $view = $::calinfo{'v'};
    $ls = $::calinfo{'ls'};  $nls = - $ls;
    $month= $::calinfo{'month'};
    $day  = $::calinfo{'day'};
    $year = $::calinfo{'year'};
    $date = printDate0( $::now{'month'}, $::now{'day'}, $::now{'year'});

    $table= <<END;
<font size=2><br><br></font><table border=0 cellspacing=1 cellpadding=0><tr><td bgcolor="#d8dcd8" class="v34navHolder">
<table border=0 cellspacing=0 cellpadding=0 width=150 class="v34navtbl">
END
    ;
    if($view == 1) { $prevc = printDate0( $month, $day -1, $year); $nextc = printDate0( $month, $day +1, $year); }
    elsif($view == 2) { $prevc = printDate0( $month, $day -7, $year); $nextc = printDate0( $month, $day +7, $year); }
    elsif($view == 4) { $prevc = printDate0( $month, 1, $year-1); $nextc = printDate0( $month, 1, $year+1); }
    else { $prevc = printDate0( $month-1, 1, $year); $nextc = printDate0( $month+1, 1, $year); }
    my $today_href = "$::o{'cginame'}?c=get&ls=$ls&w=$who&v=1&d=$date$mg$::vmg";
    $today ="<a href=\"$today_href\" class=\"transparent\"><font $webcalConfig::fontsize{'menubar'} color=#ffffff><span class=\"v34nav\">&nbsp;&nbsp;$::phr{'Today'}&nbsp;&nbsp;</span></font></a>\n";
    $left ="<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$prevc$mg$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/left.gif\" width=11 height=11 border=0 title=\"$::phr{'Previous'}\" alt=\"$::phr{'Previous'}\"></a>&nbsp;";
    $right = "&nbsp;<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$nextc$mg$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/right.gif\" width=11 height=11 border=0 title=\"$::phr{'Next'}\" alt=\"$::phr{'Next'}\"></a>";

    if(($::vm & 0x400) == 0) {
        my ($xx,$yy, $zz, $listA, $tag2, $tag3, $v2, $v3, $mtb);
        $xx = $::vm; $zz = ($xx | 0x400); $zz="&x=$zz$::vmc"; 
        if(($xx & 0x200)) { # list view 3
            $yy = $xx & ~0x200; $tag2="a"; $tag3="notused"; $v3="v"; $v2="";
        } else { #listview 2
            $yy = $xx | 0x200; $tag3="a"; $tag2="notused"; $v3=""; $v2="v";
        }
        $listA = "&x=$yy$::vmc";
        $mtb ="<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$month/$day/$year$mg$zz\"><img src=\"$::o{'imgdirurl'}/ms.gif\" width=9 height=9 border=0></a>";

        $middle =<<END;
<a href="$::o{'cginame'}?c=get&ls=0&w=$who&v=$view&d=$month/$day/$year$mg$::vmg" class="transparent"><img src="$::o{'imgdirurl'}/zblock.gif" width=15 height=15 border=0 title="$::phr{'BlockView'}" alt="$::phr{'BlockView'}"></a>&nbsp;
<a href="$::o{'cginame'}?c=get&ls=1&w=$who&v=$view&d=$month/$day/$year$mg$::vmg" class="transparent"><img src="$::o{'imgdirurl'}/zlist.gif" width=15 height=15 border=0 title="$::phr{'ListView'}" alt="$::phr{'ListView'}"></a>&nbsp;
<$tag2 href="$::o{'cginame'}?c=get&ls=-1&w=$who&v=$view&d=$month/$day/$year$mg$listA" class="transparent"><img src="$::o{'imgdirurl'}/${v2}zlist1.gif" width=15 height=15 border=0 title="$::phr{'ListView'} 2" alt="$::phr{'ListView'} 2"></$tag2>
<$tag3 href="$::o{'cginame'}?c=get&ls=-1&w=$who&v=$view&d=$month/$day/$year$mg$listA" class="transparent"><img src="$::o{'imgdirurl'}/${v3}zlist2.gif" width=15 height=15 border=0 title="$::phr{'ListView'} 3" alt="$::phr{'ListView'} 3"></$tag3>

END
    ;
    my $goto_href="$::o{'cginame'}?c=gotod&w=$who&v=$view&ls=$ls&d=$month/$day/$year$mg$::vmg";
    $goto="<a href=\"$goto_href\" class=\"transparent\"><font $webcalConfig::fontsize{'menubar'} color=#ffffff><span class=\"v34nav\">$::phr{'Goto_Date'}</span></font></a> &nbsp;&nbsp;$mtb";

    my $mview_href = "$::o{'cginame'}?c=get&ls=$ls&w=$who&v=3&d=$date$mg$::vmg";
    $mview = "<a href=\"$mview_href\" class=\"transparent\"><font $webcalConfig::fontsize{'menubar'} color=#ffffff><span class=\"v34nav\">$::phr{'ThisMonth'}</span></font></a>";
    my $wview_href="$::o{'cginame'}?c=get&ls=$ls&w=$who&v=2&d=$date$mg$::vmg";
    $wview = "<a href=\"$wview_href\" class=\"transparent\"><font $webcalConfig::fontsize{'menubar'} color=#ffffff><span class=\"v34nav\">$::phr{'ThisWeek'}</span></font></a>";

    ($tmm, $tmd, $tmy) = canDate($::now{'month'}, $::now{'day'}+1, $::now{'year'});
    $date1 = "$tmm/$tmd/$tmy";
    my $tomorrow_href = "$::o{'cginame'}?c=get&ls=$ls&w=$who&v=1&d=$date1$mg$::vmg";
    $tomorrow ="<a href=\"$tomorrow_href\" class=\"transparent\"><font $webcalConfig::fontsize{'menubar'} color=#ffffff><span class=\"v34nav\">$::phr{'Tomorrow'}</span></font></a>\n";

    my($c1, $c2, $c3, $c4, $c5);  $c1 = $c2 = $c3 = $c4 = $c5 =$dclr;
    my($s1, $s2, $s3, $s4, $s5);  $s1 = $s2 = $s3 = $s4 = $s5 ="";
    
    if($flag) {
	if($view == 1) {  
	    if($month == $::now{'month'} and $day == $::now{'day'} and $year == $::now{'year'}) { $c1 = $vclr;$s1="Active";}
	    elsif($month == $tmm and $day == $tmd and $year == $tmy) { $c2 = $vclr;$s2="Active";}
	} elsif($view == 2) {
	    my $wknuma = weekNum($month,$day,$year, $::o{'weekstart'});
	    my $wknumb = weekNum($::now{'month'},$::now{'day'},$::now{'year'},$::o{'weekstart'});
	    if($wknuma == $wknumb ) { $c3 = $vclr;$s3="Active";}
	} elsif($view == 3) {
	    if($month == $::now{'month'} and $year == $::now{'year'}) { $c4 = $vclr;$s4="Active";}
	}
    }
    
    $table .= <<END;
<tr><td align=center bgcolor=$lclr valign=middle class="v34navTd0" nowrap><font color="#ffffff">
$left $middle $right </font></td></tr>
<tr><td height=3 class="v34hfiller" ><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=1 border=0></td></tr>
<tr><td align=center class="v34tdBIG">
  <table border=0 cellspacing=1 cellpadding=0 width=100 class="v34navtbl">
  <tr><td align=center bgcolor=$c1 class="vbtn$s1" onmouseover="chover(this,1,'vbtnHover','vbtn$s1')" 
onmouseout="chover(this,0,'vbtnHover','vbtn$s1')" onclick="ngoto(this, '$today_href')">$today</td></tr>
  <tr><td align=center bgcolor=$c2 class="vbtn$s2" onmouseover="chover(this,1,'vbtnHover','vbtn$s2')" 
onmouseout="chover(this,0,'vbtnHover','vbtn$s2')" onclick="ngoto(this, '$tomorrow_href')">$tomorrow</td></tr>
  <tr><td align=center bgcolor=$c3 class="vbtn$s3" onmouseover="chover(this,1,'vbtnHover','vbtn$s3')" 
onmouseout="chover(this,0,'vbtnHover','vbtn$s3')"  onclick="ngoto(this, '$wview_href')"> $wview</td></tr>
  <tr><td align=center bgcolor=$c4 class="vbtn$s4" onmouseover="chover(this,1,'vbtnHover','vbtn$s4')" 
onmouseout="chover(this,0,'vbtnHover','vbtn$s4')" onclick="ngoto(this, '$mview_href')"> $mview</td></tr>
  <tr><td height=8><img src="$::o{'imgdirurl'}/spacer.gif" width=4 height=4 border=0></td></tr>
  <tr><td align=center bgcolor=$c5 class="vbtn" onmouseover="chover(this,1,'vbtnHover','vbtn')" 
onmouseout="chover(this,0,'vbtnHover','vbtn')" onclick="ngoto(this, '$goto_href')"> $goto</td></tr>
  </table>
</td></tr>
<tr><td class="v34hfiller" align=center><font size=1>&nbsp;</font></td></tr>
END
    ;
    } else { # use a small month calendar to navigate
	make3MonthTable($month, $year,1);
	my($bgn, $end);
	if($view >= 3) { $bgn = 1; $end=31; } 
	elsif($view == 2) {
	    my $code = wday($month,$day,$year);
	    $bgn = $day - $code + $::o{'weekstart'};
	    if($::o{'excludeWeekend'}) { $end = $bgn + 4;} else { $end = $bgn + 6;}
	}
	else { $bgn = $end = $day;}
	my $tbl = mkSmallMCal($month, $day, $year, $bgn, $end, "width=\"96%\"", "height=16", 0, 1, '#cccccc', 1, 1, "v34");

        my ($xx,$yy,$zz, $listA, $tag2, $tag3, $v2, $v3,$lk, $nk);
        $xx = $::vm;
        $zz = $xx & ~0x400; $zz = "&x=$zz$::vmc";
        if(($xx & 0x200)) { # list view 3
            $yy = $xx & ~0x200;  $tag2="a"; $tag3="notused"; $v3="v"; $v2="";
        } else { #listview 2
            $yy = $xx | 0x200; $tag3="a"; $tag2="notused"; $v3=""; $v2="v";
        }
        $listA = "&x=$yy$::vmc";
        $nk="<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$month/$day/$year$mg$zz\"><font size=1 color=#6699ff><b>x</b></font></a>";
        $tbl =~ s/<i>&nbsp;<\/i>/$nk/;

	$middle= <<END;
<a href="$::o{'cginame'}?c=get&ls=0&w=$who&v=$view&d=$month/$day/$year$mg$::vmg" class="transparent"><img src="$::o{'imgdirurl'}/zblock.gif" width=15 height=15 border=0 title="$::phr{'BlockView'}" alt="$::phr{'BlockView'}"></a>
<a href="$::o{'cginame'}?c=get&ls=1&w=$who&v=$view&d=$month/$day/$year$mg$::vmg" class="transparent"><img src="$::o{'imgdirurl'}/zlist.gif" width=15 height=15 border=0 title="$::phr{'ListView'}" alt="$::phr{'ListView'}"></a>
<$tag2 href="$::o{'cginame'}?c=get&ls=-1&w=$who&v=$view&d=$month/$day/$year$mg$listA" class="transparent"><img src="$::o{'imgdirurl'}/${v2}zlist1.gif" width=15 height=15 border=0 title="$::phr{'ListView'} 2" alt="$::phr{'ListView'} 2"></$tag2>
<$tag3 href="$::o{'cginame'}?c=get&ls=-1&w=$who&v=$view&d=$month/$day/$year$mg$listA" class="transparent"><img src="$::o{'imgdirurl'}/${v3}zlist2.gif" width=15 height=15 border=0 title="$::phr{'ListView'} 3" alt="$::phr{'ListView'} 3"></$tag3>
END

	$table .= "<tr><td align=center bgcolor=$lclr valign=middle class=\"v34navTd0\">$left $middle $right </td></tr>
<tr><td align=center>$tbl</td></tr>
<tr><td align=center><table border=0 cellspacing=0 cellpadding=0><tr><td bgcolor=#cccccc class=\"v34today\">
<font size=1> &nbsp; $today &nbsp;</td></tr></table></font></td></tr>
<tr><td><br></td></tr>";
    }

    my ($fromM, $fromD, $toM, $toD);
    if(!defined $fm) {
	$fm = $::now{'month'}+1;
	$fd = $::now{'day'};
	($tmm, $tmd, $tmy) = canDate($::now{'month'}, $::now{'day'}+14, $::now{'year'});
	$tm = $tmm+1;
	$td = $tmd;
    }
    $fromM = select_Month('sfmonth', $fm);
    $fromD = select_Day('sfday', $fd);
    $toM = select_Month('stmonth', $tm);
    $toD = select_Day('stday', $td);

    $table .= <<END;
<tr><td align=center bgcolor=$lclr class=\"v34navTd0\"><font $webcalConfig::fontsize{'menubar'} color="#ffffff"><span class="v34nav">$::phr{'Search'}</span></font></td></tr>
<tr><td align=center class="v34tdBIG">
  <Form name=csearch action="$::o{'cginame'}" method=GET class=searchform>$::vmp
  <input type=hidden name=c value=dosearch>
<input type=hidden name=searchRange value="all">
  <input type=hidden name=w value="$who">
  <input type=hidden name=v value=$view>
  <input type=hidden name=ls value=$ls>
  <input type=hidden name=d value="$date">
  $mgg
<table border=0 cellspacing=0 cellpadding=0 width=100 class="v34navtbl">
  <tr><td align=right><font size=1><span class="fmLabelS">$::phr{'From'}:</span></font></td><td nowrap>$fromM $fromD</td></tr>
  <tr><td align=right><font size=1><span class="fmLabelS">$::phr{'To'}:</span></font></td><td nowrap>$toM $toD</td></tr>
  <tr><td colspan=2 nowrap><font size=1><span class="fmLabelS">&nbsp;$::phr{'Keyword'}:</span></font></td></tr>
  <tr><td align=center colspan=2 nowrap><input class="fmEntryS" type=text name=stopic size=10 value="$::srchftrptn">
<font size=2><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font><br>$::srchi</td></tr></table></form>
</td></tr>
<tr><td align=center class="v34hfiller"><font size=1>&nbsp;</font></td></tr>
END
#    <A HREF="javascript:document.csearch.submit()"><font color="#006699"><b><span class="fmLabelS">&nbsp;$::phr{'Go'}</span></b></font></A>
    my ($task, $diary, $notes, $addr, $option, $admin, $nevent, $printV, $logout);
    my ($option_href,$admin_href,$task_href,$addr_href,$notes_href,$diary_href,$printV_href,$logout_href) =("","","","","","","","");
    if(ismember('option', $::o{'tabs'})) {
	$option_href="$::o{'cginame'}?c=option&w=$who&v=$view&ls=$ls&d=$month/$day/$year$mg$::vmg";
	$option="<a href=\"$option_href\" class=\"transparent\">
<font $webcalConfig::fontsize{'menubar'} color=#ffffff><span class=\"v34nav\">$::phr{'Options'}</span></font></a>";
    } else { $option = "";}
    if( ($::vm & 0x1000) == 0) {
	$nevent = "
<tr><td align=center bgcolor=$lclr class=\"v34navTd0\"><font $webcalConfig::fontsize{'menubar'} color=#ffffff><span class=\"v34nav\">$::phr{'EventEditor'}</span></font></td></tr>
<tr><td align=center nowrap class=\"v34tdBIG\">
<a href=\"$::o{'cginame'}?c=ne&k=1&v=$view&ls=$ls&w=$who&d=$month/$day/$year$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/apt.gif\" width=21 height=22 border=0 title=\"$::phr{'Appointment'}\" alt=\"$::phr{'Appointment'}\"></a>
<a href=\"$::o{'cginame'}?c=ne&k=2&w=$who&v=$view&ls=$ls&d=$month/$day/$year$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/todo.gif\" width=21 height=22 border=0 title=\"$::phr{'Todo'}\" alt=\"$::phr{'Todo'}\"></a>
<a href=\"$::o{'cginame'}?c=ne&k=3&w=$who&v=$view&ls=$ls&d=$month/$day/$year$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/meeting.gif\" width=21 height=22 border=0 title=\"$::phr{'Meeting'}\" alt=\"$::phr{'Meeting'}\"></a>
<a href=\"$::o{'cginame'}?c=ne&k=4&w=$who&v=$view&ls=$ls&d=$month/$day/$year$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/special.gif\" width=21 height=22 border=0 title=\"$::phr{'Special'}\" alt=\"$::phr{'Special'}\"></a>
<a href=\"$::o{'cginame'}?c=vc&k=4&w=$who&v=$view&ls=$ls&d=$month/$day/$year$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/vcal.gif\" width=21 height=22 border=0 title=\"vCal\" alt=\"vCal\"></a>
</td></tr>
<tr><td  class=\"v34hfiller\"><font size=1>&nbsp;</font></td></tr>";
    } else { $nevent = "";}
    
    if(ismember('task', $::o{'tabs'})) {
	$task_href ="$::o{'cginame'}?c=task&w=$who&v=$view&ls=$ls&d=$month/$day/$year$mg$::vmg";
	$task = "<a href=\"$task_href\" class=\"transparent\"><font $webcalConfig::fontsize{'menubar'} color=#ffffff><span class=\"v34nav\">$::phr{'TaskManager'}</span></font></a>";
    } else { $task = "";}
    if(ismember('diary', $::o{'tabs'})) {
	$diary_href="$::o{'cginame'}?c=diary&w=$who&v=$view&ls=$ls&d=$month/$day/$year$::vmg";
	$diary = "<a href=\"$diary_href\" class=\"transparent\"><font $webcalConfig::fontsize{'menubar'} color=#ffffff><span class=\"v34nav\">$::phr{'Diary'}</span></font></a>";
    } else {$diary = "";}
    if(ismember('notes', $::o{'tabs'})) {
	$notes_href = "$::o{'cginame'}?c=notes&w=$who&v=$view&ls=$ls&d=$month/$day/$year$::vmg";
	$notes = "<a href=\"$notes_href\" class=\"transparent\"><font $webcalConfig::fontsize{'menubar'} color=#ffffff><span class=\"v34nav\">$::phr{'Notes'}</span></font></a>";
    } else {$notes = "";}

    if(ismember('ad', $::o{'tabs'})) {
	$addr_href="$::o{'cginame'}?c=ad&w=$who&v=$view&ls=$ls&d=$month/$day/$year$::vmg";
	$addr = "<a href=\"$addr_href\" class=\"transparent\"><font $webcalConfig::fontsize{'menubar'} color=#ffffff><span class=\"v34nav\">$::phr{'AddressBook'}</span></font></a>";
    } else { $addr = "";}
    $printV_href="$::o{'cginame'}?c=get&w=$who&v=$view&ls=$ls&pnt=1&d=$month/$day/$year$::vmg";
    $printV ="<a href=\"$printV_href\" class=\"transparent\" target=pnt><font $webcalConfig::fontsize{'menubar'} color=#ffffff><span class=\"v34nav\">$::phr{'Print'}</span></font></a>";
    if($::d{'remote_user'} ne 'anonymous' and $::d{'remote_user'} ne 'nobody') {
	$logout_href="$::o{'cginame'}?c=logout&w=$who";
	$logout = "<a href=\"$logout_href\" class=\"transparent\"><font $webcalConfig::fontsize{'menubar'} color=#ffffff><span class=\"v34nav\">$::phr{'Logout'}</span></font></a>";
    } else { $logout = "";}

    my ($cals, $go);
    if($::o{'listAllCals'} and &use_pulldown_nemu) {
        $::calinfo{'_clist_'} = 1;
	my @othercals = &listcals;
	my $allC = join(',',@othercals);
        delete $::calinfo{'_clist_'};        
	if($::d{'megaCal'} ne "") {
            #unshift @othercals,$::phr{'CombinedCalendar'};
            $cals=select_optionX("w","$::phr{'CombinedCalendar'}",$::d{'megaCal'}, @othercals);
	} else {$cals=select_option("w",$who,@othercals);}
	my $acs = 0+@othercals;
	if($acs > 1 and $acs < 20) {
	    $cals =~ s#</select>#<option value=\"$allC\">== $::phr{'All'} ==</select>#; 
	}
	$cals =~ s/class=\"fmList\"/class=\"fmListS\"/;
	$cals =~ s/>/ onChange=\"javascript:document.webcal.submit();\">/; #"
        $go="";
    } else {
        my $tt; 
	if($::d{'megaCal'} ne "") { $tt=$::d{'megaCal'}; } else  { $tt= $who;}
        $cals = "<input type=text size=16 maxlength=96 name=w value=\"$tt\" class=\"fmEntryS\">";
        $go  = "<A HREF=\"javascript:document.webcal.submit()\"><font color=#006699><b><span class=\"fmLabelS\">&nbsp;$::phr{'Go'}</span></b></font></A>";
    }
    my $catlist="";
    if($::o{'category_filter'} and $::calinfo{'cfilter'} and not ($::vm &0x400000)) {
	my $cat; if($::calinfo{'category'}){$cat=$::calinfo{'category'};}else{$cat="";}
	$catlist = build_catlist($who,'category',1, $cat); $catlist =~ s/fmList/fmListH/g;
	if($catlist) {my $tmp=""; if($cat !~ /^\s*$/) {$tmp="<img src=\"$::o{'imgdirurl'}/run.gif\" align=absmiddle border=0 width=24 height=8 title=\"\">";}
	    $catlist = "<br><font size=-1><span class=fmLabelS>$::phr{'Category'}:</span>$tmp<br></font>$catlist";
	}
    }

    if( ($::vm & 0x1) == 0) {
	$table .=<<END;
<tr><td align=center bgcolor=$lclr class="v34navTd0"><font $webcalConfig::fontsize{'menubar'} color="#ffffff"><span class="v34nav">$::phr{'Calendar'}</span></font></td></tr>
<tr><td align=center nowrap class="v34tdBIG"><form name=webcal action="$::o{'cginame'}" method=GET class=searchform>$::vmp
  <input type=hidden name=c value=get>
  <input type=hidden name=v value=$view>
  <input type=hidden name=ls value=$ls>
  <input type=hidden name=ww value=$who>
  <input type=hidden name=d value="$date">
  <font size=1>$cals</font>$go
  $catlist
</form>
</td></tr>
<tr><td class="v34hfiller"><font size=1>&nbsp;</font></td></tr>
END
    }
    if(($::vm & 0x8) == 0) {
	$table .= "$nevent 
<tr><td align=center class=\"v34tdBIG\">
<table border=0 cellspacing=1 width=100>";

    if($task){
	$table .=<<END;
<tr><td align=center bgcolor=$dclr nowrap class="vbtn" onmouseover="chover(this,1,'vbtnHover','vbtn')" 
onmouseout="chover(this,0,'vbtnHover','vbtn')" onclick="ngoto(this, '$task_href')">$task</td></tr>
END
    ;
    }
    if($diary){
	$table .=<<END;
<tr><td align=center bgcolor=$dclr nowrap class="vbtn" onmouseover="chover(this,1,'vbtnHover','vbtn')" 
onmouseout="chover(this,0,'vbtnHover','vbtn')" onclick="ngoto(this, '$diary_href')">$diary</td></tr>
END
    ;
}
    if($notes){
	$table .=<<END;
<tr><td align=center bgcolor=$dclr nowrap class="vbtn" onmouseover="chover(this,1,'vbtnHover','vbtn')" 
onmouseout="chover(this,0,'vbtnHover','vbtn')" onclick="ngoto(this, '$notes_href')">$notes</td></tr>
END
    }
    if($addr){ 
	$table .=<<END;
<tr><td align=center bgcolor=$dclr nowrap class="vbtn" onmouseover="chover(this,1,'vbtnHover','vbtn')" 
onmouseout="chover(this,0,'vbtnHover','vbtn')" onclick="ngoto(this, '$addr_href')">$addr</td></tr>
END
}
    if($option){ 
	$table .=<<END;
<tr><td align=center bgcolor=$dclr class="vbtn" onmouseover="chover(this,1,'vbtnHover','vbtn')" 
onmouseout="chover(this,0,'vbtnHover','vbtn')" onclick="ngoto(this, '$option_href')">$option</td></tr>
END
}
    $table .= <<END;
  </table>
</td></tr>
END
 }
    $table .=<<END;
<tr><td align=center class="v34tdBIG"><table border=0 cellspacing=1 width=100>
<tr><td align=center bgcolor=$dclr nowrap class="vbtn" onmouseover="chover(this,1,'vbtnHover','vbtn')" 
onmouseout="chover(this,0,'vbtnHover','vbtn')"  onclick="ngoto(this, '$printV_href')">$printV</td></tr>
END
    if($logout){
	$table .=<<END;
<tr><td align=center bgcolor=$dclr class="vbtn" onmouseover="chover(this,1,'vbtnHover','vbtn')" 
onmouseout="chover(this,0,'vbtnHover','vbtn')" onclick="ngoto(this, '$logout_href')">$logout</td></tr>
END
   }
    $table .= "</table>
</td></tr>
<tr><td>&nbsp;</td></tr>
</table>
</td></tr>
</table>";

    $table;
}
#=====================================================================================================
sub readData {
    if(not $::d{'megaCal'}) { 
        tryReadCache($::calinfo{'w'},  $::calinfo{'v'}, $::calinfo{'month'},  $::calinfo{'day'},  $::calinfo{'year'});
    }
}
sub tryReadCache {
    my($who, $view,$cmn, $cdy, $cyr) = (@_);
    if(1) { 
	my ($cdir, $cfile, $tmn, $tdy, $tyr, $datafile, $cached, $cachefile);
	my ($datm, $cachem);
	$datafile = "$::o{'spooldir'}/$who/data";
	$cdir="$::o{'spooldir'}/$who/cache";
	$cachefile = "";
	$cached = 0;
	$ = time;
	if($view == 3) { # month view
	    $cachefile = "$cdir/".untaintname("m$cyr-$cmn",$::phr{'invalid_date'});
	    if( -f "$cachefile") {
		$datm = -M "$datafile";
		$cachem = -M "$cachefile";
		if ($cachem >= 0.0 and $cachem <= $datm ) { # cache is newer than data, check date
		    @::mdata=();
                    if( doReadFile("$cachefile")) {
                        @::caldata = @::mdata;
                        $cached = 1;
                    } 
		}
	    }
	} elsif($view == 2) { #weekview
	    my $start = $::o{'weekstart'};
	    my $wknum = weekNum($cmn, $cdy, $cyr, $start);
	    $cachefile = "$cdir/".untaintname("w$cyr-$wknum",$::phr{'invalid_date'});
	    if( -f "$cachefile") {
		$datm = -M "$datafile";
		$cachem = -M "$cachefile";
		if ($cachem >= 0.0 and $cachem <= $datm ) { # cache is newer than data, check date
		    @::wdata=();
                    if( doReadFile("$cachefile")) {
                        @::caldata = @::wdata;
                        $cached = 1; 
                    }
		}
	    } elsif($cdy >= 7 and ($cdy <= 21 or $cmn != 1 and $cdy <= 23) ) {
		$cachefile = "$cdir/".untaintname("m$cyr-$cmn",$::phr{'invalid_date'});
		if( -f "$cachefile") {
		    $datm = -M "$datafile";
		    $cachem = -M "$cachefile";
		    if ($cachem >= 0.0 and $cachem <= $datm ) { # cache is newer than data, check date
			@::mdata=();
                        if( doReadFile("$cachefile")) {
                            @::caldata = @::mdata;
                            $cached = 1;
                        }
		    }
		}		
	    }
	} elsif($view == 1) { #
	    $cachefile = "$cdir/".untaintname("d$cyr-$cmn-$cdy",$::phr{'invalid_date'});
	    if( -f "$cachefile") {
		$datm = -M "$datafile";
		$cachem = -M "$cachefile";
		if ($cachem >= 0.0 and $cachem <= $datm ) { # cache is newer than data, check date
		    @::ddata=();
                    if( doReadFile("$cachefile")) {
                        @::caldata = @::ddata;
                        $cached = 1; 
                    }
		}
	    } else {
		my $start = $::o{'weekstart'};
		my $wknum = weekNum($cmn, $cdy, $cyr, $start);
		$cachefile = "$cdir/".untaintname("w$cyr-$wknum",$::phr{'invalid_date'});
		if( -f "$cachefile") {
		    $datm = -M "$datafile";
		    $cachem = -M "$cachefile";
		    if ($cachem >= 0.0 and $cachem <= $datm ) { # cache is newer than data, check date
			@::wdata=();
                        if( doReadFile("$cachefile")) {
                            @::caldata = @::wdata;
                            $cached = 1; 
                        }
		    }
		} else {
		    $cachefile = "$cdir/".untaintname("m$cyr-$cmn",$::phr{'invalid_date'});
		    if( -f "$cachefile") {
			$datm = -M "$datafile";
			$cachem = -M "$cachefile";
			if ($cachem >= 0.0 and $cachem <= $datm ) { # cache is newer than data, check date
			    @::mdata=();
                            if( doReadFile("$cachefile")) {
                                @::caldata = @::mdata;
                                $cached = 1;
                            }
                        }
		    }
		}    
	    }
	} elsif($view == 4) { #year view
            if($::calinfo{'ls'} == 0 and not $::catfilterpattern and not $::srchftrptn) {
                my $cacheDfile = "$cdir/".untaintname("y-$cyr",$::phr{'invalid_date'});
                $cachefile = "$cdir/".untaintname("yt-$cyr",$::phr{'invalid_date'});
                if( -f $cachefile and -f $cacheDfile) {
		    $datm = -M "$datafile";
                    $cachem = -M "$cachefile";
                    if ($cachem >= 0.0 and $cachem <= $datm ) { # cache is newer than data, check date
			@::ydata=();
			if( doReadFile("$cacheDfile")) {
			    @::caldata = @::ydata;			
			    $cached = 1;
			}
                    }
                }
            }
	}
    	if($cached == 0) {  doReadFile("$datafile");}
    }
}
#=====================================================================================================
sub cacheData {
    if(not $::cache_info{'megaCal'}) { # month is in [0..11] !!
	my ($i, $pid, $sess_id);
        my ($who, $cdir, $cfile, $cmn, $cyr, $cdy, $tmn, $tdy, $tyr, $datm, $cam, $datafile);
        my ($cachefile, $view, $wknum, $doit, $dotable, $data_read, $pnd);
        $who = $::cache_info{'w'};   
        $view = $::cache_info{'v'};  
        $cdy = $::cache_info{'day'}; 
        $cmn = $::cache_info{'month'};
        $cyr = $::cache_info{'year'}; 
        if($::cache_info{'spooldir'} =~ /^(.+)$/) {$::cache_info{'spooldir'} = $1;} # untaint
        $cdir="$::cache_info{'spooldir'}/$who/cache";
        if(! -d "$cdir") { mkdir("$cdir", 0711);}
        $datafile = "$::cache_info{'spooldir'}/$who/data";
        $cachefile="";
        $doit = $dotable = $data_read = $pnd = 0;
        if($view == 3) { #month view
            $cachefile = "m$cyr-$cmn";
        } elsif($view == 2) { #weekview
            my $start = $::cache_info{'weekstart'};
            $wknum = weekNum($cmn, $cdy, $cyr, $start);
            $cachefile = "w$cyr-$wknum";
        } elsif($view == 1) { #dayview
            $cachefile = "d$cyr-$cmn-$cdy";
            $dotable =1;
        } else { $dotable =1;}
        if( $cachefile) {
            my $tmpfile = untaintname($cachefile,$::phr{'invalid_date'});
            $cachefile = "$cdir/$tmpfile";
            if(! -f "$cachefile") {$doit = 1;}
            else {
                $ = time;
                $datm = -M "$datafile";
                $cam = -M "$cachefile";
                if($datm <= $cam or $cam < 0.0) { $doit = 1;}
            }
            #open(LOG , ">/tmp/log");
            if($doit) { $doit = doReadFile("$datafile"); $data_read = 1;}
            if($doit) { 
                my ($ay, $am, $ad, $by, $bm, $bd, %css);
                my ($href, $eM, $eD, $eY, $sM, $sD, $sY, $role, $tmp, $ee, $date);
                my $fhcfm = gensym;
		%css = ();
                if($view ==3) {
                    my $fhcfm = gensym;
                    if(sysopen($fhcfm, "$cachefile", O_WRONLY | O_CREAT, 0644 ) and &webcalLock::doflock(\*$fhcfm, LOCK_EX, "$cachefile")) {
                        truncate($fhcfm, 0);
                        ($am, $ad, $ay ) = canDate($cmn, -6, $cyr);
                        ($bm, $bd, $by ) = canDate($cmn, 37, $cyr);
                        for $href (@::caldata) {
			    $pnd++ if $href->{'pnd'};
			    if($href->{'cs'}) { my ($tmp,$jnk)=extract_cal_css_name($href->{'cs'}); $css{$tmp}=1 if $tmp;}
                            if($href->{'end'}) { ($eM, $eD, $eY) = split(/\//, $href->{'end'}); $eM--;}
                            else {($eM, $eD, $eY) = (11,30,3000);}
                            $date = $href->{'date'};
                            if( $href->{'kind'} == 2) { $date = $href->{'bdate'} if $href->{'bdate'};}
                            ($sM, $sD, $sY) = split(/\//, $date); $sM--;
                            if( mdyAafterB($am, $ad, $ay, $eM, $eD, $eY) < 2 and mdyAafterB($sM, $sD, $sY, $bm, $bd, $by) < 2) {
                                #print LOG "Cached: [$am, $ad, $ay, $eM, $eD, $eY]  [$sM, $sD, $sY, $bm, $bd, $by]\n";
                                $href->{'mcm'} = 1;
                            } elsif($href->{'kind'} == 2 and (!defined $href->{'done'} or $href->{'done'} ne 'y')) {
                                if(defined $href->{'forward'} and $href->{'forward'} eq 'y' and
                                   mdyAafterB($bm, $bd, $by, $eM, $eD, $eY) ) { $href->{'mcm'} = 1;}
                            }
                            #else {  print LOG "======: [$am, $ad, $ay, $eM, $eD, $eY]  [$sM, $sD, $sY, $bm, $bd, $by]\n";}
                        }
                        print $fhcfm '@::mdata=(';
                        for $href (@::caldata) { 
                            if(defined $href->{'mcm'}) {
                                delete $href->{'mcm'};
                                $tmp = print1Entry($href);
                                print $fhcfm $tmp;
                            }
                        }
                        print $fhcfm ");\n1;\n";
                        &webcalLock::doflock(\*$fhcfm, LOCK_UN, "$cachefile");
                        close $fhcfm;
                    }
                } elsif($view == 2) {
                    my $fhcfw = gensym;
                    if(sysopen($fhcfw, "$cachefile", O_WRONLY | O_CREAT, 0644 ) and &webcalLock::doflock(\*$fhcfw, LOCK_EX, "$cachefile")) {
                        truncate($fhcfw, 0);
                        my $wcode = wday($cmn, $cdy, $cyr);
                        if($::cache_info{'weekstart'}) { #week starts on Monday
                            $wcode = 7 if ($wcode == 0);
                            ($am, $ad, $ay ) = canDate($cmn, $cdy-$wcode +1, $cyr);
                            ($bm, $bd, $by ) = canDate($cmn, $cdy + 14-$wcode, $cyr); # look at two weeks advance, fb table
                        } else {
                            ($am, $ad, $ay ) = canDate($cmn, $cdy-$wcode, $cyr);
                            ($bm, $bd, $by ) = canDate($cmn, $cdy + 13-$wcode, $cyr); # look at two weeks advance
                        }
                        for $href (@::caldata) {
			    $pnd++ if $href->{'pnd'};
			    if($href->{'cs'}) { my ($tmp,$jnk)=extract_cal_css_name($href->{'cs'}); $css{$tmp}=1 if $tmp;}
                            ($eM, $eD, $eY) = split(/\//, $href->{'end'}); $eM--;
                            $date = $href->{'date'};
                            if( $href->{'kind'} == 2) { $date = $href->{'bdate'} if $href->{'bdate'};}
                            ($sM, $sD, $sY) = split(/\//, $date); $sM--;
                            if( mdyAafterB($am, $ad, $ay, $eM, $eD, $eY) < 2 and mdyAafterB($sM, $sD, $sY, $bm, $bd, $by) < 2) {
                                $href->{'mcw'} = 1;
                            } elsif($href->{'kind'} == 2 and (!defined $href->{'done'} or $href->{'done'} ne 'y')) {
                                if(defined $href->{'forward'} and $href->{'forward'} eq 'y' and
                                   mdyAafterB($bm, $bd, $by, $eM, $eD, $eY) ) { $href->{'mcw'} = 1;}
                            }				
                        }
                        print $fhcfw '@::wdata=(';
                        for $href (@::caldata) { 
                            if(defined $href->{'mcw'}) {
                                delete $href->{'mcw'};
                                $tmp = print1Entry($href);
                                print $fhcfw $tmp;
                            }
                        }
                        print $fhcfw ");\n1;\n";
                        &webcalLock::doflock(\*$fhcfw, LOCK_UN, "$cachefile");
                        close $fhcfw;
                    } 
                } elsif($view == 1) {
                    my $fhcfd = gensym;
                    if(sysopen($fhcfd, "$cachefile", O_WRONLY | O_CREAT, 0644) and &webcalLock::doflock(\*$fhcfd, LOCK_EX,"$cachefile")) {
                        truncate($fhcfd, 0);
                        ($am, $ad, $ay ) = ($cmn, $cdy, $cyr);
                        ($bm, $bd, $by ) = canDate($cmn, $cdy + 1, $cyr);
                        for $href (@::caldata) {
			    $pnd++ if $href->{'pnd'};
			    if($href->{'cs'}) { my ($tmp,$jnk)=extract_cal_css_name($href->{'cs'}); $css{$tmp}=1 if $tmp;}
                            ($eM, $eD, $eY) = split(/\//, $href->{'end'}); $eM--;
                            $date = $href->{'date'};
                            if( $href->{'kind'} == 2) { $date = $href->{'bdate'} if $href->{'bdate'};} 				
                            ($sM, $sD, $sY) = split(/\//, $date); $sM--;
                            if( mdyAafterB($am, $ad, $ay, $eM, $eD, $eY) < 2 and mdyAafterB($sM, $sD, $sY, $bm, $bd, $by) < 2) {
                                $href->{'mcd'} = 1;
                            } elsif($href->{'kind'} == 2 and (!defined $href->{'done'} or $href->{'done'} ne 'y')) {
                                if(defined $href->{'forward'} and $href->{'forward'} eq 'y' and
                                   mdyAafterB($bm, $bd, $by, $eM, $eD, $eY) ) { $href->{'mcd'} = 1;}
                            }				
                        }
                        print $fhcfd '@::ddata=(';
                        for $href (@::caldata) { 
                            if(defined $href->{'mcd'}) {
                                delete $href->{'mcd'};
                                $tmp = print1Entry($href);
                                print $fhcfd $tmp;
                            }
                        }		
                        print $fhcfd ");\n1;\n";
                        &webcalLock::doflock(\*$fhcfd, LOCK_UN, "$cachefile");
                        close $fhcfd;
                    }
                }
		my $css= join(':', (keys %css));
		if($css) {
                    my $fhcss = gensym;
		    my $cachefile = "$::cache_info{'spooldir'}/$who/css";
		    
                    if(sysopen($fhcss, "$cachefile", O_WRONLY | O_CREAT, 0644 ) and &webcalLock::doflock(\*$fhcss, LOCK_EX, "$cachefile")) {
			$::mycss="";
			do "$cachefile" if -f "$cachefile";
			truncate($fhcss, 0);   
			my $tmp = "$::mycss" . ":" . $css;
			$css = unique_css($tmp);
			print $fhcss "\$::mycss=\'$css\';\n1;\n";
                        &webcalLock::doflock(\*$fhcss, LOCK_UN, "$cachefile");
                        close $fhcss;			
		    }
		}
		if($pnd) { &markHasPending("$::cache_info{'spooldir'}/$who/pnd");}
	    }
        }
        $doit = 1; my $LOADAVG= gensym;
        if (open($LOADAVG, '/proc/loadavg')) {
            while(<$LOADAVG>) {
                my @loadavg = split(/\s/, $_);
                $doit = 0 if ($loadavg[0] > 2.0);
                last;
            }
            close($LOADAVG);
        }
        if($doit) {
	    if($dotable) {
		if(not $data_read)  { doReadFile("$datafile");}
		makeYearTable($cyr,$::cache_info{'spooldir'},$who, "", $::cache_info{'dctoc'});
	    }
	    my $DIR3= gensym;
            if( opendir($DIR3, $cdir )) { # book keeping. Remove cache older than two weeks
                my @filenames = readdir($DIR3);
                closedir($DIR3);
                my $cname;
                for $cname (@filenames) {
                    next if "$cname" =~ /\^./;
                    $cname = untaintname($cname, "");
                    my $fname = "$cdir/$cname";
                    $ = time;
                    unlink("$fname") if -M  $fname > 14;
                }
            }
        }
        %::cache_info=();
    }
}
sub extract_cal_css_name{
    my ($in)=(@_); my ($a,$b)=("",""); 
    if($in =~ /^w[\-_](.+)[\-_]sCs[\-_](.+)/ ) {
	$a=$1; $b=$2;
	$a =~ s/\-dot\-/\./g; $a =~ s/\-eq\-/=/g; 
	$a =~ s/\-dash\-/\-/g; $a =~ s/\-uscore\-/_/g;
    }
    return ($a,$b);
};
sub unique_css {
    my ($css) = (@_);
    my @all =split(/:/, $css);
    my (%h, @m, $a, $r); %h=(); @m=(); $r="";
    for $a (@all) {if(! exists $h{$a}) { $h{$a}=1; if( -d "$::o{'spooldir'}/$a") { push @m, $a;}}}
    return join(':', @m);
}

sub markHasPending {
    my ($cachefile) = (@_);
    write_file($cachefile,"1");
}
#=====================================================================================================
sub build_catlist {
    my ($who, $name, $icode, $cat) = (@_);
    my $file = "$::o{'spooldir'}/$who/cats";
    %::cats=(); doReadFile($file); if($cat and $cat !~ /^\s+$/) {$::cats{$cat}=$cat;}
    my ($code, $v)=("","");
    if(scalar(%::cats)) {
	if($icode <= 0) { # used in event editors
	    $code="onchange=\"javascript:setcat()\""; if($name eq "dndcat"){$code ="";}
	    $::cats{'?????'} = " ";
	} else {  # used in category filter list
	    $code = "onchange=\"javascript:document.webcal.submit();\"";
	    my $tmp = "==$::phr{'All'}==";
	    $::cats{$tmp} = " ";
	}
	$v = select_hash($name, $cat, $code, \%::cats);
	if($icode == 0 and $::d{'authResult'} > 3){ # normal event editor
	    my $url="$::o{'cgimisc'}?w=$who&cmd=efile&file=cats";
	    $v .= "<a href=\"javascript:openpopup('$url','cats',680,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>";
	} elsif($icode > 0) {
	    $v .= "<input type=hidden name=\"hiddencat\" value=\"\">";
	}
    } else {$v="";}
    return $v;
}
sub update_catlist {
    my ($who, $cat) = (@_);    
    if($cat) {
	my $file = "$::o{'spooldir'}/$who/cats";
	%::cats=(); doReadFile($file); 
	if(!$::cats{$cat}) {
	    $::cats{$cat}=$cat;
	    my ($r, $k); $r='%::cats=(';
	    for $k (keys %::cats) { $k=~ s/\'/\\\'/g; $r .= "\'$k\'=>\'$k\',\n";} $r .=");\n";
	    write_file($file, $r);
	}
    }
}
sub build_ncatlist {
    my ($who, $cat) = (@_);
    my $file = "$::o{'spooldir'}/$who/cats";
    %::cats=(); doReadFile($file); if($cat and $cat !~ /^\s+$/) {$::cats{$cat}=$cat;}
    my ($code, $v)=("","");
    if(scalar(%::cats)) {
	$code = "onchange=\"javascript:setnotecat()\"";
	$v = select_hash('ignore', $cat, $code, \%::cats);
    } else {$v="";}
    return $v;
}
#=====================================================================================================
sub cal_menu_in_editor {
    my ($command, $who, $eme) = (@_);
    my $others;
    my $whol = "";
    if($::calinfo{'mg'}) { my $mg = $::calinfo{'mg'}; $mg =~ s/[,;]+/:/g; $others = expandMeetingGroups($eme,"$mg"); }
    else { $others = $::calinfo{'clist'}; $others =~ s/[,;]+/:/g; }
    my (%hh, $mem, $sel, $mixed);  %hh= (); $mixed=0;
    my @members=(); 
    my (@tmem) = split(/:/, $others);
    for $mem (@tmem) {
	if($mem and $mem ne $::phr{'none'} and ! exists $hh{$mem}) {
	    push @members, $mem; 
	    if(getinfo($mem, "resrc")) { $mixed |= 1;} else {$mixed |= 2;}
	    $hh{$mem} = 1;
	}
    }  
    if($mixed == 1) {$::calinfo{'noinvitee'} = 1;};
    if(! $hh{$who}) { push @members, $who; $sel=""; $sel=$who if $command ne "nevent";} else {$sel= $who;}
    if( 0+@members > 1) {
	$whol =  select_option("w",$sel, @members);
	$whol .= "<input type=hidden name='dateformat_in' value=\"$::o{'dateformat'}\">";
	if($command ne "nevent"){$whol .= "<input type=hidden name=\"owho\" value=\"$who\">";}
	$::calinfo{'smgpowner'} = 1;
    }
    return $whol;
}
#=====================================================================================================
sub bp_repeat_occur {
    my ($repeat,$occurs) = (@_);
    my ($tmp, $recurr); $recurr="";

    if($occurs eq 'MTWThF') { 
	$tmp = int(($repeat+4) / 5); 
	if($tmp * 5 != $repeat) {  $recurr="MTWThF:$tmp:$repeat"; }
	$repeat= $tmp;
    } elsif ($occurs eq 'MWF') {
	$tmp = int(($repeat+2) / 3); 
	if($tmp * 3 != $repeat) { $recurr="MWF:$tmp:$repeat";}
	$repeat = $tmp;
    } elsif ($occurs eq 'TTh') { 
	$tmp =($repeat+1) >> 1; 
	if($repeat & 1) { $recurr="TTh:$tmp:$repeat";}
	$repeat = $tmp;
    } elsif(substr($occurs,0,2) eq 'ZW' and $occurs =~ /^Z(.+),(\d+),(\d*)/ ) {
	my($word, $c1, $c2) = ($1,$2,$3);
	my $nbits = unpack "%8b*", pack("C", $c2);
	$tmp = int(($repeat +$nbits-1) / $nbits);
	if($tmp * $nbits != $repeat) { $recurr="Z$word,$c1,$c2:$tmp:$repeat";} 
	$repeat = $tmp;
    }
    return($repeat, $recurr);
}
#=====================================================================================================
#
# post a edit form
#
sub edit {
    my ($who, $view, $month, $day, $year, $hour, $min, $stmp, $name, $out, $summary, $mme, $pauthor,$rsvp,$cat, $spkr,
	 $reminder, $emn, $mn, $ekind, $todayc, $command, $tag, $i,$j,$attendants,$room,$warnRepeat, $exception, $oedate,
	 $date, $edate, $shr, $smn, $ehr, $ehn, $occurs, $repeat, $kind, $description, $JwarnInsert, $recurr, $oattendants,
	 $mailu, $maili, $maily, $flashi, $flashu, $flashy, $popupi, $popupu, $popupy, $ctp, $ctm, $acc, $dec, $ctd, $ctds,
	 $chime, $chimeu, $chimei, $chimey, $author, $rurl, $privacy, $eevent, $href, $mg, $ls, $JwarnGrp, $warnGrp,$theCs,
	 $mail, $popup, $flash, $utmp, $imgp, $detail, $forward, $done, $bdate, $theFG, $theBG, $priority, $imkey, $seq,
 	 $xtra, $kwd, $cbg, $eme, $forever, $r1, $warnOld,$catlist,$cancelbtn,$enddate,$cp);
    my ($upload, $kkind, $label0,$label1, $title, $ckcode,$cpath)=("","", "","","","",""); $cp=0;
    my ($nmrb,$nmre, $nprb,$npre, $nbrb,$nbre, $ncrb,$ncre)=("","","","","","","","");
    
     $who = $::calinfo{'w'};
     $command = (@_)[0];

     $view = $::calinfo{'v'};
     $ls = $::calinfo{'ls'};
     $month= $::calinfo{'month'};
     $day  = $::calinfo{'day'};
     $year = $::calinfo{'year'};
     $hour = $::calinfo{'hour'};
     $min  = $::calinfo{'min'};
     $name = $::calinfo{'name'};
     if(defined $::calinfo{'lrem'}) { $reminder= $::calinfo{'lrem'}; }
     elsif(defined $::calinfo{'drem'}) { $reminder= $::calinfo{'drem'}; $reminder=~ s/\-//g; }
     else { $reminder="rf:n:5:m,rm:n:5:m,rp:n:5:m,rc:n:5:m";}
     $name = $who unless $name;
     $kind = $::calinfo{'k'} or $kind = 0;
     $rsvp = 0;
     $acc = $dec = $cbg= "";
     $cat = $spkr= $kwd = "";
     $ctd=$ctds=$imkey=$xtra="";
     $exception=""; $recurr=""; $oedate=""; $oattendants="";
     $author= $::d{'ceditor'};
     $mg=$privacy="";
     $priority="";
     $rurl = ""; $occurs=""; $forever=""; $r1=0;
     $forward = "";
     $done="";
     $enddate=$bdate="";
     $attendants="";
     $room="";
     $description="";
     $detail="";
     $imgp = "";
     $theFG = $theBG = "";
     $ctp=$ctm="";
     $todayc = printDate( $::now{'month'}, $::now{'day'}, $::now{'year'});
     $summary = oneDaySummary($month, $day, $year, $todayc, $webcalConfig::fontsize{'summary'}, 0);
     $tag = 0;
     $date = printDate($month, $day, $year);
     $eevent=0;
     $mme = 0;
     $warnRepeat="";
     $JwarnInsert="";
     $JwarnGrp="";
     $warnGrp="";
     $seq = $theCs="";
     if($::calinfo{'eme'}) {$eme = $::calinfo{'eme'};}

     # for meeting events, display the complete event if remote user
     # is a participant of the meeting.
     if( $command eq 'edit' and  ($::d{'authResult'} | $::d{'ispublic'}) != 4) {
       my ($tattendants, $tauthor, $mkey);
       # find the relevent event
       $tag=$::calinfo{'t'};
       for $href (@::caldata) {
	 if( $href->{'key'} == $tag) {
	   if(1) {
	     if($href->{'mme'}) {$mme =  $href->{'mme'};} else {$mme ="";}
	     if($href->{'mkey'}) {$mkey = $href->{'mkey'};} else {$mkey = "";}
	     $mkey =~ s/_eMe_\d+//g;   if(not $::calinfo{'eme'}) {$eme =  $mkey;}
	     if($href->{'attendants'}) {$tattendants = $href->{'attendants'};} else {$tattendants="";}
	     $tattendants =~ s/[,; ]+/:/g;
	     $tattendants =~ s/:$//g;
	     $tattendants = expandMeetingGroups($mkey, $tattendants);
	     if(ismember($::d{'remote_user'}, $tattendants) or $::d{'remote_user'} eq $mkey) { $::d{'authResult'} = 3;}
	   }
	   last;
	 }
       }
    }

     # Display the content only when permission is OK
     my ($gprivacy, $junk) = getPrivacy(0);
#     if($command eq 'edit' and ($gprivacy > 0 or $::d{'ispublic'} or $webcalConfig::r{'limitGet'} eq 0)) {
     if($command eq 'edit' ) {
	 # find the relevent event
	 $tag=$::calinfo{'t'};
	 for $href (@::caldata) {
	     if( $href->{'key'} == $tag) {
		 my ($start,$duration, $eprivacy, $tmp); $duration=0;
		 if($gprivacy > 3) { $eprivacy = 3;}	#authorized editor or self
		 else {
		     if($href->{'privacy'}) {$tmp = $href->{'privacy'};  $eprivacy = $::privacyTable{$tmp} - 1;}
		     else {$eprivacy = $gprivacy;}
		 }
		 $eevent = $eprivacy;
		 $author=" ";
		 #=======================
		 my ($mkey, $invitee);
		 $mkey = $href->{'mkey'} || ""; $mkey =~ s/_eMe_\d+//g;  if(not $::calinfo{'eme'}) {$eme = $mkey;}
		 if($eevent < 3 and $href->{'mkey'} and $href->{'attendants'}) {
		     if(isre($::d{'remote_user'}, $mkey, 'editors')) { $eevent = 3;}
		     elsif( $href->{'mme'}) {
			 $invitee = $href->{'attendants'};
			 $invitee = expandMeetingGroups($mkey,$invitee);
			 if(ismember($::d{'remote_user'}, $invitee)) { $eevent = 3;}
		     }
		 }
		 #=======================
		 if($href->{'pnd'} and not isre($::d{'remote_user'}, $who, 'editors')) { $eevent = 0;}
		 if($eevent > 1) { 
		     $description = $href->{'what'} if (defined $href->{'what'}); 
		     if(defined $href->{'end'}) {$enddate = $href->{'end'};}
		     if(defined $href->{'bdate'}) {$bdate = $href->{'bdate'};}
		     if(defined $href->{'start'}) { $start = $href->{'start'};}
		     if(defined $href->{'privacy'}) {$privacy = $href->{'privacy'}; }
		     if($href->{'author'}) {$author = $href->{'author'};} else {$author="";}
		     if($::d{'ispublic'} and ismember($::d{'remote_user'}, $author)) { $::d{'authResult'} = 4; $eevent=3;}
		 } 
		 if($eevent > 2) {
		     if(defined  $href->{'detail'}) {$detail = $href->{'detail'}; }
		     $edate = $href->{'date'};
		     $oedate="<input type=hidden name=oedate value=\"$edate\">";
		     if($href->{'seq'}) { my $t=$href->{'seq'};$seq = "<input type=hidden name=seq value=\"$t\">";} 
		     if($href->{'mkey'}) { my $t=$href->{'mkey'};  $imkey = "<input type=hidden name=imkey value=\"$t\">";}
		     if(defined $href->{'rsvp'}) {$rsvp = $href->{'rsvp'};} 
		     if(defined $href->{'acc'}) {$acc ="<input type=hidden name=acc value=\"$href->{'acc'}\">";}
		     if(defined $href->{'dec'}) {$dec ="<input type=hidden name=dec value=\"$href->{'dec'}\">";}
		     if(defined $href->{'cat'}) {$cat = $href->{'cat'};}
		     if(defined $href->{'kwd'}) {$kwd = $href->{'kwd'};}
		     if(defined $href->{'cbg'}) {$cbg = $href->{'cbg'};}
		     if(defined $href->{'spkr'}) {$spkr = $href->{'spkr'};}
		     if(defined $href->{'url'}) {$rurl = $href->{'url'};}
		     if(defined $href->{'fg'}){$theFG = $href->{'fg'};}
		     if(defined $href->{'bg'}){$theBG = $href->{'bg'};}
		     if(defined $href->{'ctp'}){$ctp = $href->{'ctp'};}
		     if(defined $href->{'ctm'}){$ctm = $href->{'ctm'};}
		     if(defined $href->{'cs'}){$theCs = $href->{'cs'};}
		     if(defined $href->{'cp'}) { $cp = $href->{'cp'};}
		     if($href->{'duration'}) {$duration = $href->{'duration'};} else {$duration=0;}
		     if(exists $href->{'ctd'}) { $ctd = "<input type=hidden name=octd value=\"$href->{'ctd'}\">";}
		     if(exists $href->{'ctds'}) { $ctds = "<input type=hidden name=octds value=\"$href->{'ctds'}\">";}
		     if(defined $href->{'occurs'}) {$occurs = $href->{'occurs'};}
		     if(defined $href->{'repeat'}) { 
			 $repeat = $href->{'repeat'}; if(!$repeat) { $repeat = 0;} 
			 if($repeat and $repeat>1) {
			     my $udate = to_native_date($edate);
			     $tmp=$::phr{'warnModify'};
			     $tmp =~ s/\\//g; $tmp =~ s/\'/\\\'/g; 
			     $tmp =~ s/\n/\\n/g;
			     $tmp .= " $udate";
			     $JwarnInsert="function vf(){var zd=window.document.webcal.sdate.value; if(zd == \'$udate\') { return true;} else {  return confirm(\'$tmp\');}}";
			     $warnRepeat="onClick=\"return vf()\"";
			 }
		     } else {$repeat = 0;}
		     #===================================================================
		     {
			 my ($i, $tmp,$smp);
			 for $i (0..5) { 
			     $tmp="X$i"; if($href->{$tmp}) {
				 $smp=$href->{$tmp}; $smp=~ s/\"/&quot;/g; #"
				 $xtra .= "<input type=hidden name=\"X$i\" value=\"$smp\">";
			     }
			 }
		     }
		     #===================================================================
                     if(defined $href->{'pri'}) {$priority = $href->{'pri'};}
		     ($repeat, $recurr)= &bp_repeat_occur($repeat,$occurs);
		     $recurr = "<input type=hidden name=orecurr value=\"$recurr\">";

		     if(defined $href->{'exception'}) {
			 my $aref =$href->{'exception'};
			 $tmp = '[' . join(',', @$aref) . ']';
			 $exception="<input type=hidden name=oexception value=\"$occurs:$repeat:$tmp\">";
		     }
		     $kind =  $href->{'kind'};
		     if(defined $href->{'forward'}) {$forward = $href->{'forward'};}
		     if(defined $href->{'done'}) {$done = $href->{'done'};}
		     if(defined $href->{'rem'}) { $reminder= $href->{'rem'};} else {$reminder="rf:n:5:m,rm:n:5:m,rp:n:5:m,rc:n:5:m";}
		     if($href->{'attendants'}) {
			 $attendants=$href->{'attendants'};
			 $oattendants = "<input type=hidden name=oattendants value=\"$attendants\">";
		     }
		     if(exists $href->{'mme'}) { $mme = $href->{'mme'};}
		     if(exists $href->{'room'}) { $room = $href->{'room'};}
		     if($href->{'r1'}){$r1 = $href->{'r1'}; }
		 }
		 if($eevent) {
		     ($shr,$smn)=split(/:/,$start || ":");
		     if($shr ne "" and $smn ne "") {
		       $utmp=$smn+$duration;
		       $ehr=$shr + int($utmp/60);
		       $emn = $utmp % 60;
		     }else {$ehr=$emn = 0;}
		 }
		 last;
	     }
	 }
       }
     if(! $eevent) { $command = 'nevent';}
     if($kind == 3 and $::calinfo{'wa'}) {
	 my $tmp =$::phr{'WarnInvitee'};
	 $tmp =~ s/\\//g; $tmp =~ s/\'/\\\'/g;  $tmp =~ s/\n/\\n/g;
	 $JwarnGrp="function wg() {var a= window.document.webcal.mattendants.value; if(a != '') { return confirm(\'$tmp\\\n\\\n      ' + a);} else return true;}";
	 $warnGrp = "onClick=\"return wg()\"";
     }
     if($command eq 'nevent') {
       if($::calinfo{'tarf'}) { $ forward = "y";}
       my ($dei, $tmp); if(defined $::calinfo{'dei'}) { $dei=$::calinfo{'dei'} || 0;} else {$dei=60;}
       $shr=$hour; $smn=$min;  $tmp = $min + $dei; $ehr=$shr+ int($tmp/60); $emn=$tmp%60;
       if($ehr > 24) { $ehr=24; $emn=0;}
       if($kind == 4) { $shr=$ehr="05"; $smn= $emn= "00";}
       $repeat = 1; $occurs = 'OneTime';
       $mme = 1;
       if(defined $::calinfo{'mg'} and $::calinfo{'mg'} ne ""){$attendants="$::calinfo{'mg'}"; }
       if( $::calinfo{'imrem'} or $::calinfo{'imatt'} or $::calinfo{'imgp'}) {# invoked from the conflict table
	 if(defined $::calinfo{'imatt'}) {$attendants=$::calinfo{'imatt'};}
	 if(defined $::calinfo{'iroom'}) {$room=$::calinfo{'iroom'};}
	 if(defined $::calinfo{'irsvp'}) {$rsvp=$::calinfo{'irsvp'};}
	 if(defined $::calinfo{'imme'}) {$mme=$::calinfo{'imme'};} 
	 if(defined $::calinfo{'icat'}) {$cat=$::calinfo{'icat'};}
	 if(defined $::calinfo{'ikwd'}) {$kwd=$::calinfo{'ikwd'};}
	 if(defined $::calinfo{'ispkr'}) {$spkr=$::calinfo{'ispkr'};}
	 if(defined $::calinfo{'ictp'}) {$ctp=$::calinfo{'ictp'};}
	 if(defined $::calinfo{'ictm'}) {$ctm=$::calinfo{'ictm'};}
         if(defined $::calinfo{'iacc'}) {$acc ="<input type=hidden name=acc value=\"$::calinfo{'iacc'}\">";}
         if(defined $::calinfo{'idec'}) {$dec ="<input type=hidden name=dec value=\"$::calinfo{'idec'}\">";}
	 if(defined $::calinfo{'ieme'}) {$eme=$::calinfo{'ieme'};}
	 if(defined $::calinfo{'imrem'}) {$reminder = $::calinfo{'imrem'};}
	 if(defined $::calinfo{'imgp'}) { $imgp = $::calinfo{'imgp'};}
	 if(defined $::calinfo{'author'}) { $author=$::calinfo{'author'};} else {$author="";}
	 $author =~ s/:/ /g;
	 if(defined $::calinfo{'rurl'}) { $rurl = $::calinfo{'rurl'};}
	 if(defined $::calinfo{'occurs'}) { $occurs=$::calinfo{'occurs'};}
	 if(defined $::calinfo{'repeat'}) {$repeat=$::calinfo{'repeat'};}
	 if(defined $::calinfo{'eprivacy'}) {$privacy=$::calinfo{'eprivacy'}; }
	 if(defined $::calinfo{'desc'}) { $description=$::calinfo{'desc'};}
	 $description =~ s/\|/\n/g;
	 $description =~ s/_/ /g;
	 if(exists $::calinfo{'detail'}) {$detail=$::calinfo{'detail'};}
	 if(exists $::calinfo{'forward'}) {$forward=$::calinfo{'forward'};}
	 if(defined $::calinfo{'done'}) {$done=$::calinfo{'done'};}
	 $detail =~ s/\|/\n/g;
	 $detail =~ s/_/ /g;
	 if(exists $::calinfo{'fgclr'}) { $theFG = $::calinfo{'fgclr'};}
	 if(exists $::calinfo{'bgclr'}) { $theBG = $::calinfo{'bgclr'};}
	 if(exists $::calinfo{'cs'}) { $theCs= $::calinfo{'cs'};}
	 if($::calinfo{'ir1'}) {$r1= $::calinfo{'ir1'};}
     }
       if(! $theCs) {
	   my $tmp = "css$kind";
	   if($::calinfo{$tmp}) { $theCs = $::calinfo{$tmp};}
       } 
       my ($f1,$f2,$f3,$f4,$b1,$b2,$b3,$b4,$css1,$css2,$css3,$css4,$unused);
       if(exists $::calinfo{'dafg'}) {$f1 = $::calinfo{'dafg'};} else {$f1="";}
       if(exists $::calinfo{'dabg'}) {$b1 = $::calinfo{'dabg'};} else {$b1="";}
       if(exists $::calinfo{'dtfg'}) {$f2 = $::calinfo{'dtfg'};} else {$f2="";}
       if(exists $::calinfo{'dtbg'}) {$b2 = $::calinfo{'dtbg'};} else {$b2="";}
       if(exists $::calinfo{'dmfg'}) {$f3 = $::calinfo{'dmfg'};} else {$f3="";}
       if(exists $::calinfo{'dmbg'}) {$b3 = $::calinfo{'dmbg'};} else {$b3="";}
       if(exists $::calinfo{'dsfg'}) {$f4 = $::calinfo{'dsfg'};} else {$f4="";}
       if(exists $::calinfo{'dsbg'}) {$b4 = $::calinfo{'dsbg'};} else {$b4="";}
       if($theFG eq "") {
	   if($kind == 1)    { $theFG=$f1;}
	   elsif($kind == 2) { $theFG=$f2;}
	   elsif($kind == 3) { $theFG=$f3;}
	   elsif($kind == 4) { $theFG=$f4;}
       }
       if($theBG eq "") {
	   if($kind == 1)    { $theBG = $b1;}
	   elsif($kind == 2) { $theBG = $b2;}
	   elsif($kind == 3) { $theBG = $b3;}
	   elsif($kind == 4) { $theBG = $b4;}
       }
       ($css1,$css2,$css3,$css4)=&default_css_setup();
       #
       my @elist =(1,$::phr{'Appointment'}, 2, $::phr{'ToDo'}, 3, $::phr{'Meeting'}, 4, $::phr{'Special'});
       $label0 = "$::phr{'Event'}:";
       $label1= select_value('k', $kind, @elist);  
       $label1=~ s/<select/<select OnChange="resetclrs('$f1','$b1','$f2','$b2','$f3','$b3','$f4','$b4','$css1','$css2','$css3','$css4',$::o{'hourformat'})"/;
       $title = $::phr{'EventEditor'};
   } else {
       $kkind="<input type=hidden name=\"k\" value=$kind>";
       if($kind == 1) { $label1="$::phr{'Appointment'}:"; $title = $::phr{'AppointmentEditor'};}
       elsif($kind == 2) { $label1="$::phr{'ToDo'}:"; $title= $::phr{'ToDoEditor'};}
       elsif($kind == 3) { $label1="$::phr{'Meeting'}:"; $title= $::phr{'MeetingEditor'};}
       else { $label1="$::phr{'Special'}:"; $title= $::phr{'SpecialEditor'}}
       $label0="&nbsp;"; $label1="<span class=\"fmLabel\">$label1</span>";
   }
    if($repeat and $repeat > 729) { $forever = "checked";}

     ($flash,$mail,$popup, $chime)=split(/,/, $reminder);
     (undef, $maily, $maili,$mailu) = split(/:/, $mail);
     (undef, $flashy, $flashi,$flashu) = split(/:/, $flash);
     (undef, $popupy, $popupi,$popupu) = split(/:/, $popup);
     (undef, $chimey, $chimei,$chimeu) = split(/:/, $chime);
     if(!defined $maili or  not $maili) { $maili = 5;}
     if(!defined $flashi or not $flashi) { $flashi = 5;}
     if(!defined $popupi or not $popupi) { $popupi = 5;}
     if(!defined $chimei or not $chimei) { $chimei = 5;}
     if(!defined $mailu) { $mailu = 'm';}
     if(!defined $popupu) { $popupu = 'm';}
     if(!defined $chimeu) { $chimeu = 'm';}
     if(!defined $flashu) { $flashu = 'm';}
     if(!defined $maily) { $maily = 'n';}
     if(!defined $popupy) { $popupy = 'n';}
     if(!defined $chimey) { $chimey = 'n';}
     if(!defined $flashy) { $flashy = 'n';}

     if($forward eq "") { $forward = 'n';}
     if($done eq "") { $done = 'n';}

     if(! $privacy) { $privacy = $::calinfo{'privacy'};}

     if($kind == 2) {
       if($bdate eq "") { $bdate = $date;}
     }
    if(exists $::calinfo{'pri'}) { 
	my $tmp = $::calinfo{'pri'}; 
	$tmp =~ s/\\//g; $tmp=~ s/\'//g;
	$priority=$tmp;
    }
    $catlist = build_catlist($who,'cats', 0, $cat);
    if($::calinfo{'inpopup'}){
	$cancelbtn=<<END;
<input type=button class="fmBtnStSa" value="$::phr{'Cancel'}" onclick="javascript:history.go(-1)">
<input name=inpopup type=hidden value=1>
END
    ;
    } else{
	$cancelbtn=<<END;
<input type=submit name=action class="fmBtnStSa" value="$::phr{'Cancel'}">
END
    ;
    }
    

    # disallow modification of the Author field for public calendars
     if($author eq "") { $author=$::d{'remote_user'};}
     my $authornames=expand_author_name($author);
     $pauthor="<input type=hidden name=author value=\"$author\">&nbsp;<font color=#ff0000>$authornames</font>";
    #&make_style_sheet();
     &headers($::phr{'EventEditor'},"$ckcode $JwarnInsert $JwarnGrp",undef,1,1);
     print "<Form name=webcal action=\"$::o{'cginame'}\" method=POST>$::vmp";
     print "<center>";
     if(!$eme) { $eme= $who;} else { $::calinfo{'eme'} = $eme;}
     my $whol= "<span class=\"fmLabel\">$who<input type=hidden name=\"w\" value=\"$who\"></span>";
     if(not $webcalConfig::r{'disable_cal_menu_in_editor'} and 
	  ($command eq "nevent" or (not $oattendants)) and ($::calinfo{'mg'} or $::calinfo{'clist'}) 
	and ! $::calinfo{'nextnew'}) {
	 my $nwhol = cal_menu_in_editor($command, $who, $eme);
	 if($nwhol) { $whol = $nwhol;}
     } 
    $eme = "<input type=hidden name='eme' value=\"$eme\">"; 
    $title = "<span class=\"fmLabel\">$title</span>";
    if($kind == 1) {  print "<font color=#ff0000><b>$title -- <font color=#009900> $whol </font></b></font>\n";}
    elsif($kind == 2) {  print "<font color=#009900><b>$title -- <font color=#ff0000> $whol</font></b></font>\n";}
    elsif($kind == 3) {  print "<font color=#cc00cc><b>$title -- <font color=#009900> $whol</font></b></font>\n";}
    else {  print "<font color=#0066ff><b>$title -- <font color=#ff0000> $whol</font></b></font>\n";}

    if(($::d{'authResult'} | $::d{'ispublic'}) < 4 or $::d{'validuser'} == 0) {
	print "<br><font color=#999900><b><span class=\"authWarn\">$::phr{'AuthRequired'}!</span></b></font>\n";
     }
     print "</center><hr>\n";
     if(defined $::calinfo{'mg'}) { $mg="<input type=hidden name=mg value=\"$::calinfo{'mg'}\">";} else {$mg="";}

     if($::o{'allowImageUpload'}) {
	 my $iurl="$::o{'cgiupload'}?c=ui&w=$who";
	 $upload = "<a href=\"Javascript:openpopup(\'$iurl\','uls',500,400)\" style=\"color:blue;background-color:#cc00cc\"><font size=1><span class=\"iupload\">$::phr{'IUpload'}</span></font></a><br><br>";
     }
      my $repos = "$::o{'imgdir'}/$::o{'uploadsubdir'}";
      my @list= listImgDirContents($repos,1);
      my ($iadd1, $iadd2, $iadd3) = ("","",""); 
      if (scalar @list) {
	  my $surl="$::o{'cginame'}?c=simage&imgoffset=0&w=$who";
	  $upload .= "<a href=\"Javascript:openpopup(\'$surl&the_form=webcal&the_elt=detail\','imgs',500,600)\" style=\"color:green;background-color:#cccc00\"><font size=1><span class=\"iselect\">$::phr{'UsableImgs'}</span></font></a><br><br>";
	  $iadd1= "<br><a href=\"Javascript:openpopup(\'$surl&the_form=webcal&the_elt=description\','imgs',500,600)\" style=\"color:green;background-color:#cccc00\"><font size=1><span class=\"iselect\">$::phr{'UsableImgs'}</span></font></a>";
	  $iadd2= "<br><a href=\"Javascript:openpopup(\'$surl&the_form=webcal&the_elt=rurl\','imgs',500,600)\"><img src=\"$::o{'imgdirurl'}/doc.gif\" width=20 height=9 border=0></a>";
	  $iadd3= "<a href=\"Javascript:openpopup(\'$surl&the_form=webcal&the_elt=cbg&noappend=1\','imgs',500,600)\"><img src=\"$::o{'imgdirurl'}/ig.gif\" width=11 height=9 border=0></a>";
     }
#=================================
    if($::calinfo{'NMR'}){ $nmrb="<strike><font color=#ccccff>"; $nmre="</font></strike>";}
    if($::calinfo{'NPR'}){ $nprb="<strike><font color=#ccccff>"; $npre="</font></strike>";}
    if($::calinfo{'NFR'}){ $nbrb="<strike><font color=#ccccff>"; $nbre="</font></strike>";}
    if($::calinfo{'NCR'}){ $ncrb="<strike><font color=#ccccff>"; $ncre="</font></strike>";}
#=================================
    if(not $webcalConfig::r{'disable_past_event_warning'}){
	$warnOld="onClick=\"return timetravel(1+$::o{'dateformat'}-1,1+$::o{'hourformat'}-1, $kind)\"";
	if(not $warnRepeat) { $warnRepeat = $warnOld;}
	if(not $warnGrp) { $warnGrp = $warnOld;}
    }

    if($enddate) {$enddate = to_native_date($enddate);}
    my $ronce = input_radio("r1", $r1, @::switchList); $ronce=~ s/class=\"fmRadio\"/class=\"fmRadioS\"/g;

    my @priorityL=("$::phr{'Low'}" ,  "$::phr{'Medium'}", "$::phr{'High'}", "$::phr{'Urgent'}" );
    if( !iselement($priority, @priorityL) ) {unshift @priorityL, $priority;}

    if($::o{'cpath'}) {
	my $tmp = select_value('cp',$cp, (0, $::phr{'No'}, 1, $::phr{'Yes'})); 
	$cpath =<<END;
<font color="#ff6600"><b><span class="fmLabel">&nbsp;&nbsp;&nbsp;&nbsp;$::phr{'CPath'}:</b></font></span> $tmp	
END
;
    }

     if($kind == 1) {	# appointment Editor zzzzzzzzzzzzzzzz
	 my $udate = to_native_date($date);
	 my $submit;
	 if($command eq 'edit') {
	     $submit="<input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'InsertAsNew'}\" $warnOld>
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'Modify'}\" $warnRepeat>";
	     if($repeat and $repeat > 0) {
		 $submit .= "<input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'DeleteThisOne'}\">
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'DeleteForward'}\">
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'DeleteAll'}\">";
	     } else {
		 $submit .= "<input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'Delete'}\">";
	     }
	 } else {
	     $submit = "<input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'Insert'}\" $warnOld>
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'NextNew'}\" $warnOld> $cancelbtn";
	 }

	 print "

$kkind
<input type=hidden name=c value=doedit>
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=t value=$tag>
<input type=hidden name=d value=\"$month/$day/$year/$hour/$min\">
$eme
$seq
$acc
$dec
$mg
$oedate
$exception
$recurr
$oattendants
$ctd
$ctds
$imkey
$xtra
<table border=0 cellspacing=1 cellpadding=0 width=\"$::o{'tw'}%\" class=\"editor\">
<tr><td width=\"8%\" align=right><b><span class=\"fmLabel\">$label0</span></b></td>
  <td width=\"42%\" align=left><font color=#ff0000><b>$label1</b></font></td>
  <td width=\"50%\" colspan=2 valign=bottom bgcolor=#ffeedd class=\"editorEsum\">
     <table border=0 cellpadding=0 cellspacing=0 width=\"100%\" class=\"editor\">
       <tr><td width=\"20%\" class=\"editorRow0\"><b><span class=\"fmLabel\">$::phr{'Time'}</span></b></td><td class=\"editorRow0\" width=\"80%\"><b><span class=\"fmLabel\">$::phr{'What'}</span></b><span class=\"fmLabelS\">&nbsp;($::phr{'CurrentEvents'}&nbsp;<font color=#ff0000>$udate</font>)</span></td></tr></table>
</td>
</tr>
<tr>
  <td align=right><b><span class=\"fmLabel\">$::phr{'Date'}:</span></b></td>
  <td align=left ><input type=text size=20 maxlength=24 name=sdate value=\"$udate\" class=\"fmEntry\" onChange=\"rmED()\">",
  linkSmallCal("webcal.sdate",$who,$month,$year),"</td>
  <td colspan=2 rowspan=7 valign=top bgcolor=#ffeedd class=\"editorEsum\">$summary</td>
</tr>
<tr>
  <td align=right><b><span class=\"fmLabel\">$::phr{'Start'}:</span></b></td>
  <td align=left>",select_time("s",$shr,$smn);
	 print "
 </td>
</tr>
<tr>
 <td align=right><b><span class=\"fmLabel\">$::phr{'End'}:</span></b></td>
 <td align=left>",select_time("e",$ehr,$emn);

	 print "
 </td>
</tr>";

   my $oltmp; if(defined $::calinfo{'ol'}) { $oltmp = $::calinfo{'ol'};} else {$oltmp = 0;} # 0 allow, 1 disallow

   if($oltmp < 2) {	 
   print "<tr><td>&nbsp;</td><td>&nbsp;<font color=#cd3b3b size=-1><b><span class=\"fmLabelS\">$::phr{'AllowOverlap'}:</span>";
   my $trmp= input_radio("aol",$oltmp, @::boolList);
   $trmp =~ s/class=\"fmRadio\"/class=\"fmRadioS\"/g;
   print  $trmp, "</b></font>";
   print "</td></tr>";
   } else { print "<tr><td><font size=1><br></font></td></tr><input type=hidden name=\"aol\" value=2>";}
   print <<END;
<tr>
 <td align=right><font color="#ff0000"><b><span class="fmLabel">$::phr{'What'}:</span></b></font>$iadd1</td>
 <td align=left>
   <textarea cols=30 rows=2 wrap=virtual name=description  class="fmText">$description</textarea>
 </td>
</tr>
<tr>
 <td align=right>$upload<b><span class="fmLabel">$::phr{'Details'}:</span><br><a href="#dd"><img src="$::o{'imgdirurl'}/lower.gif" width=25 height=16 border=0></a>&nbsp;&nbsp;&nbsp;</b></td>
 <td align=left>
<textarea cols=30 rows=3 wrap=virtual name=detail class="fmText">$detail</textarea>
 </td>
</tr>
<tr>
<td width="8%" align=right><font color="#ff0000"><b><span class="fmLabel">$::phr{'Location'}:</span></b></font></td>
<td align=left><input type=text size=24 maxlength=60 name=sroom value="$room" class="fmEntry"></td>
</tr>
<tr>
<td width="8%" align=right><b><span class="fmLabel">$::phr{'Category'}:</span></b></td>
<td align=left nowrap><input type=text size=12 maxlength=60 name=cat value="$cat" class="fmEntry">$catlist</td>
<td colspan=2 rowspan=2 align="center" class="editsubmit">$submit</td>
</tr>
<tr>
 <td noWrap align=right><font color="#009900"><b><span class="fmLabel">$::phr{'Priority'}:</span></b></font></td>
 <td align=left><input type=text size=8 maxlength=99 name=pri class="fmEntry" value="$priority">
END
    ;
         print select_optionV("ignore", $priority,
"OnChange=\"Javascript:var z=window.document.webcal;z.pri.value=z.ignore.options[z.ignore.selectedIndex].value;\"",
                              @priorityL);

	 print $cpath;

	 print <<END;
</td>
</tr>
<tr>
<td align=right class="editorClrs">
<font color=blue><b><input type=Button onclick="openpopup('$::o{'cginame'}?c=showclr&w=$who','clrs',500,480)" value="$::phr{'Colors'}:" class="fmBtn"></b></font>
<br>
END
    ;
      print user_defined_color_pairs(1);

      print "</td><td class=\"editorClrs\"><table border=0 cellspacing=0 cellpadding=0 width=\"100%\" class=\"editorClrs\"><tr><td bgcolor=#ccccff class=\"editorClrs\">",
	  "<span class=\"fmLabel\">$::phr{'Fg'}:&nbsp;</span>",
	 "<input type=text size=8 value=\"$theFG\" name=fgclr class=\"fmEntry\">",
	 select_valueV("pfgclr",$theFG, "onChange=\"javascript:psetfg()\"", ("?????", $theFG, @::sixteenColors)),
	 "<br>",
	 "<span class=\"fmLabel\">$::phr{'Bg'}:&nbsp;</span>",
	 "<input type=text size=8 value=\"$theBG\" name=bgclr class=\"fmEntry\">",
	 select_valueV("pbgclr",$theBG, "onChange=\"javascript:psetbg()\"", ("?????", $theBG, @::sixteenColors));
	 my ($cst, $sid)= user_defined_css('css', $theCs, 1);
	 my $eurl="$::o{'cgicss'}?c=post&w=$who";    
	 if($cst) {
	     print  <<END;
</td><td class="editorClrs">&nbsp;</td><td bgcolor="#ffcccc" class="editorFont">&nbsp;<a href="javascript:openpopup('$eurl','ecs',680,600)" onMouseOver="showtip(event,'$sid');" 
onMouseOut="hidetip('$sid');"><span class=\"fmLabel\">$::phr{'Font'}:</span></a><br>&nbsp; $cst
END
    ;
	 }
	 print "</td></tr></table>";
	 
	 print "	 
 </td>
 <td class=\"editorCT\" bgcolor=#ccffcc nowrap colspan=2 valign=bottom align=right><span class=\"fmLabel\">$::phr{'ContactP'}:</span><input type=text size=20 maxlength=60 value=\"$ctp\" name=ctp class=\"fmEntry\">&nbsp;&nbsp;<br><span class=\"fmLabel\">$::phr{'ContactE'}:</span><input type=text size=20 maxlength=60 value=\"$ctm\" name=ctm class=\"fmEntry\">&nbsp;&nbsp;</td>
</tr>
<tr>
 <td class=\"editorP\" align=right><font color=#ff0000><b><span class=\"fmLabel\">$::phr{'Privacy'}:</span></b></font></td>
 <td class=\"editorP\" align=left>",select_value("eprivacy",$privacy,@::privacyList),"</td>
 <td class=\"editorK\" colspan=2 align=right><span class=\"fmLabel\">$::phr{'Keyword'}:</span><input type=text size=20 maxlength=128 name=kwd value=\"$kwd\" class=\"fmEntry\">&nbsp;&nbsp;</td>
</tr>";
#---07/22/01
   &printAttPart($who, $attendants,$imgp,$mme, $rsvp, "#ff0000");
#---07/22/01
	 print "
<tr>
  <td colspan=4><hr></td>
</tr>
<tr>
 <td align=right></td>
 <td align=left><font color=#ff0000><b><span class=\"fmLabel\">$::phr{'Frequency'}</span></b></font></td>
 <td><br></td>
 <td align=left><font color=#ff0000><b><span class=\"fmLabel\">$::phr{'Reminders'}</span></b></font></td>
</tr>
<tr>";
	my $cfreq="$::o{'cginame'}?c=cfreq&w=$who&ooc=";
	print "
<td align=right><b><span class=\"fmLabel\">$::phr{'Occurs'}:</span></b><br><a href=\"javascript:cfreq('$cfreq')\"><font color=blue size=1><span class=\"fmLabelS\">$::phr{'More'}&nbsp;&nbsp;</span></font></a></td>
<td align=left nowrap>";
	 my @freq16=customized_freq($occurs); my $hid_oc; if($freq16[0]=~/^Z/){$hid_oc=$freq16[0];}else{$hid_oc="";}
	 my $fq = select_value("occurs",$occurs,(@::occurrenceList, @freq16));
	 $fq =~ s/<select/<select onChange=\"pfreq('$cfreq')\"/;
	 print $fq, "<input type=\"hidden\" name=\"hidden_occurs\" value=\"$hid_oc\">", "</td>";

	 print "
<td align=right><b><span class=\"fmLabel\">$nmrb$::phr{'Mail'}$nmre</span></b></td>
<td noWrap align=left>";
	 print input_radio("rmail",$maily,@::nyList);
	 print "<input type=text size=4 maxlength=36 name=rmailv value=\"$maili\" class=\"fmEntry\">";
	 print select_value("rmailu",$mailu,@::unitmList),"</td></tr>";

	 print "
<tr>
 <td align=right><b><span class=\"fmLabel\">$::phr{'For'}:</span></b></td>
 <td align=left nowrap>
<input type=text size=4 maxlength=12 name=repeat value=\"$repeat\" 
class=\"fmEntry\" onChange=\"rmED()\"><span class=\"fmLabel\">$::phr{'times'}</span>
 <font color=blue><span class=\"fmLabel\">$::phr{'orIndefinitely'}</span></font><input type=checkbox name=rforever value=1 $forever  class=\"fmRadio\" onChange=\"resetED()\">
 </td>
 <td align=right><b><span class=\"fmLabel\">$nprb$::phr{'Popup'}$npre</span></b></td>
 <td noWrap align=left>";
	 print input_radio("rpopup",$popupy,@::nyList);
	 print "<input type=text size=4 maxlength=36 name=rpopupv value=\"$popupi\" class=\"fmEntry\">";
	 print select_value("rpopupu",$popupu,@::unitList),"</td></tr>";

	 print "<tr><td align=right><b><span class=\"fmLabel\">&nbsp;</span></b></td>
<td nowrap><font color=#009900><span class=\"fmLabel\">$::phr{'orUntilDate'}</span></font>
<input name=enddate type=text size=10 class=\"fmEntry\" value=\"$enddate\">",
linkSmallCal("webcal.enddate",$who,$month,$year),
"<br><font size=2 color=#f03060><span class=\"fmLabel\">$::phr{'wcf'}</span></font></td>
  <td align=right><b><span class=\"fmLabel\">$nbrb$::phr{'Blink'}$nbre</span></b></td>
  <td noWrap align=left>";
	 print input_radio("rflash",$flashy,@::nyList);
	 print "<input type=text size=4 maxlength=36 name=rflashv value=\"$flashi\" class=\"fmEntry\">";
	 print select_value("rflashu",$flashu,@::unitList),"</td></tr>";

	 print "<tr><td align=right><b><span class=\"fmLabel\">URL:</span></b>$iadd2</td>
<td align=left>
<input type=text size=30 maxlength=124 name=rurl value=\"$rurl\" class=\"fmEntry\">
</td>
  <td align=right><b><span class=\"fmLabel\">$ncrb$::phr{'Chime'}$ncre</span></b></td>
  <td noWrap align=left>";
	 print input_radio("rchime",$chimey,@::nyList);
	 print "<input type=text size=4 maxlength=36 name=rchimev value=\"$chimei\" class=\"fmEntry\">";
	 print select_value("rchimeu",$chimeu,@::unitList),"</td></tr>";

	 print "<tr><td align=right><b><span class=\"fmLabel\">$::phr{'Author'}:</span></b></td>
<td align=left><span class=\"fmLabel\">$pauthor</span></td>
<td class=\"editorRmnd1\" colspan=2 nowrap bgcolor=#ccffcc> <font size=2 color=red><span class=\"fmLabelS\">$::phr{'remindOnce'}:
<b>$ronce</b></span></font></td></tr>
<tr>
  <td colspan=4><hr></td>
</tr>
";
	 $submit =~ s/fmBtnStSa/fmBtnSt/g;
	 print "
<tr>
<td colspan=4 align=center>
<a href=\"#uu\"><img src=\"$::o{'imgdirurl'}/upper.gif\" width=25 height=16 border=0></a>&nbsp;
$submit
</td></tr></table>
";
         print "<a name=dd></a>\n";
     } elsif($kind == 2) {	# to do list editor
	 my ($udate1, $udate2, $sk);
	 $udate1 = to_native_date($bdate);
	 $udate2 = to_native_date($date);
	 if(defined $::calinfo{'sk'}) {$sk = "<input type=hidden name=sk value=1>";} else {$sk ="";}
	 my $submit;
	 if($command eq 'edit') {
	     $submit = "<input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'InsertAsNew'}\" $warnOld>
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'Modify'}\" $warnRepeat>";
	     if($repeat and $repeat > 0) { 
		 $submit .= "
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'DeleteThisOne'}\">
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'DeleteForward'}\">
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'DeleteAll'}\">";
	     } else  { 
		 $submit .= "<input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'Delete'}\">";
	     }
	     $submit .= "$cancelbtn";
	 } else { 
	     $submit = "<input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'Insert'}\" $warnOld>
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'NextNew'}\" $warnOld>
$cancelbtn
";
	 }

	 print "

$kkind
<input type=hidden name=c value=\"doedit\">
<input type=hidden name=t value=\"$tag\">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value=\"$month/$day/$year/$hour/$min\">
$eme
$seq
$acc
$dec
$mg
$sk
$oedate
$exception
$recurr
$oattendants
$ctd
$ctds
$imkey
$xtra
<table border=0 cellspacing=2 cellpadding=0 width=\"$::o{'tw'}%\" class=\"editor\">
<tr>
 <td width=\"10%\" align=right><b><span class=\"fmLabel\">$label0</span></b></td>
 <td width=\"42%\" align=left><font color=#009900><b>$label1</b></font></td>
 <td colspan=2 width=\"50%\" valign=bottom bgcolor=#ffeedd class=\"editorEsum\">
     <table border=0 cellpadding=0 cellspacing=0 width=\"100%\" class=\"editor\">
       <tr><td class=\"editorRow0\" width=\"20%\"><b><span class=\"fmLabel\">$::phr{'Time'}</span></b></td><td class=\"editorRow0\" width=\"80%\"><b><span class=\"fmLabel\">$::phr{'What'}</span></b><span class=\"fmLabelS\">&nbsp;($::phr{'CurrentEvents'} <font color=#ff0000>$udate1</font>)</span></td></tr></table>
 </td>
</tr>
<tr>
 <td noWrap align=right><b><span class=\"fmLabel\">$::phr{'StartDate'}:</span></b></td>
 <td align=left><input type=text size=20 maxlength=24 name=bdate value=\"$udate1\" class=\"fmEntry\">",
  linkSmallCal("webcal.bdate",$who,$month,$year),"</td>
 <td colspan=2 rowspan=6 valign=top bgcolor=#ffeedd class=\"editorEsum\">$summary<br></td>
</tr>
<tr>
 <td noWrap align=right><b><span class=\"fmLabel\">$::phr{'DueDate'}:</span></b></td>
 <td align=left><input type=text size=20 maxlength=24 name=sdate value=\"$udate2\" class=\"fmEntry\" onChange=\"rmED()\">",
  linkSmallCal("webcal.sdate",$who,$month,$year),"</td>
</tr>
<tr>
 <td noWrap align=right><b><span class=\"fmLabel\">$::phr{'DueTime'}:</span></b></td>
 <td align=left>",select_time("s",$ehr,$emn);
	 print "
 </td>
</tr>
<tr>
 <td align=right><font color=#009900><b><span class=\"fmLabel\">$::phr{'What'}:</span></b></font>$iadd1</td>
 <td align=left>
   <textarea cols=30 rows=2 wrap=virtual name=description class=\"fmText\">$description</textarea>
 </td>
</tr>
<tr>
 <td align=right>$upload<b><span class=\"fmLabel\">$::phr{'Details'}:<br></span><a href=\"#dd\"><img src=\"$::o{'imgdirurl'}/lower.gif\" width=25 height=16 border=0></a>&nbsp;&nbsp;&nbsp;</b></td>
 <td align=left><b>
   <textarea cols=30 rows=3 wrap=virtual name=detail class=\"fmText\">$detail</textarea>
 </td>
</tr>
<tr>
<td width=\"8%\" align=right><b><span class=\"fmLabel\">$::phr{'Location'}:</span></b></td>
<td align=left><input type=text size=24 maxlength=60 name=sroom value=\"$room\" class=\"fmEntry\"></td>
</tr>
<tr>
<td width=\"8%\" align=right><b><span class=\"fmLabel\">$::phr{'Category'}:</span></b></td>
<td align=left><input type=text size=12 maxlength=60 name=cat  class=\"fmEntry\" value=\"$cat\">$catlist</td>
<td colspan=2 rowspan=2 align=\"center\" class=\"editsubmit\">$submit</td>
</tr>
<tr>
 <td noWrap align=right><font color=#009900><b><span class=\"fmLabel\">$::phr{'Priority'}:</span></b></font></td>
 <td align=left><input type=text size=8 maxlength=99 name=pri class=\"fmEntry\" value=\"$priority\">&nbsp;";

         print select_optionV("ignore", $priority,
"OnChange=\"Javascript:var z=window.document.webcal;z.pri.value=z.ignore.options[z.ignore.selectedIndex].value;\"",
                              @priorityL);
	 print $cpath;

         print "
</td>
</tr>
<tr>
<td align=right class=\"editorClrs\">
<font color=blue><b><input type=Button  class=\"fmBtn\" onclick=\"openpopup('$::o{'cginame'}?c=showclr&w=$who','clrs',500,480)\" value=\"$::phr{'Colors'}:\"></b></font>
<br>";
	 
      print user_defined_color_pairs(2);

      print "</td><td class=\"editorClrs\"><table border=0 cellspacing=0 cellpadding=0 width=\"100%\" class=\"editorClrs\"><tr><td bgcolor=#ccccff class=\"editorClrs\">",
	  "<span class=\"fmLabel\">$::phr{'Fg'}:</span>",
	 "&nbsp;<input type=text size=8 value=\"$theFG\" name=fgclr class=\"fmEntry\">",
	 select_valueV("pfgclr",$theFG, "onChange=javascript:psetfg()", ("?????", $theFG, @::sixteenColors)),
	 "<br>",
	 "<span class=\"fmLabel\">$::phr{'Bg'}:</span>",
	 "&nbsp;<input type=text size=8 value=\"$theBG\" name=bgclr class=\"fmEntry\">",
	 select_valueV("pbgclr",$theBG, "onChange=javascript:psetbg()", ("?????", $theBG, @::sixteenColors));
	 my ($cst, $sid)= user_defined_css('css', $theCs,1);
	 my $eurl="$::o{'cgicss'}?c=post&w=$who";    
	 if($cst) {
	     print  <<END;
</td><td class="editorClrs">&nbsp;</td><td bgcolor="#ffcccc" class="editorFont">&nbsp;<a href="javascript:openpopup('$eurl','ecs',680,600)" onMouseOver="showtip(event,'$sid');" 
onMouseOut="hidetip('$sid');"><span class=\"fmLabel\">$::phr{'Font'}:</span></a><br>&nbsp; $cst
END
    ;
	 }
	 print "</td></tr></table>";

	 print "
 </td>
 <td class=\"editorCT\" bgcolor=#ccffcc nowrap colspan=2 valign=bottom align=right><span class=\"fmLabel\">$::phr{'ContactP'}:</span><input type=text size=20  class=\"fmEntry\" value=\"$ctp\" name=ctp>&nbsp;&nbsp;<br><span class=\"fmLabel\">$::phr{'ContactE'}:</span><input type=text size=20 value=\"$ctm\" name=ctm class=\"fmEntry\">&nbsp;&nbsp;</td>
</tr>
<tr>
 <td align=right class=\"editorP\" ><font color=#009900><b><span class=\"fmLabel\">$::phr{'Privacy'}:</span></b></font></td>
 <td align=left class=\"editorP\">",select_value("eprivacy",$privacy,@::privacyList),"</td>
 <td colspan=2 class=\"editorK\" align=right><span class=\"fmLabel\">$::phr{'Keyword'}:</span> <input type=text size=20 maxlength=128 name=kwd value=\"$kwd\" class=\"fmEntry\">&nbsp;&nbsp;</td>
</tr>";

#----begin insertion ------ added 04/28/2001
	 &printAttPart($who, $attendants,$imgp,$mme, $rsvp, "#009900");
#----end insertion ------ added 04/28/2001


       print "
<tr>
  <td colspan=4><hr></td>
</tr>
<tr>
 <td align=right></td>
 <td align=left><font color=#009900><b><span class=\"fmLabel\">$::phr{'Frequency'}</span></b></font></td>
 <td><br></td>
 <td align=left><font color=#009900><b><span class=\"fmLabel\">$::phr{'Reminders'}</span></b></font></td>
</tr>
<tr>";
	my $cfreq="$::o{'cginame'}?c=cfreq&w=$who&ooc=";
	print "
<td align=right><b><span class=\"fmLabel\">$::phr{'Occurs'}:</span></b><br><a href=\"javascript:cfreq('$cfreq')\"><font color=blue size=1><span class=\"fmLabelS\">$::phr{'More'}&nbsp;&nbsp;</span></font></a></td>
<td align=left nowrap>";
	 my @freq16=customized_freq($occurs); my $hid_oc; if($freq16[0]=~/^Z/){$hid_oc=$freq16[0];}else{$hid_oc="";}
	 my $fq = select_value("occurs",$occurs,(@::occurrenceList, @freq16));
	 $fq =~ s/<select/<select onChange=\"pfreq('$cfreq')\"/;
	 print "$fq", "<input type=\"hidden\" name=\"hidden_occurs\" value=\"$hid_oc\">", "</td>";
	 print "
<td align=right><b><span class=\"fmLabel\">$nmrb$::phr{'Mail'}$nmre</span></b></td>
<td noWrap align=left>";
	 print input_radio("rmail",$maily,@::nyList);
	 print "
 <input type=text size=4 maxlength=36 name=rmailv value=\"$maili\" class=\"fmEntry\"> ";
	 print select_value("rmailu",$mailu,@::unitmList),"</td></tr>";
	 print "
<tr>
 <td align=right><b><span class=\"fmLabel\">$::phr{'For'}:</span></b></td>
 <td align=left nowrap>
   <input type=text size=4 maxlength=12 name=repeat value=\"$repeat\" 
class=\"fmEntry\"  onChange=\"rmED()\"> <span class=\"fmLabel\">$::phr{'times'}</span>
 <font color=blue><span class=\"fmLabel\">$::phr{'orIndefinitely'}</span></font> <input type=checkbox name=rforever value=1 $forever class=\"fmRadio\" onChange=\"resetED()\">
 </td>
 <td noWrap align=right><b><span class=\"fmLabel\">$nprb$::phr{'Popup'}$npre</span></b></td>
 <td noWrap align=left>";
	 print input_radio("rpopup",$popupy,@::nyList);
	 print "
<input type=text size=4 maxlength=36 name=rpopupv value=\"$popupi\" class=\"fmEntry\"> ";
	 print select_value("rpopupu",$popupu,@::unitList),"</td></tr>";

	 print "<tr><td align=right><b><span class=\"fmLabel\">&nbsp;</span></b></td>
<td nowrap><font color=#009900><span class=\"fmLabel\">$::phr{'orUntilDate'}</span></font>
<input name=enddate type=text size=10 class=\"fmEntry\" value=\"$enddate\">",
linkSmallCal("webcal.enddate",$who,$month,$year),
 "<br><font size=2 color=#f03060>$::phr{'wcf'}</font></td>
  <td align=right><b><span class=\"fmLabel\">$nbrb$::phr{'Blink'}$nbre</span></b></td>
  <td noWrap align=left>";
	 print input_radio("rflash",$flashy,@::nyList);
	 print "
<input type=text size=4 maxlength=36 name=rflashv value=\"$flashi\" class=\"fmEntry\"> ";
	 print select_value("rflashu",$flashu,@::unitList),"</td></tr>";


	 print "
<tr><td align=right><b><span class=\"fmLabel\">URL:</span></b>$iadd2</td>
<td align=left>
<input type=text size=30 maxlength=124 name=rurl value=\"$rurl\" class=\"fmEntry\">
</td>
  <td noWrap align=right><b><span class=\"fmLabel\">$ncrb$::phr{'Chime'}$ncre</span></b>
  <td noWrap align=left>";
	 print input_radio("rchime",$chimey,@::nyList);
	 print "
<input type=text size=4 maxlength=36 name=rchimev value=\"$chimei\" class=\"fmEntry\"> ";
	 print select_value("rchimeu",$chimeu,@::unitList),"</td></tr>";

	 print "
<tr><td align=right><b><span class=\"fmLabel\">$::phr{'Author'}:</span></b></td>
<td align=left><span class=\"fmLabel\">$pauthor</span>
</td>
<td class=\"editorRmnd1\" colspan=2 nowrap bgcolor=#ccffcc> <font size=2 color=red><span class=\"fmLabelS\">$::phr{'remindOnce'}:</span>
<b>$ronce</b></font></td></tr>";

	 if($command eq 'nevent' or ($command eq 'edit' and $repeat < 2)) {	 
	     print "<tr><td colspan=4><hr></td></tr>";
	     print "<tr><td colspan=2 align=center><font color=#009900><b><span class=\"fmLabel\">$::phr{'TaskDone'}:</span></b></font>",input_radio("done",$done,@::nyList),"</td>";
	     print "<td colspan=2 align=center><font color=#009900><b><span class=\"fmLabel\">$::phr{'RemindForward'}:</span></b></font>",input_radio("forward",$forward,@::nyList),"</td></tr>";
	     
	 }
	 else {
	     print "<input type=hidden name='forward' value='n'> <input type=hidden name='done' value='n'>";
	 }
	 print "<tr><td colspan=4><hr></td></tr>";

	 $submit =~ s/fmBtnStSa/fmBtnSt/g;
	 
	 print "
<tr>
<td colspan=4 align=center>
<a href=\"#uu\"><img src=\"$::o{'imgdirurl'}/upper.gif\" width=25 height=16 border=0></a>&nbsp;
$submit
</td></tr></table>";
         print "<a name=dd></a>\n";
     } elsif ($kind == 3) {	# meeting editor, $kind = 3;
       my $udate = to_native_date($date);
       my $submit;
       if($command eq 'edit') {
	   $submit= "
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'InsertAsNew'}\" $warnOld>
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'Modify'}\" $warnRepeat>";
	   if($repeat and $repeat > 0) {
	       $submit .= "
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'DeleteThisOne'}\">
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'DeleteForward'}\">
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'DeleteAll'}\">";
	   } else { 
	       $submit .= "<input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'Delete'}\">";
	   }
       } else {
	   $submit = "
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'Insert'}\" $warnGrp>
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'NextNew'}\" $warnGrp>";
       }


       print "
$kkind
<input type=hidden name=c value=\"doedit\">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=t value=\"$tag\">
<input type=hidden name=d value=\"$month/$day/$year/$hour/$min\">
$eme
$seq
$acc
$dec
$mg
$oedate
$exception
$recurr
$oattendants
$imkey
$xtra
<table border=0 cellspacing=2 cellpadding=0 width=\"$::o{'tw'}%\" class=\"editor\">
<tr><td width=\"8%\" align=right><b><span class=\"fmLabel\">$label0</span></b></td>
  <td width=\"42%\" align=left><font color=#cc00cc><b>$label1</b></font></td>
  <td colspan=2 width=\"50%\" valign=bottom bgcolor=#ffeedd class=\"editorEsum\">
     <table border=0 cellpadding=0 cellspacing=0 width=\"100%\" class=\"editor\">
       <tr><td width=\"20%\" class=\"editorRow0\"><b><span class=\"fmLabel\">$::phr{'Time'}</span></b></td><td class=\"editorRow0\" width=\"80%\"><b><span class=\"fmLabel\">$::phr{'What'}</span></b><span class=\"fmLabelS\">&nbsp;($::phr{'CurrentEvents'} <font color=#ff0000>$udate</font>)</span></td></tr></table>
</td>
</tr>
<tr>
  <td width=\"8%\" align=right><b><span class=\"fmLabel\">$::phr{'Date'}:</span></b></td>
  <td align=left><input type=text size=20 maxlength=24 name=sdate value=\"$udate\" class=\"fmEntry\" onChange=\"rmED()\">",
  linkSmallCal("webcal.sdate",$who,$month,$year),"</td>
  <td colspan=2 rowspan=6 valign=top bgcolor=#ffeedd class=\"editorEsum\">$summary<br></td>
</tr>
<tr>
  <td align=right width=\"8%\"><b><span class=\"fmLabel\">$::phr{'Start'}:</span></b></td>
  <td align=left>",select_time("s",$shr,$smn);
	 print "
 </td>
</tr>
<tr>
 <td align=right width=\"8%\"><b><span class=\"fmLabel\">$::phr{'End'}:</span></b></td>
 <td align=left>",select_time("e",$ehr,$emn);
	 print "
 </td>
</tr>";
   my $oltmp; if(defined $::calinfo{'ol'}) { $oltmp = $::calinfo{'ol'};} else {$oltmp = 0;} # 0 allow, 1 disallow
   if($oltmp < 2) {	 
   print "<tr><td>&nbsp;</td><td>&nbsp;<font color=#cd3b3b size=-1><b><span class=\"fmLabelS\">$::phr{'AllowOverlap'}:</span>";
   my $trmp = input_radio("aol",$oltmp, @::boolList);
   $trmp =~ s/class=\"fmRadio\"/class=\"fmRadioS\"/g;
   print  $trmp, "</b></font>";
   print "</td></tr>";
  } else { print "<tr><td><font size=1><br></font></td></tr><input type=hidden name=\"aol\" value=2>";}

 print "<tr>
 <td align=right><font color=#cc00cc><b><span class=\"fmLabel\">$::phr{'What'}:</span></b></font>$iadd1</td>
 <td align=left>
   <textarea cols=30 rows=2 wrap=virtual name=description class=\"fmText\">$description</textarea>
 </td>
</tr>

<tr>
 <td align=right width=\"8%\">$upload<b><span class=\"fmLabel\">$::phr{'Details'}:</span><br><a href=\"#dd\"><img src=\"$::o{'imgdirurl'}/lower.gif\" width=25 height=16 border=0></a>&nbsp;&nbsp;&nbsp;</b></td>
 <td align=left>
   <textarea cols=30 rows=3 wrap=virtual name=detail class=\"fmText\">$detail</textarea>
 </td>
</tr>
<tr>
<td width=\"8%\" align=right><font color=#cc00cc><b><span class=\"fmLabel\">$::phr{'Location'}:</span></b></font></td>
<td align=left><input type=text size=24 maxlength=60 name=sroom value=\"$room\" class=\"fmEntry\"></td>
<td colspan=2 rowspan=2 align=\"center\" class=\"editsubmit\">$submit $cancelbtn</td>
</tr>
<tr>
<td width=\"8%\" align=right><b><span class=\"fmLabel\">$::phr{'Category'}:</span></b></td>
<td align=left><input type=text size=12 maxlength=60 name=cat value=\"$cat\" class=\"fmEntry\">$catlist</td></tr>";

       print <<END;
<tr>
 <td noWrap align=right><font color="#009900"><b><span class=\"fmLabel\">$::phr{'Priority'}:</span></b></font></td>
 <td align=left><input type=text size=8 maxlength=99 name=pri class=\"fmEntry\" value=\"$priority\">&nbsp;
END
    ;
       print select_optionV("ignore", $priority,
"OnChange=\"Javascript:var z=window.document.webcal;z.pri.value=z.ignore.options[z.ignore.selectedIndex].value;\"",
                              @priorityL);

	 print $cpath;
       
       print "
</td>
<td colspan=2 nowrap align=right><span class=\"fmLabel\">$::phr{'Speaker'}:</span><input type=text size=20 maxlength=60 name=spkr value=\"$spkr\" class=\"fmEntry\">&nbsp;&nbsp;</td>
</tr>";


	 print "
<tr>
<td align=right class=\"editorClrs\">
<font color=blue><b><input type=Button  class=\"fmBtn\" onclick=\"openpopup('$::o{'cginame'}?c=showclr&w=$who','clrs',500,480)\" value=\"$::phr{'Colors'}:\"></b></font>
<br>
";
      print user_defined_color_pairs(3);

      print "</td><td class=\"editorClrs\"><table border=0 cellspacing=0 cellpadding=0 width=\"100%\" class=\"editorClrs\"><tr><td bgcolor=#ccccff class=\"editorClrs\">",
	  "<span class=\"fmLabel\">$::phr{'Fg'}:</span>",
	 "&nbsp;<input type=text size=8 value=\"$theFG\" name=fgclr class=\"fmEntry\">",
	 select_valueV("pfgclr",$theFG, "onChange=javascript:psetfg()", ("?????", $theFG, @::sixteenColors)),
	 "<br>",
	 "<span class=\"fmLabel\">$::phr{'Bg'}:</span>",
	 "&nbsp;<input type=text size=8 value=\"$theBG\" name=bgclr class=\"fmEntry\">",
         select_valueV("pbgclr",$theBG, "onChange=javascript:psetbg()", ("?????", $theBG, @::sixteenColors));
         my ($cst, $sid)= user_defined_css('css', $theCs,1);
	 my $eurl="$::o{'cgicss'}?c=post&w=$who";    
	 if($cst) {
	     print  <<END;
</td><td class="editorClrs">&nbsp;</td><td bgcolor="#ffcccc" class="editorFont">&nbsp;<a href="javascript:openpopup('$eurl','ecs',680,600)" onMouseOver="showtip(event,'$sid');" 
onMouseOut="hidetip('$sid');"><span class=\"fmLabel\">$::phr{'Font'}:</span></a><br>&nbsp; $cst
END
    ;
	 }
         print "</td></tr></table>";

       print "
 </td>
 <td class=\"editorCT\"  bgcolor=#ccffcc nowrap colspan=2 valign=bottom align=right><span class=\"fmLabel\">$::phr{'ContactP'}:</span><input type=text size=20  class=\"fmEntry\" value=\"$ctp\" name=ctp>&nbsp;&nbsp;<br><span class=\"fmLabel\">$::phr{'ContactE'}:</span><input type=text size=20 value=\"$ctm\" name=ctm class=\"fmEntry\">&nbsp;&nbsp;</td>
</tr>
<tr>
 <td class=\"editorP\" align=right width=\"8%\"><font color=#cc00cc><b><span class=\"fmLabel\">$::phr{'Privacy'}:</span></b></font></td>
 <td class=\"editorP\" align=left>",select_value("eprivacy",$privacy, @::privacyList),"</td>
 <td  class=\"editorK\" colspan=2 align=right><span class=\"fmLabel\">$::phr{'Keyword'}:</span> <input type=text size=20 maxlength=128 name=kwd value=\"$kwd\" class=\"fmEntry\">&nbsp;&nbsp;</td>
</tr>";

#--------- 07/22/01
       &printAttPart($who, $attendants,$imgp,$mme, $rsvp, "#cc00cc");
#--------- 07/22/01
       print "<tr><td colspan=4><hr></td></tr>
<tr>
 <td align=right></td>
 <td align=left><font color=#cc00cc><b><span class=\"fmLabel\">$::phr{'Frequency'}</span></b></font></td>
 <td><br></td>
 <td align=left><font color=#cc00cc><b><span class=\"fmLabel\">$::phr{'Reminders'}</span></b></font></td>
</tr>
<tr>";

	my $cfreq="$::o{'cginame'}?c=cfreq&w=$who&ooc=";
	print "
<td align=right><b><span class=\"fmLabel\">$::phr{'Occurs'}:</span></b><br><a href=\"javascript:cfreq('$cfreq')\"><font color=blue size=1><span class=\"fmLabelS\">$::phr{'More'}&nbsp;&nbsp;</span></font></a></td>
<td align=left nowrap>";
	 my @freq16=customized_freq($occurs); my $hid_oc; if($freq16[0]=~/^Z/){$hid_oc=$freq16[0];}else{$hid_oc="";}
	 my $fq = select_value("occurs",$occurs,(@::occurrenceList, @freq16));
	 $fq =~ s/<select/<select onChange=\"pfreq('$cfreq')\"/;
	 print "$fq", "<input type=\"hidden\" name=\"hidden_occurs\" value=\"$hid_oc\">", "</td>";
	 print "
<td  noWrap align=right><font size=-2 color=#ff00cc><b><span class=\"fmLabel\">$nmrb$::phr{'MailToAll'}<br>$::phr{'Participants'}$nmre</span></b></font></td>
<td noWrap align=left>";
	 print input_radio("rmail",$maily,@::nyList);
	 print "
 <input type=text size=4 maxlength=36 name=rmailv value=\"$maili\" class=\"fmEntry\"> ";
	 print select_value("rmailu",$mailu,@::unitmList),"</td></tr>";
	 print "
<tr>
 <td align=right><b><span class=\"fmLabel\">$::phr{'For'}:</span></b></td>
 <td align=left nowrap>
   <input type=text size=4 maxlength=12 name=repeat value=\"$repeat\"
 class=\"fmEntry\"  onChange=\"rmED()\"> <span class=\"fmLabel\">$::phr{'times'}</span>
 <font color=blue><span class=\"fmLabel\">$::phr{'orIndefinitely'}</span></font> <input type=checkbox name=rforever value=1 $forever class=\"fmRadio\" onChange=\"resetED()\">
 </td>
 <td align=right><b><span class=\"fmLabel\">$nprb$::phr{'Popup'}$npre</span></b></td>
 <td noWrap align=left>";
	 print input_radio("rpopup",$popupy,@::nyList);
	 print "
<input type=text size=4 maxlength=36 name=rpopupv value=\"$popupi\" class=\"fmEntry\"> ";
	 print select_value("rpopupu",$popupu,@::unitList),"</td></tr>";

	 print "<tr><td align=right><b><span class=\"fmLabel\">&nbsp;</span></b></td>
<td nowrap><font color=#009900><span class=\"fmLabel\">$::phr{'orUntilDate'}</span></font>
<input name=enddate type=text size=10 class=\"fmEntry\" value=\"$enddate\">",
linkSmallCal("webcal.enddate",$who,$month,$year),
"<br><font size=2 color=#f03060>$::phr{'wcf'}</font></td>
  <td align=right><b><span class=\"fmLabel\">$nbrb$::phr{'Blink'}$nbre</span></b></td>
  <td noWrap align=left>";
	 print input_radio("rflash",$flashy,@::nyList);
	 print "
<input type=text size=4 maxlength=36 name=rflashv value=\"$flashi\" class=\"fmEntry\"> ";
	 print select_value("rflashu",$flashu,@::unitList),"</td></tr>";


	 print "
<tr><td align=right><b><span class=\"fmLabel\">URL:</span></b>$iadd2</td>
<td align=left>
<input type=text size=30 maxlength=124 name=rurl value=\"$rurl\" class=\"fmEntry\">
</td>
  <td align=right><b><span class=\"fmLabel\">$ncrb$::phr{'Chime'}$ncre</span></b></td>
  <td noWrap align=left>";
	 print input_radio("rchime",$chimey,@::nyList);
	 print "
<input type=text size=4 maxlength=36 name=rchimev value=\"$chimei\" class=\"fmEntry\"> ";
	 print select_value("rchimeu",$chimeu,@::unitList),"</td></tr>";

	 print "
<tr><td align=right><b><span class=\"fmLabel\">$::phr{'Author'}:</span></b></td>
<td align=left><span class=\"fmLabel\">$pauthor</span>
</td><td  class=\"editorRmnd1\" colspan=2 nowrap bgcolor=#ccffcc> <font size=2 color=red><span class=\"fmLabelS\">$::phr{'remindOnce'}: </span>
<b>$ronce</b></font></td></tr>";

	 print "<tr><td colspan=4><hr></td></tr>";

	 print "<tr><td colspan=4 align=center>";
       print "<a href=\"#uu\"><img src=\"$::o{'imgdirurl'}/upper.gif\" width=25 height=16 border=0></a>&nbsp;\n";
       $submit =~ s/fmBtnStSa/fmBtnSt/g; $cancelbtn =~ s/fmBtnStSa/fmBtnSt/g;
       print "$submit";

       if( not $::calinfo{'inpopup'}){
	   print "<input type=submit name=action class=\"fmBtnSt\" value=\"$::phr{'FindConflict'}\">";
       }
       print "$cancelbtn</td></tr>";

       if( not $::calinfo{'inpopup'}){
	   print "<tr><td colspan=4><hr></td></tr>\n";
	   print "<tr><td class=\"editorCmp\" colspan=4 align=center bgcolor=$webcalConfig::r{'dkbackground'}>
<span class=\"fmLabel\">$::phr{'View'}:&nbsp;</span>",select_value("v",$view,@::viewList)," ",
select_value("ls",$ls,@::lsList)," <span class=\"fmLabel\">$::phr{'Events'}:&nbsp;</span>",
select_value("ke",0,@::eventList),"
<br><input type=submit name=action class=\"fmBtnSt\" value=\"$::phr{'ShowCombinedCalendar'}\"></td></tr>";
       }
       print "</table><a name=dd></a>\n";
     }  else {		# special event, $kind = 4;
       my $udate = to_native_date($date);
       my $submit;

       if($command eq 'edit') {
	   $submit = "
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'InsertAsNew'}\" $warnOld>
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'Modify'}\" $warnRepeat>";
	   if($repeat > 0) { $submit .= "
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'DeleteThisOne'}\">
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'DeleteForward'}\">
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'DeleteAll'}\">";
			 } else { $submit .= "
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'Delete'}\">";
			      }
	   $submit .= $cancelbtn;
       } else {
	   $submit = "
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'Insert'}\" $warnOld>
 <input type=submit name=action class=\"fmBtnStSa\" value=\"$::phr{'NextNew'}\" $warnOld>
$cancelbtn
";
       }

       print "

$kkind
<input type=hidden name=c value=\"doedit\">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=t value=\"$tag\">
<input type=hidden name=d value=\"$month/$day/$year/$hour/$min\">
$eme
$seq
$acc
$dec
$mg
$oedate
$exception
$recurr
$oattendants
$imkey
$xtra
<table border=0 cellspacing=2 cellpadding=0 width=\"$::o{'tw'}%\" class=\"editor\">
<tr><td width=\"8%\" align=right><b><span class=\"fmLabel\">$label0</span></b></td>
  <td width=\"42%\" align=left><font color=#0066ff><b>$label1</b></font></td>
  <td colspan=2 width=\"50%\" valign=bottom bgcolor=#ffeedd class=\"editorEsum\">
     <table border=0 cellpadding=0 cellspacing=0 width=\"100%\" class=\"editor\">
       <tr><td class=\"editorRow0\" width=\"20%\"><b><span class=\"fmLabel\">$::phr{'Time'}</span></b></td><td class=\"editorRow0\" width=\"80%\"><b><span class=\"fmLabel\">$::phr{'What'}</span></b><span class=\"fmLabelS\">&nbsp;($::phr{'CurrentEvents'} <font color=#ff0000>$udate</font>)</span></td></tr></table>
</td>
</tr>
<tr>
  <td width=\"8%\" align=right><b><span class=\"fmLabel\">$::phr{'Date'}:</span></b></td>
  <td align=left><input type=text size=20 maxlength=24 name=sdate value=\"$udate\" class=\"fmEntry\" onChange=\"rmED()\">",
  linkSmallCal("webcal.sdate",$who,$month,$year),"</td>
  <td colspan=2 rowspan=5 valign=top bgcolor=#ffeedd class=\"editorEsum\">$summary<br></td>
</tr>
<tr>
  <td align=right width=\"8%\"><b><span class=\"fmLabel\">$::phr{'Start'}:</span></b></td>
  <td align=left>",select_time("s",$shr,$smn);
	 print "
 </td>
</tr>
<tr>
 <td align=right><font color=#0066ff><b><span class=\"fmLabel\">$::phr{'What'}:</span></b></font>$iadd1</td>
 <td align=left>
   <textarea cols=30 rows=2 wrap=virtual name=description class=\"fmText\">$description</textarea>
 </td>
</tr>
<tr>
 <td align=right width=\"8%\">$upload<b><span class=\"fmLabel\">$::phr{'Details'}:</span><br><a href=\"#dd\"><img src=\"$::o{'imgdirurl'}/lower.gif\" width=25 height=16 border=0></a>&nbsp;&nbsp;&nbsp;</b></td>
 <td align=left>
   <textarea cols=30 rows=3 wrap=virtual name=detail class=\"fmText\">$detail</textarea>
 </td>
</tr>
<tr>
<td width=\"8%\" align=right><b><span class=\"fmLabel\">$::phr{'Location'}:</span></b></td>
<td align=left><input type=text size=24 maxlength=60 name=sroom value=\"$room\" class=\"fmEntry\"></td>
</tr>
<tr>
<td width=\"8%\" align=right><b><span class=\"fmLabel\">$::phr{'Category'}:</span></b></td>
<td align=left><input type=text size=12 maxlength=60 name=cat value=\"$cat\" class=\"fmEntry\">$catlist</td>
<td colspan=2 rowspan=2 align=\"center\" class=\"editsubmit\">$submit</td>
</tr>

<tr>
 <td noWrap align=right><font color=#009900><b><span class=\"fmLabel\">$::phr{'Priority'}:</span></b></font></td>
 <td align=left><input type=text size=8 maxlength=99 name=pri class=\"fmEntry\" value=\"$priority\">&nbsp;";
         print select_optionV("ignore", $priority,
"OnChange=\"Javascript:var z=window.document.webcal;z.pri.value=z.ignore.options[z.ignore.selectedIndex].value;\"",
                              @priorityL);

	 print $cpath;

	 print "
</td>
</tr>
<tr>
<td align=right class=\"editorClrs\">
<font color=blue><b><input type=Button class=\"fmBtn\" onclick=\"openpopup('$::o{'cginame'}?c=showclr&w=$who','clrs',500,480)\" value=\"$::phr{'Colors'}:\"></b></font><br>";
       
     print user_defined_color_pairs(4); 

      print "</td><td class=\"editorClrs\"><table border=0 cellspacing=0 cellpadding=0 width=\"100%\"><tr><td class=\"editorClrs\" bgcolor=#ccccff>",
	  "<span class=\"fmLabel\">$::phr{'Fg'}:</span>",
	 "&nbsp;<input type=text size=8 value=\"$theFG\" name=fgclr class=\"fmEntry\">",
	 select_valueV("pfgclr",$theFG, "onChange=javascript:psetfg()", ("?????", $theFG, @::sixteenColors)),
	 "<br>",
	 "<span class=\"fmLabel\">$::phr{'Bg'}:</span>",
	 "&nbsp;<input type=text size=8 value=\"$theBG\" name=bgclr class=\"fmEntry\">",
        select_valueV("pbgclr",$theBG, "onChange=javascript:psetbg()", ("?????", $theBG, @::sixteenColors));
	 my ($cst, $sid)= user_defined_css('css', $theCs,1);
	 my $eurl="$::o{'cgicss'}?c=post&w=$who";    
	 if($cst) {
	     print  <<END;
</td><td class=\"editorClrs\">&nbsp;</td><td  class=\"editorFont\" bgcolor="#ffcccc">&nbsp;<a href="javascript:openpopup('$eurl','ecs',680,600)" onMouseOver="showtip(event,'$sid');" 
onMouseOut="hidetip('$sid');"><span class=\"fmLabel\">$::phr{'Font'}:</span></a><br>&nbsp; $cst
END
    ;
	 }
         print "</td></tr></table>";

	 print "	 
 </td>
<td class=\"editorCT\" bgcolor=#ccffcc nowrap colspan=2 valign=bottom align=right><span class=\"fmLabel\">$::phr{'ContactP'}:</span><input type=text size=20 value=\"$ctp\" name=ctp class=\"fmEntry\">&nbsp;&nbsp;<br><span class=\"fmLabel\">$::phr{'ContactE'}:</span><input type=text class=\"fmEntry\" size=20 value=\"$ctm\" name=ctm>&nbsp;&nbsp;</td>
</tr>
<tr>
 <td align=right class=\"editorP\" width=\"8%\"><font color=#0066ff><b><span class=\"fmLabel\">$::phr{'Privacy'}:</span></b></font></td>
 <td align=left class=\"editorP\">",select_value("eprivacy",$privacy, @::privacyList),
"</td>
 <td colspan=2  class=\"editorK\"align=right><span class=\"fmLabel\">$::phr{'Keyword'}: </span><input type=text size=20 maxlength=128 name=kwd class=\"fmEntry\" value=\"$kwd\">&nbsp;&nbsp;</td>
</tr>";



#----begin insertion ------ added 07/13/2001
    &printAttPart($who, $attendants,$imgp,$mme, $rsvp, "#0066ff");
#----end insertion ------ added 07/13/2001

       print "
<tr>
<td colspan=4><hr></td>
</tr>
<tr>
 <td align=right></td>
 <td align=left><font color=#0066ff><b><span class=\"fmLabel\">$::phr{'Frequency'}</span></b></font></td>
 <td><br></td>
 <td align=left><font color=#0066ff><b><span class=\"fmLabel\">$::phr{'Reminders'}</span></b></font></td>
</tr>
<tr>";
	my $cfreq="$::o{'cginame'}?c=cfreq&w=$who&ooc=";
	print "
<td align=right><b><span class=\"fmLabel\">$::phr{'Occurs'}:</span></b><br><a href=\"javascript:cfreq('$cfreq')\"><font color=blue size=1><span class=\"fmLabelS\">$::phr{'More'}&nbsp;&nbsp;</span></font></a></td>
<td align=left nowrap>";
	 my @freq16=customized_freq($occurs); my $hid_oc; if($freq16[0]=~/^Z/){$hid_oc=$freq16[0];}else{$hid_oc="";}
	 my $fq = select_value("occurs",$occurs,(@::occurrenceList, @freq16));
	 $fq =~ s/<select/<select onChange=\"pfreq('$cfreq')\"/;
	 print "$fq", "<input type=\"hidden\" name=\"hidden_occurs\" value=\"$hid_oc\">", "</td>";
	 print "
<td  noWrap align=right><b><span class=\"fmLabel\">$nmrb$::phr{'Mail'}$nmre</span></b></td>
<td noWrap align=left>";
	 print input_radio("rmail",$maily,@::nyList);
	 print "
 <input type=text size=4 maxlength=36 name=rmailv value=\"$maili\" class=\"fmEntry\">";
	 print select_value("rmailu",$mailu,@::unitmList),"</td></tr>";
	 print "
<tr>
 <td align=right><b><span class=\"fmLabel\">$::phr{'For'}:</span></b></td>
 <td align=left nowrap>
   <input type=text size=4 maxlength=12 name=repeat value=\"$repeat\" 
class=\"fmEntry\"  onChange=\"rmED()\"> <span class=\"fmLabel\">$::phr{'times'}</span>
 <font color=blue><span class=\"fmLabel\">$::phr{'orIndefinitely'}</span></font> <input type=checkbox name=rforever value=1 $forever class=\"fmRadio\" onChange=\"resetED()\">
 </td>
<td colspan=2 class=\"editorRmnd1\" nowrap bgcolor=#ccffcc> <font size=2 color=red><span class=\"fmLabelS\">$::phr{'remindOnce'}:</span> 
<b>$ronce</b></font></td>
</tr>";


	 print "<tr><td align=right><b><span class=\"fmLabel\">&nbsp;</span></b></td>
<td nowrap><font color=#009900><span class=\"fmLabel\">$::phr{'orUntilDate'}</span></font>
<input name=enddate type=text size=10 class=\"fmEntry\" value=\"$enddate\">",
linkSmallCal("webcal.enddate",$who,$month,$year),
"<br><font size=2 color=#f03060>$::phr{'wcf'}</font></td>
<td>&nbsp;</td></tr>";
	 print "
<tr> 
<td align=right><b><span class=\"fmLabel\">URL:</span></b>$iadd2</td>
<td align=left>
<input type=text size=30 maxlength=124 name=rurl value=\"$rurl\" class=\"fmEntry\">
</td>
<td align=right><b><span class=\"fmLabel\">$::phr{'Author'}:</span></b></td>
<td align=left><span class=\"fmLabel\">$pauthor</span>
</td>
</tr>";

       print "<tr><td colspan=4><hr></td></tr>";
       if($cst) { $cst =~ s/<select name=\"css\"/<select name=\"nucss\" onchange=\"set_cell_css()\" /; }
       print "<tr>
  <td colspan=2><font color=#0066ff><b><span class=\"fmLabel\">$::phr{'RemindForward'}:</span></b></font>",input_radio("forward",$forward,@::nyList),
"</td><td colspan=2 nowrap align=right><font size=-1><span class=\"fmLabelS\">Cell bg:</span> <input type=text name=cbg size=16 maxlength=99  class=\"fmEntryS\" value=\"$cbg\">$cst $iadd3</font></td></tr>\n";

       print "<tr><td colspan=4><hr></td></tr>";

       $submit =~ s/fmBtnStSa/fmBtnSt/g;

       print "
<tr>
<td colspan=4 align=center>
 <a href=\"#uu\"><img src=\"$::o{'imgdirurl'}/upper.gif\" width=25 height=16 border=0></a>&nbsp;
$submit
</table>
";
       print "<a name=dd></a>\n";
     }
     print "<hr></form>\n";
     if(($::d{'authResult'} | $::d{'ispublic'}) < 4 or $::d{'validuser'} == 0) {
	     print "<center><br><font color=#999900><b><span class=\"authWarn\">$::phr{'AuthRequired'}!</span></b></font>\n</center>";
     }
     &trailer(0,0);
}


#==============================================================================================
sub printAttPart {
    my ($who, $attendants,$imgp,$mme, $rsvp, $color,$fmname)=(@_);
    if($::d{'remote_user'} eq 'anonymous' or $::d{'remote_user'} eq 'nobody') { return;}
    if($::o{'corporate_calendar'} and ismember($who, $::o{'corporate_calendar'})) { return;}
    my $more =""; 
    my ($lcalB, $lcalE, $calB, $calE)=("", "", "", "");
    if($::o{'listAllCals'}) {
	$lcalB = "<a href=\"javascript:openpopup(\'$::o{'cginame'}?c=listcal&w=$who\',\'calendars\',500,400)\">";
	$lcalE = "</a>";
    } else {
	$calB = "<a href=\"javascript:openpopup(\'$::o{'cginame'}?c=listcal&w=$who\',\'calendars\',500,400)\">";
	$calE = "</a>";
    }
    if( ($::d{'authResult'} | $::d{'ispublic'}) == 4 and $::o{'tabs'} =~ /ad,|,ad$/) {
	if(not $fmname) { $fmname="webcal";}
	$more="<br><a href=\"javascript:openpopup(\'$::o{'cginame'}?c=gEaddr&fmname=$fmname&eltname=mattendants\','ew',800,500)\"><font color=blue size=1><span class=\"fmLabelS\">$::phr{'AddressBook'}&nbsp;</span></font></a>";
    }
    print "\n<tr><td class=\"editorAtt\">&nbsp;</td><td  class=\"editorAtt\" bgcolor=$webcalConfig::r{'dkbackground'} colspan=4><font size=-1><span class=\"fmLabelS\">$::phr{'ListParticipants'}.</span></font></td></tr>\n";

    print "<tr><td class=\"editorAtt\" align=right>$lcalB<font color=$color>$calB<b><span class=\"fmLabel\">$::phr{'Participants'}:</span></b>$calE</font>$lcalE$more</td>";
    $::calinfo{'_clist_'} = 1;
    if($::calinfo{'c'} eq 'ne' and ($::calinfo{'resrc'} or $::calinfo{'noinvitee'})) { $attendants = $imgp = "";}
    my ($hasmeetgroup, @slist, $eme); if($::calinfo{'eme'}) { $eme=$::calinfo{'eme'};} else {$eme=$who;}
    @slist = get_mgroups($eme);
    $hasmeetgroup = scalar @slist;
    unshift @slist,"$::phr{'none'}";
    my ($textfield,$selectfield);
    if ($hasmeetgroup) {
	my $mglabel= "<font color=$color><b><span class=\"fmLabel\">$::phr{'Meeting_group'}:</span></b></font>";
	if(not $imgp and $attendants) {
	    my @all = split(/[,:]/, $attendants);
	    my ($t, $s);
	    foreach $t (@all) { foreach $s (@slist) {if ($t eq $s) {$imgp = $s; last;}} if($imgp) { last;}}
	}
	my $att = $attendants;
	if($imgp) {my @all = split(/[,:]/, $attendants); $att=""; my ($t); for $t (@all) { if($t ne $imgp) {$att .= "$t:";}}}
	($textfield,$selectfield) = select_multicals("mattendants",$att);
	print "<td class=\"editorAtt\" nowrap bgcolor=$webcalConfig::r{'dkbackground'} colspan=4>$textfield &nbsp;&nbsp;";
	print $mglabel, "\n";
	print select_mgp("smtgp",$imgp,@slist);
	if($::calinfo{'smgpowner'} or $eme ne $who) { 
	    print "<font size=1><span class=\"fmLabelS\"> $::phr{'OwnerName'}:</span>
 <font color=red><span class=\"fmLabel\">$eme</span></font></font>";
	}
    } else {
	($textfield,$selectfield) = select_multicals("mattendants",$attendants);
	print "<td class=\"editorAtt\" nowrap bgcolor=$webcalConfig::r{'dkbackground'} colspan=4>$textfield &nbsp;&nbsp;";
    }
    print "</td></tr>";
    # have to embed a table to make the columns aligned right
    delete $::calinfo{'_clist_'};
    if($::o{'listAllCals'}) {
	print "<tr><td class=\"editorAtt\"><br></td><td class=\"editorAtt\" align=left valign=top colspan=4 bgcolor=$webcalConfig::r{'dkbackground'}>",
	"<table border=0 cellspacing=0 cellpadding=0><tr><td class=\"editorAtt\" valign=top>", $selectfield, "&nbsp;&nbsp;</td><td class=\"editorAtt\">",
	"<blockquote class=\"fmMsg\">", $::phr{'SelectAttendee'}, "</blockquote>",
	"</td></tr></table>",
	"</td></tr>";
    } 
    print "<tr><td class=\"editorAtt\"><br></td>
<td class=\"editorAtt\" bgcolor=$webcalConfig::r{'dkbackground'} colspan=4><font color=#ff0000><b><span class=\"fmLabel\">$::phr{'Participants_are_allowed_to'}&nbsp;</span>",input_radio("imme",$mme,
																       (   "0","$::phr{'View_only'}",
																	   "1","$::phr{'Edit'}",
																	   "2","$::phr{'EditAndDelete'}")),"
</b></font></td></tr>";
    print "<tr><td class=\"editorAtt\">&nbsp;</td><td class=\"editorAtt\" bgcolor=$webcalConfig::r{'dkbackground'} colspan=4><font color=#ff0000><b><span class=\"fmLabel\">$::phr{'RequestRSVP'}:&nbsp;&nbsp;</span>",input_radio("rsvp", $rsvp, ("0", $::phr{'N'}, "1", $::phr{'Y'})), "<b></font></td></tr>\n";
}
#==============================================================================================
sub findConflict {
    if($::calinfo{'cfd'}) {
	if($::calinfo{'cfd'} > 1) { &findConflictDetail(@_);}
	else { &findConflictCombined(@_);}
    } else { &findConflictZ(@_);}
}

sub findConflictZ {
    use integer;
    my ($rest, $d, $i, $k, $m, $n, $itv, $cal, $iwho, $stmp, $utmp, $ttmp,$table, $wcode, $tday, $month, $day, $year, $msg,
	$sdate, $tdate, $todayc, $todayc0, $start, $end, $cmin, $title, @dwd, $tmp, $view, $stime, $etime, $smth, $sday, $syr,
	$nday,$nmonth, $nyear, $bcnt, $etmp, $extra, $date, $htb, $wklen, $ls, %mhash, $total, $inpopup, $A);
    my ($others, @members, $mem, @rmembers, $eMe, $invitee, %whash, %thash, $fsize);
    $view= $::calinfo{'v'};  $ls = $::calinfo{'ls'};  $iwho = $::calinfo{'w'};
    $stime=$::calinfo{'shour'} || $::calinfo{'hourB'};
    if (not $::o{'hourformat'} and $::calinfo{'sampm'} and $::calinfo{'sampm'} eq 'pm') { $stime += 12 unless $stime eq 12;}
    $etime=$::calinfo{'ehour'} || $::calinfo{'hourE'};
    if (not $::o{'hourformat'} and $::calinfo{'eampm'} and $::calinfo{'eampm'} eq 'pm') { $etime += 12 unless $etime eq 12;}
    if($stime > $etime){ $tmp=$stime; $stime=$etime; $etime=$tmp;}
    #$etime++ unless $etime == 24;

    if($::o{'excludeWeekend'}) { $wklen=5; $fsize=2;} else { $wklen =7; $fsize=1;}

    ($extra, $invitee) = getEditorState();    $extra .= $invitee;
    $etmp = $::calinfo{'smtgp'};
    if(defined $::calinfo{'mattendants'}) {$tmp = $::calinfo{'mattendants'};} else {$tmp="";}
    if($etmp && $etmp ne "$::phr{'none'}") { $_=$tmp;  if( ! /\b$etmp\b/) { $tmp .= ":$etmp";}}

    if($::calinfo{'imkey'}) { $eMe = $::calinfo{'imkey'}; $eMe =~ s/_eMe_\d+//g; } 
    elsif($::calinfo{'eme'}) { $eMe = $::calinfo{'eme'};}
    else {$eMe = $iwho;}
    if(!$tmp) { $tmp = $::calinfo{'mg'};}
    $tmp =~ s/[,; ]+/:/g;    $tmp =~ s/:$//g;
    $others = expandMeetingGroups($eMe,"$tmp:$iwho", 1);
    if(!$others) { $others = $iwho;}
    my (%hh, @tmem);  %hh= ();
    @members=(); @rmembers=();
    (@tmem) = split(/:/, $others);
    for $mem (@tmem) { if( ! exists $hh{$mem}) { push @members, $mem; $hh{$mem} = 1;}}
    $date = $::calinfo{'sdate'} || $::calinfo{'d'};
    ($month, $day, $year, $rest) = split(/\//, $date); $month -=1;
    ($smth, $sday, $syr, $rest) =($month, $day, $year);
    $todayc0 = printDate0( $month, $day, $year);
    if($::calinfo{'interval'}) {$itv = $::calinfo{'interval'};} else {$itv=30;}

    $wcode= wday($month, $day, $year);
    if($wcode == 0 && $::o{'weekstart'}) {$wcode = 7;}
    $tday = $day = $day - $wcode;
    $todayc = printDate( $::now{'month'}, $::now{'day'}, $::now{'year'});
    if($tday <= 0) {
	if($month == 0) {
	    $month = 11;  $year -= 1; $tday = 31 + $tday;
	} else {
	    $month -= 1;
	    if($month == 1) { if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}}
	    $tday = $::mdays[$month] + $tday;
	}
    }
    my ($zmonth, $zday, $zyear) = canDate($month, $tday+1, $year);
    if($::o{'weekstart'})   { ($nmonth, $nday, $nyear) = ($zmonth, $zday, $zyear);}
    else { ($nmonth, $nday, $nyear) = ($month, $tday, $year);}
    $msg="<font color=#ff0000><b>$::phr{'Week_starts_on'} ".mdy_string($nmonth,$nday,$nyear)."</b></font>";
    if($::calinfo{'inpopup'}) {$inpopup="&inpopup=1"; $A="z";} else {$inpopup=""; $A="a";}

    if(not $::calinfo{'cmp'}) {
	$start = $::calinfo{'hourB'};
	if($start > $stime) { $start = $stime;}
	$end = $::calinfo{'hourE'};
	if($end < $etime) { $end = $etime;}
    } else {
	$start = $stime;
	$end = $etime;
    }
    %mhash=(); %whash=(); %thash=();
    $title="";
    my $who = "";

    my @_ary=(); for($d=0; $d < $wklen; $d++) {  my @tmp=map("", (0..25)); push @_ary, \@tmp;} 
    my @_bry=(); for($d=0; $d < $wklen; $d++) {  my @tmp=map(0, (0..25)); push @_bry, \@tmp;} 
    $k = "==$::phr{'All'}==";  $mhash{$k}=\@_ary; $thash{$k}=\@_bry;
    my $whoami = $::d{'remote_user'}; my $admin = isadmin($whoami);

    for $mem ( @members) {
	my ($calendar);
	$_ = $mem;
	if(/.+\@.+/ and ! -d "$::o{'spooldir'}/$mem") {
	    $tmp = findWhoFromEmail($mem); 
	    if($tmp) {$mem = $tmp;}
	}
	next if $mem =~ /\//;
	$mem = untaintname($mem,$::phr{'Invalidusername'});
	$calendar = "$::o{'spooldir'}/$mem";
	@::caldata=();
	if( -d $calendar and -f "$calendar/data") {
	    $who = $mem;
            $::d{'ceditor'} = isre($::d{'remote_user'}, $mem, 'any');
	    $::caldata=(); tryReadCache($mem,2,$zmonth, $zday, $zyear);
	    my $ispublic;  { my $tmp=getinfo($mem, 'ctype'); if($tmp and $tmp =~ 'public'){$ispublic=1;}};
	    my $reader = ($admin or $ispublic or $::d{'ceditor'} or ($whoami eq $mem) or isvgadmin($whoami,$mem))?1:0; 
	    if(!$reader) { 
		my $href;
		foreach $href (@::caldata) { 
                    if($href->{'privacy'}) {
                        my $privacy = $::privacyTable{$href->{'privacy'}};
                        if($privacy < 3) { $href->{'what'} = $::phr{'Protected'};} 
                    }
		}
	    }
	    $title .= " <$A href=\"$::o{'cginame'}?c=get&ls=$ls&w=$mem&v=2&d=$smth/$sday/$syr$::vmg\"><span class=\"memberInTitle\">$mem</span></$A>";

	    getWorkingHourTable($mem);
	    my @ary=();  for($d=0; $d < $wklen; $d++) {  my @tmp=map("", (0..25)); push @ary, \@tmp;} $mhash{$mem} = \@ary;
	    my @bry=();  for($d=0; $d < $wklen; $d++) {  my @tmp=map(0, (0..25)); push @bry, \@tmp;} $thash{$mem} = \@bry;
	    # off duty hours
	    for($d=0; $d < 7; $d++) {
		my $istart = $::WorkingHours[$d]/100;
		my $iend = $::WorkingHours[$d+8]/100;
		my $ttb = $bry[$d];
		for($i=0; $i < $istart; $i++){$ttb->[$i]=987654321; $_bry[$d]->[$i] |= 987654321;}
		for($i=$iend; $i<24;$i++){$ttb->[$i]=987654321; $_bry[$d]->[$i] |= 987654321;}
	    }

	    for($d=0; $d < $wklen; $d++) {
		my ($key, $j, $str);
		$m=$tday+$d +$::o{'weekstart'};
		($nmonth, $nday, $nyear) = canDate($month, $m, $year);
		getOneDayEvents($nmonth, $nday, $nyear, $todayc,0);
		for $key (keys %::oneDayEvents) {
		    my $thing = $::oneDayEvents{$key}; 
		    my ($hr,$mn, $ehr, $emn, $kind, $tag)=split(/:/, $key);if($kind==4){$hr=~ s/^\(\d+\)//;}
		    if($kind & 1) {
			my $time = hm_hm_string($hr,$mn,$ehr,$emn); 
			my $color; $color = $kind == 1? "$::o{'tclra'}" : "$::o{'tclrm'}";
			my $nn="";
			if($emn > 0) {$ehr++;}
			if($bry[$d]->[$hr] <= 0 ||$bry[$d]->[$hr]==987654321) {
			    for($j=$hr; $j<$ehr; $j++) {$bry[$d]->[$j] = 0;}
			    $nn= "<font color=black><b>$mem</b>:</font><br>";
			}
			$str ="$nn<font color=$color>" . $time . "</font> " . $thing . "<br>";  
			if($ehr < $start or $hr > $end) {
			    $bry[$d]->[$hr] += $tag;  $bry[$d]->[24] += $tag; $ary[$d]->[24] .= $str;
			    $_ary[$d]->[24] .= $str; $_bry[$d]->[24] += $tag;
			} else {
			    for($j=$hr; $j<$ehr; $j++) { 
				$bry[$d]->[$j] += $tag;   $ary[$d]->[$j] .= $str;
				$_ary[$d]->[$j] .= "$str"; $_bry[$d]->[$j] += $tag;
			    }
			}
		    } else {
			my $nn=""; 
			if($bry[$d]->[24] == 0 || $bry[$d]->[24] ==987654321) { $nn= "<font color=black><b>$mem</b>:</font><br>";}
			$bry[$d]->[24] += $tag;
			$_bry[$d]->[24] += $tag;
			if($kind == 2){
			    my $str = "$nn<font color=$::o{'tclrt'}>" . hm_string($hr,$mn) . "</font>" . $thing . "<br>"; 
			    $ary[$d]->[24] .= $str;
			    $_ary[$d]->[24] .= "$str";
			} else { 
			    my $str = "$nn<font color=$::o{'tclrs'}>****</font> " . $thing . "<br>"; 
			    $ary[$d]->[24] .= $str;			
			    $_ary[$d]->[24] .= "$str";
			}
		    }
		}
		%::oneDayEvents =();
	    }
	    push @rmembers, $mem;
	}
    }
    $tmp=join(':', @rmembers);  $tmp =~ s/^:|:$//g; my $zg=""; if(0+@rmembers>1){$zg=$tmp;}
    my $eme= $iwho;
    if($::calinfo{'eme'}) { $eme = $::calinfo{'eme'};}
    $extra="eme=".$eme. $inpopup . "&mg=$tmp&" . $extra ;

    my ($prev, $next);
    {
	my ($m,$d,$y) = canDate($smth, $sday-7, $syr); $m++;
	$prev = <<END;
<a href="$::o{'cginame'}?c=docompare&action=cft&w=$iwho&v=$view&ls=$ls&d=$m/$d/$y$::vmg&$extra&cfd=0"><img src="$::o{'imgdirurl'}/rleft.gif" width=10 height=12 border=0 alt=""></a>
END
    ;
	($m,$d,$y) = canDate($smth, $sday+7, $syr); $m++;
	$next = <<END;
<a href="$::o{'cginame'}?c=docompare&action=cft&w=$iwho&v=$view&ls=$ls&d=$m/$d/$y$::vmg&$extra&cfd=0"><img src="$::o{'imgdirurl'}/rright.gif" width=10 height=12 border=0 alt=""></a>
END
    ;
    }
    &headers($::phr{'ConflictTable'},
	     "function qa(){q=window.open(\"$::o{'cginame'}?c=qa&w=$who&v=$view&ls=$ls&d=$smth/$sday/$syr$::vmg&mg=$zg\",\"qa\", \"scrollbars=yes,resizable=yes,width=600,height=300\");if(window.focus){q.window.focus(); }}",
	     ,undef,1,1);
    print "<center>\n";
    print "<br><font size=+1><b><span class=\"miscTitle\">$::phr{'Calendar'} $::phr{'Conflict'} $::phr{'Table'}</span></b></font><br>";
    print "$title<br>$prev&nbsp;&nbsp;$msg &nbsp;&nbsp;$next$::o{'qadd'}";
    print "<br><br>\n";

    if(not $::calinfo{'cmp'}) {
	$start = $::calinfo{'hourB'};
	if($start > $stime) { $start = $stime;}
	$end = $::calinfo{'hourE'};
	if($end < $etime) { $end = $etime;}
    } else {
	$start = $stime;
	$end = $etime;
    }

    $total= 1+@rmembers;
    my $ncells = 2 + $end - $start;

    print "<table border=0 cellpadding=0 cellspacing=0 bgcolor=#999999 class=\"backtblfb\"><tr><td class=\"backtblfb\">";
    print "<table border=0 cellpadding=0 cellspacing=1 class=\"fbtbl\">";
    print "<tr><td bgcolor=#ccff33 class=\"crow1\"><font size=$fsize>&nbsp;</font></td>";
    
    for($d=0; $d < $wklen; $d++) {
	my ($jk, $kj)=("", "");
	$m=$tday+$d+$::o{'weekstart'};
	($nmonth, $nday, $nyear) = canDate($month, $m, $year);
	my $zz = $::o{'weekstart'}+$d;
	$utmp = "<font color=black><span class=\"crow1txt\">$::swd[$zz]</span></font>";
	if($d&1) { $kj="bgcolor=#ddddee"; $jk="#ddddee";} else {$kj = "bgcolor=#ffffff";}
	print "<td align=center colspan=$ncells $kj class=\"crow1\"><$A href=\"$::o{'cginame'}?c=get&v=1&w=$iwho&d=$nmonth/$nday/$nyear&$extra\"><font size=-1 color=#cc00cc><span class=\"crow1txts\">".md_nstring($nmonth+1,$nday) . "</span></font>&nbsp;&nbsp;<b>$utmp</b></$A></td>";
    }
    print "</tr>\n";
    print "<tr><td bgcolor=#ccff33 class=\"ccol1\" align=center><img src=\"$::o{'imgdirurl'}/gt.gif\" width=40 height=20 border=0></td>";
    my $tstr="<td bgcolor=#ffcc66 class=\"ccolz\"><font size=$fsize><br></font></td>";

    for($d=0; $d < $wklen; $d++) {
	$m=$tday+$d+$::o{'weekstart'};
	($nmonth, $nday, $nyear) = canDate($month, $m, $year);
	print $tstr, "\n";
	for($i=$start; $i<=$end; $i++) {
	    my ($ten, $one, $all);
	    $all = sprintf "%02d", $i;
	    $ten= substr($all, 0,1); $one= substr($all, 1,1);
	    print "<td bgcolor=#cccc99 class=\"crow2\"><a href=\"$::o{'cginame'}?c=ne&d=$nmonth/$nday/$nyear/$all/0&w=$iwho&v=$view&ls=$ls$::vmg&k=3&wa=1&$extra\"><font size=$fsize color=black><span class=\"crow2txt\">$ten<br>$one</span></font></a></td>";
	}
    }
    print "</tr>\n";

    my @rrmembers = sort { uc($a) cmp uc($b)} @rmembers;
    for $mem ("==$::phr{'All'}==", @rrmembers) {
	my $taref = $thash{$mem};
	my $maref = $mhash{$mem};
	my $owner=$mem; 
	my $aa = "$::o{'cginame'}?c=ne&v=$view&ls=$ls&w=$owner$inpopup";
	my $bb="";
	my $divider="";
	if($mem eq "==$::phr{'All'}==") {
	    if( $total > 2) {
		my $n = $ncells * $wklen + 1;
		$divider="<tr><td bgcolor=#cccc00 colspan=$n class=\"cdivider\"><img src=\"$::o{'imgdirurl'}/spacer.gif\" height=2 width=100></td></tr>";
		$owner = $iwho;
		$aa = "$::o{'cginame'}?c=ne&v=$view&ls=$ls&w=$owner&wa=1&$extra&k=3";
		$bb=$extra;
	    }  else { next;}
	} 
	print "<tr><td bgcolor=#666699 class=\"ccol1\"><$A href=\"$::o{'cginame'}?c=get&v=2&w=$owner&d=$smth/$sday/$syr$::vmg&$bb\"><font color=white><b><span class=\"ccol1txt\">&nbsp;$mem</span></b></font></$A></td>";

	for($d=0; $d < $wklen; $d++) {	
	    my $ttb = $taref->[$d];
	    my $mtb = $maref->[$d];
	    my $tdate = printDate0($month, $tday+$::o{'weekstart'}+$d,$year);
	    if($ttb->[24]) {
		my $m = $mtb->[24];
		my $tid=addtip($m);
		my $tip = "onMouseOver=\"showtip(event,\'$tid\');\" onMouseout=\"hidetip(\'$tid\');\"";
		print "<td bgcolor=#00cc66 class=\"ccolx\"><a href=\"javascript:void(0)\" $tip><font size=$fsize><span class=\"cc\">&nbsp;&nbsp;</span></font></a></td>";
	    } else {
		print "<td bgcolor=#ffcc66 class=\"ccolz\"><font size=$fsize><span class=\"cc\">&nbsp;&nbsp;</span></font></td>";
	    }
	    for($i=$start; $i<=$end; $i++) {
		my ($m, $c, $t, $tid, $tip);
		$m = $mtb->[$i];
		if($m) {
		    $tid=addtip($m);
		    $tip = "onMouseOver=\"showtip(event,\'$tid\');\" onMouseout=\"hidetip(\'$tid\');\"";
		} else {
		    $tip="";
		}
		$c = $ttb->[$i];
		if($c == 987654321) {
		    if(not $tip) {
			$tid = add2tip("odhrs", $::phr{'OffDutyHours'});
			$tip = "onMouseOver=\"showtip(event,\'$tid\');\" onMouseout=\"hidetip(\'$tid\');\"";
		    }
		    print "<td background=\"$::o{'imgdirurl'}/mask1.gif\"><font size=$fsize><span class=\"cc\"><a href=\"$aa&d=$tdate/$i/0\" $tip>&nbsp;&nbsp;</a></span></font></td>";
		} elsif($c) {
		    my $z=$c & 0x1f;
		    my $bgclr=$webcalConfig::r{'txtColors'}->[$z];
		    print "<td bgcolor=$bgclr class=\"cbusy\"><font size=$fsize><span class=\"cc\"><a href=\"$aa&d=$tdate/$i/0\" $tip>&nbsp;&nbsp;</a></span></font></td>";
		} else { 
		    print "<td bgcolor=white class=\"cfree\"><font size=$fsize><span class=\"cc\"><a href=\"$aa&d=$tdate/$i/0\" $tip>&nbsp;&nbsp;</a></span></font></td>";
		}
	    }
	}
	print "</tr>\n";
	print $divider;
    }
    print "</table>\n";
    print "</td></tr></table>";
    if($inpopup) {
	print <<END;
<br><br>
<form><table border=0><tr><td><b><input type=button value="$::phr{'Close'}" onClick="self.close()" class="fmBtnSt"></b></td></tr></table></form>
END
    }
    print "</center><br><br>\n";
    &trailer(0,0);
}
#==============================================================================================
sub findConflictDetail {
  use integer;
  my ($rest, $d, $i, $k, $m, $n, $itv, $cal, $iwho, $stmp, $utmp, $ttmp,$table, $wcode, $tday, $month, $day, $year, $msg,
      $sdate, $tdate, $todayc, $todayc0, $start, $end, $cmin, $title, @dwd, $tmp, $view, $stime, $etime, $smth, $sday, $syr,
      $nday,$nmonth, $nyear, $bcnt, $etmp, $extra, $date, $htb, $percent, $wklen, $ls, %mhash, $total);
  my ($others, @members, $mem, @rmembers, $eMe, $invitee);
  $view= $::calinfo{'v'};
  $ls = $::calinfo{'ls'};
  $iwho = $::calinfo{'w'};

  $stime=$::calinfo{'shour'} || $::calinfo{'hourB'};
  if (not $::o{'hourformat'} and $::calinfo{'sampm'} and $::calinfo{'sampm'} eq 'pm') { $stime += 12 unless $stime eq 12;}
  $etime=$::calinfo{'ehour'} || $::calinfo{'hourE'};
  if (not $::o{'hourformat'} and $::calinfo{'eampm'} and $::calinfo{'eampm'} eq 'pm') { $etime += 12 unless $etime eq 12;}
  if($stime > $etime){ $tmp=$stime; $stime=$etime; $etime=$tmp;}
  $etime++ unless $etime == 24;

  if($::o{'excludeWeekend'}) { $percent=16; $wklen =5;} else { $percent=12; $wklen =7;}

  ($extra, $invitee) = getEditorState();    $extra .= $invitee;

  $etmp = $::calinfo{'smtgp'};
  if(defined $::calinfo{'mattendants'}) {$tmp = $::calinfo{'mattendants'};} else {$tmp="";}
  if($etmp && $etmp ne "$::phr{'none'}") {
      $_=$tmp;
      if( ! /\b$etmp\b/) {
      $tmp .= ":$etmp";
    }
  }
  $tmp =~ s/[,; ]+/:/g;
  $tmp =~ s/:$//g;
  if($::calinfo{'imkey'}) { $eMe = $::calinfo{'imkey'}; $eMe =~ s/_eMe_\d+//g; } 
  elsif($::calinfo{'eme'}) { $eMe = $::calinfo{'eme'};}
  else {$eMe = $iwho;}
  if(!$tmp) { $tmp = $::calinfo{'mg'};}
  $others = expandMeetingGroups($eMe,"$tmp:$iwho", 1);
  if(!$others) { $others = $iwho;}
  my (%hh, @tmem);  %hh= ();
  @members=(); @rmembers=();
  (@tmem) = split(/:/, $others);
  for $mem (@tmem) {
    if( ! exists $hh{$mem}) {
      push @members, $mem;
      $hh{$mem} = 1;
    }
  }
  $date = $::calinfo{'sdate'} || $::calinfo{'d'};
  ($month, $day, $year, $rest) = split(/\//, $date); $month -=1;
  ($smth, $sday, $syr, $rest) =($month, $day, $year);
  $todayc0 = printDate0( $month, $day, $year);
  if($::calinfo{'interval'}) {$itv = $::calinfo{'interval'};} else {$itv=30;}

  $wcode= wday($month, $day, $year);
  if($wcode == 0 && $::o{'weekstart'}) {$wcode = 7;}
  $tday = $day = $day - $wcode;
  $todayc = printDate( $::now{'month'}, $::now{'day'}, $::now{'year'});
  if($tday <= 0) {
    if($month == 0) {
      $month = 11;  $year -= 1; $tday = 31 + $tday;
    } else {
      $month -= 1;
      if($month == 1) { if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}}
      $tday = $::mdays[$month] + $tday;
    }
  }
  my ($zmonth, $zday, $zyear) = canDate($month, $tday+1, $year);
  if($::o{'weekstart'})   { ($nmonth, $nday, $nyear) = ($zmonth, $zday, $zyear);}
  else { ($nmonth, $nday, $nyear) = ($month, $tday, $year);}
  $msg="<font color=#ff0000><b>$::phr{'Week_starts_on'} ".mdy_string($nmonth,$nday,$nyear)."</b></font>";

  # go through all participant's calendar and merge them all into a single table
  $total=0; %mhash=();
  $title="";
  my $who = "";
  my $whoami = $::d{'remote_user'}; my $admin = isadmin($whoami);
  for $mem ( @members) {
    my ($calendar);
    $_ = $mem;
    if(/.+\@.+/ and ! -d "$::o{'spooldir'}/$mem") {
	$tmp = findWhoFromEmail($mem); 
	if($tmp) {$mem = $tmp;}
    }
    next if $mem =~ /\//;
    $mem = untaintname($mem,$::phr{'Invalidusername'});
    $calendar = "$::o{'spooldir'}/$mem";
    @::caldata=();
    if( -d $calendar and -f "$calendar/data") {
      $who = $mem;
      $::d{'ceditor'} = isre($::d{'remote_user'}, $mem, 'any');
      tryReadCache($mem,2,$zmonth, $zday, $zyear);
      my $ispublic;  { my $tmp=getinfo($mem, 'ctype'); if($tmp and $tmp =~ 'public'){$ispublic=1;}};
      my $reader = ($admin or $ispublic or $::d{'ceditor'} or ($whoami eq $mem) or isvgadmin($whoami,$mem) )?1:0; 
      if(!$reader) {
	  my $href;
	  foreach $href (@::caldata) { 
	      my $privacy = $::privacyTable{$href->{'privacy'}};
	      if($privacy < 3) { $href->{'what'} = $::phr{'Protected'};} 
	  }
      }
      
      $title .= " <a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$mem&v=2&d=$smth/$sday/$syr$::vmg\"><span class=\"memberInTitle\">$mem</span></a>";

      my @ary=();  for($d=0; $d < 7; $d++) {  $htb={}; push @ary, $htb;} $mhash{$mem} = \@ary;
      for($d=0; $d < 7; $d++) {
	my ($key, $htb);
	$htb= $ary[$d];
	$m=$tday+$d +$::o{'weekstart'};
	($nmonth, $nday, $nyear) = canDate($month, $m, $year);
	getOneDayEvents($nmonth, $nday, $nyear, $todayc,1);
	for $key (keys %::oneDayEvents) {  $htb->{$key} = $::oneDayEvents{$key}; }
	%::oneDayEvents =();
      }
      $total++;
      push @rmembers, $mem;
    }
  }
  $tmp=join(':', @rmembers);  $tmp =~ s/^:|:$//g; my $zg=""; if(0+@rmembers>1){$zg=$tmp;}
  my $eme= $iwho;
  if($::calinfo{'eme'}) { $eme = $::calinfo{'eme'};}
  $extra="eme=".$eme. "&mg=$tmp&" . $extra;

  my ($prev, $next);
  {
      my ($m,$d,$y) = canDate($smth, $sday-7, $syr); $m++;
      $prev = <<END;
<a href="$::o{'cginame'}?c=docompare&action=cft&w=$iwho&v=$view&ls=$ls&d=$m/$d/$y$::vmg&$extra&cfd=2"><img src="$::o{'imgdirurl'}/rleft.gif" width=10 height=12 border=0 alt=""></a>
END
    ;
      ($m,$d,$y) = canDate($smth, $sday+7, $syr); $m++;
      $next = <<END;
<a href="$::o{'cginame'}?c=docompare&action=cft&w=$iwho&v=$view&ls=$ls&d=$m/$d/$y$::vmg&$extra&cfd=2"><img src="$::o{'imgdirurl'}/rright.gif" width=10 height=12 border=0 alt=""></a>
END
    ;
  }

  &headers($::phr{'ConflictTable'},
	   "function qa(){q=window.open(\"$::o{'cginame'}?c=qa&w=$who&v=$view&ls=$ls&d=$smth/$sday/$syr$::vmg&mg=$zg\",\"qa\", \"scrollbars=yes,resizable=yes,width=600,height=300\");if(window.focus){q.window.focus(); }}",
	   ,undef,1,1);
  print "<center>\n";
  print "<br><font size=+1><b><span class=\"miscTitle\">$::phr{'Calendar'} $::phr{'Conflict'} $::phr{'Table'}</span></b></font><br>";
  print "$title<br>$prev&nbsp;&nbsp;$msg&nbsp;&nbsp;$next $::o{'qadd'}";
  print "<br><br>\n";

  if(not $::calinfo{'cmp'}) {
      $start = $::calinfo{'hourB'};
      if($start > $stime) { $start = $stime;}
      $end = $::calinfo{'hourE'};
      if($end < $etime) { $end = $etime;}
  } else {
      $start = $stime;
      $end = $etime;
  }
  $tmp= ($end - $start) * 60;
  print  "<table border=0 cellpadding=0 cellspacing=0 bgcolor=#999999><tr><td>";
  print  "<table border=0 cellpadding=0 cellspacing=1><tr><td bgcolor=#ff9933 colspan=2><font size=1>&nbsp;</font></td><td>";
  print "<table border=0 cellspacing=0 cellpadding=0 width=$tmp bgcolor=#ff9933><tr>";
  for($i = $start; $i < $end; $i++) {
      print  "<td align=center width=60><font size=-2>".hm_string($i,0)."</font></td>"; 
      print "<td><img src=\"$::o{'imgdirurl'}/b2.gif\" border=0 width=1 height=16></a></td>";
  }
  print "</tr><tr></table></td></tr>";

  my ($ttotal, $nnn, $zz);
  $nnn= ($end - $start) * 12;

  if($total > 1) {$tmp="<br>"; $ttotal=$total+1;} else {$tmp=""; $ttotal = 1;}
  for($d=0; $d < $wklen; $d++) {
      my ($jk, $kj)=("", "");
      if($d&1) { $kj="bgcolor=#ddddee"; $jk="#ddddee";} else {$kj = "bgcolor=#ffffff";}
      $m=$tday+$d+$::o{'weekstart'};
      ($nmonth, $nday, $nyear) = canDate($month, $m, $year);
      $zz = $::o{'weekstart'}+$d;
      $utmp = $::swd[$zz];
      print "<tr><td rowspan=$ttotal $kj><font size=-2 color=#cc00cc>".md_nstring($nmonth+1,$nday)."</font><font size=-2 color=#000000>$tmp&nbsp;<b>$utmp</b></font></td>";
      $utmp = 0;
      my @table = (); $table[$nnn] = 0; for($i = 0; $i < $nnn; $i++) {$table[$i]=0;}
      for $mem (@rmembers) {
          my $aref = $mhash{$mem};
          my $ehref = $aref->[$d];
          if($utmp) { print "<tr>";} $utmp++; $utmp = 1 if $utmp > 13;
	  &getWorkingHourTable($mem);
          &timetable($start, $end, $ehref, $mem, $utmp, $ls, $view, "$nmonth/$nday/$nyear", $extra, $jk, 
		     $total, \@table, 0, $zz);
          print "</tr>";
      }
      if($ttotal > 1) {
	  print "<tr>";
	  &getWorkingHourTable('+_+');
          &timetable($start, $end, undef, $who, 0, $ls, $view, "$nmonth/$nday/$nyear", $extra, $jk, 
		     $total, \@table, 1, $zz);
	  print "</tr>";
      }
      #print "<tr><td colspan=3 bgcolor=$webcalConfig::r{'dkbackground'}><font size=-2><br></font></td></tr>";
  }
  print "</table>";
  print "</td></tr></table>";
  print "</center><br><br>\n";
  &trailer(0,0);
}
sub timetable {
    use integer;
    my ($start, $end, $events, $mem, $cnt, $ls, $view, $date, $extra, $jkclr, $total, $tt, $sum, $zz)=(@_);
    my (@keys, $n, @table, $key, $ihr, $imn, $fhr, $fmn, $i, $psize, $tmp, $k, $kind, @etable, $jnk);
    my ($zbgn, $zend, $za, $zb, $ztmp1, $ztmp2);
    $n = ($end - $start) * 12; $psize = 5* $n;
    @table = (); $table[$n] = 0; for($i = 0; $i < $n; $i++) {$table[$i]=0;}
    @etable = (); $etable[$n] = ""; for($i = 0; $i < $n; $i++) {$etable[$i]="";}
    if(!$sum) {
	@keys = sort sorttime (keys %$events);
	for $key (@keys) {
	    ($ihr, $imn, $fhr, $fmn, $kind, $jnk) = split(/:/, $key);if($kind==4){$ihr=~ s/^\(\d+\)//;}
	    if(intersectTimeinterval($ihr, $imn, $fhr, $fmn, $start, 0, $end, 0)) {
		my ($tcolor, $tim, $smp);
		if($kind == 1) { $tcolor="$::o{'tclra'}"; $tim = hm_hm_string($ihr,$imn,$fhr,$fmn);}
		elsif($kind == 2) { $tcolor="$::o{'tclrt'}"; $tim = hm_string($ihr,$imn);} 
		elsif($kind == 3) { $tcolor="$::o{'tclrm'}"; $tim = hm_hm_string($ihr,$imn,$fhr,$fmn);} 
		if($ihr < $start) { $ihr = $start; $imn=0;}
		if($fhr > $end ) { $fhr = $end; $fmn=60;}
		my ($s, $e, $i);
		$s = (($ihr - $start)*60 + $imn)/5;
		$e = (($fhr - $start)*60 + $fmn)/5; $e=$n if $e>$n;
		for($i=$s; $i<$e; $i++) {$table[$i]=1; $tt->[$i] = 1;}
		$smp = $events->{$key};
		$etable[$s] .= "<font color=$tcolor>$tim: $smp<br><br>"; 
	    }
	}
	#-------------------
	$zbgn = $::WorkingHours[$zz]; $zend = $::WorkingHours[8+$zz];
	$za = $start * 100; $zb = $end * 100;
	if($zbgn > $za) {
	    $fhr = int($zbgn/100); $fmn = $zbgn - $fhr *100;
	    my ($s, $e, $i);
	    $s = 0; $e = (($fhr - $start)*60 + $fmn)/5; $e=$n if $e>$n;
	    for($i=$s; $i<$e; $i++) {$table[$i]=6; $tt->[$i] = 6;}	    
	}
	if($zend < $zb) {
	    $ihr = int($zend/100); $imn = $zend - $ihr *100;
	    my ($s, $e, $i);
	    $s = (($ihr - $start)*60 + $imn)/5; $s=0 if $s<0; $e=$n; 
	    for($i=$s; $i<$e; $i++) {$table[$i]=6; $tt->[$i] = 6;}	    
	} 
	#-------------------
    } else {for($i = 0; $i < $n; $i++) { $table[$i] = $tt->[$i];}} #copy the combined table

    $cnt++;
    my ($cclr, $dclr, $height, $bheight, $dotip);
    if(!$sum) {
	$k=1; $height=12; $bheight=16; $dotip=1;
	if($jkclr) {
	    $cclr= $webcalConfig::r{'usrColors'}->[$cnt];
	    $dclr= "#ddddee";
	} else {
	    $cclr= $webcalConfig::r{'usrColors'}->[$cnt];
	    $dclr= "#FFFFFF";
	}
	if($total > 1) {$tmp="$mem"; } else { $tmp="";}
	print "<td bgcolor=$dclr><font size=-1>$tmp</font></td>";
    } else {
	$k=3; $height=2; $bheight=1; $dotip=0;
	$cclr= "#ff0000";
	$dclr= "#00ff00";
	$jkclr="";
	print "<td><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=11 height=1 border=0></td>";	
    }
    my ($hr, $mn) = ($start, 0);
    print "<td><table width=$psize border=0 cellspacing=0 cellpadding=0 $jkclr><tr>";
    $i = 0; $mn = 0;
    my ($s, $t, $i0, $shr, $smn, $j, $j0, $ww, $xx, $savemn, $tip, $nhr, $nmn);
    while($i < $n) {
	my $etip = "";
        $s = $table[$i];
        $i0 = $i;
        while($table[$i] == $s) { $etip .= $etable[$i]; $i++; if($i == $n) {last;} };
        $t = ($i - $i0) * 5 + $mn;
        $nhr = $hr + $t/60;
        $nmn = $t % 60;
        my ($color, $cmd);
        if($s > 0) { $color=$cclr; $cmd='ctd';} else { $color=$dclr; $cmd="ne";}
	if(!$sum and $s == 6) {$color = $webcalConfig::r{'oColors'}->[6]; if(! $color){ $color=$cclr;}};
        $shr = $hr; $smn = $mn;
        $j = $j0 = $i0; $savemn = $smn;
	if($table[$i0] and $dotip) {
	    my $interval = hm_hm_string($hr,$mn,$nhr, $nmn);
            my $tpid; 
	    if($etip) { $tpid=addtip("$interval <br><br>$etip");}
	    else {$tpid=addtip("$interval<br><br><font color=red><b>$::phr{'OffDutyHours'}</b></font>");}
	    $tip = "onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"";
	} else {$tip = "";}
        while($j < $i) {
            $j++; $smn += 5;
            if($smn == 60) {
                $ww = ($j-$j0)*5;
                $xx = $ww-1;
                $smn = $savemn;
		print "<td bgcolor=$color height=$height width=$ww><a href=\"$::o{'cginame'}?c=$cmd&k=$k&v=$view&ls=$ls&w=$mem&d=$date/$shr/$smn&wa=1$::vmg&$extra\" $tip>";
                print "<img src=\"$::o{'imgdirurl'}/spacer.gif\" border=0 width=$xx height=$height></a>";
                print "<img src=\"$::o{'imgdirurl'}/b2.gif\" border=0 width=1 height=$bheight></a></td>";
                $shr++; 
                $mn = $smn = $savemn=0;   
                $j0 = $j;
            }
        }
        if($j0 != $j) {
            $ww = ($j-$j0)*5;
            $xx = $ww-1;
            $smn = $savemn;
            print "<td bgcolor=$color height=$height width=$ww><a href=\"$::o{'cginame'}?c=$cmd&k=$k&v=$view&ls=$ls&w=$mem&d=$date/$shr/$smn$::vmg&$extra\" $tip>";
            print "<img src=\"$::o{'imgdirurl'}/spacer.gif\" border=0 width=$xx height=$height></a></td>";
        }
        $hr =$nhr;
        $mn = $nmn;
     }
    print "</tr></table></td>\n";
}

sub findConflictCombined {
  my ($rest, $d, $i, $k, $m, $n, $itv, $cal, $iwho, $stmp, $utmp, $ttmp,$table, $wcode, $tday, $month, $day, $year, $msg,
      $sdate, $tdate, $todayc, $todayc0, $start, $end, $cmin, $title, @dwd, $tmp, $view, $stime, $etime, $smth, $sday, $syr,
      @wevents, $nday,$nmonth, $nyear, $bcnt, $etmp, $extra, $date, $htb, $percent, $wklen, $ls);
  my ($others, @members, $mem, $eMe, $mixed, $invitee, $extra0);
  $view= $::calinfo{'v'};
  $ls = $::calinfo{'ls'};
  $iwho = $::calinfo{'w'};
  $stime=$::calinfo{'shour'} || $::calinfo{'hourB'};
  if (not $::o{'hourformat'} and  $::calinfo{'sampm'} eq 'pm') { $stime += 12 unless $stime eq 12;}
  $etime=$::calinfo{'ehour'} || $::calinfo{'hourE'}; 
  if (not $::o{'hourformat'}  and $::calinfo{'eampm'} eq 'pm') { $etime += 12 unless $etime eq 12;}
  $etime++ unless $etime == 24;

  if($::o{'excludeWeekend'}) { $percent=16; $wklen =5;} else { $percent=12; $wklen =7;}

  ($extra0, $invitee) = getEditorState();
  
  $etmp = $::calinfo{'smtgp'};
  if(defined $::calinfo{'mattendants'}) { $tmp = $::calinfo{'mattendants'};} else {$tmp="";}
  if($etmp && $etmp ne "$::phr{'none'}") {
      $_=$tmp;
      if( ! /\b$etmp\b/) {
      $tmp .= ":$etmp";
    }
  }
  $tmp =~ s/[,; ]+/:/g;
  $tmp =~ s/:$//g;
  if($::calinfo{'imkey'}) { $eMe = $::calinfo{'imkey'}; $eMe =~ s/_eMe_\d+//g; } 
  elsif($::calinfo{'eme'}) { $eMe = $::calinfo{'eme'};}
  else {$eMe = $iwho;}
  if(!$tmp) { $tmp = $::calinfo{'mg'};}
  $others = expandMeetingGroups($eMe,"$tmp:$iwho",1);
  if(!$others) { $others = $iwho;}
  my (%hh, @tmem);  %hh= (); $mixed = 0;
  @members=();
  (@tmem) = split(/:/, $others);
  for $mem (@tmem) {
    if( $mem and ! exists $hh{$mem}) {
      push @members, $mem;
      if(getinfo($mem, 'resrc')) { $mixed |= 1;} else { $mixed |= 2; }
      $hh{$mem} = 1;
    }
  }
  $mixed=0 if $mixed != 3; 
  $tmp=join(':', @members);  $tmp =~ s/^:|:$//g; my $zg=""; if(0+@members>1){$zg=$tmp;}
  $extra="mg=$tmp&" . $extra0 . $invitee;
  $date = $::calinfo{'sdate'} || $::calinfo{'d'};
  ($month, $day, $year, $rest) = split(/\//, $date); $month -=1;
  ($smth, $sday, $syr) = ($month, $day, $year);
  $todayc0 = printDate0( $month, $day, $year);
  if($::calinfo{'interval'}) {$itv = $::calinfo{'interval'};} else {$itv=30;}
  @wevents=();
  $wcode= wday($month, $day, $year);
  if($wcode == 0 && $::o{'weekstart'}) {$wcode = 7;}
  $tday = $day = $day - $wcode;
  $todayc = printDate( $::now{'month'}, $::now{'day'}, $::now{'year'});
  if($tday <= 0) {
    if($month == 0) {
      $month = 11;  $year -= 1; $tday = 31 + $tday;
    } else {
      $month -= 1;
      if($month == 1) { if(isleap($year)) { $::mdays[1] = 29;} else { $::mdays[1] = 28;}}
      $tday = $::mdays[$month] + $tday;
    }
  }

  my ($zmonth, $zday, $zyear) = canDate($month, $tday+1, $year);
  if($::o{'weekstart'})   { ($nmonth, $nday, $nyear) = ($zmonth, $zday, $zyear);}
  else { ($nmonth, $nday, $nyear) = canDate($month, $tday, $year);}
  $msg="<font color=#ff0000><b>$::phr{'Week_starts_on'} ".mdy_string($nmonth,$nday,$nyear)."</b></font>";

  # initialize an empty event table
  for($d=0; $d < 7; $d++) {  $htb={};    push @wevents, $htb;  }

#---------
  my @WorkingHours=(0,0,0,0,0,0,0,0,2500,2500,2500,2500,2500,2500,2500,2500);
#---------
  # go through all participant's calendar and merge them all into a single table
  my $who="";
  $title="";
  my $whoami = $::d{'remote_user'}; my $admin = isadmin($whoami);
  my $nusers = 0+@members;
  for $mem (@members) {
    my ($calendar);
    $_ = $mem;
    if(/.+\@.+/ and ! -d "$::o{'spooldir'}/$mem" ) {
	$tmp = findWhoFromEmail($mem); 
	if($tmp) {$mem = $tmp;}
    }
    next if $mem =~ /\//;
    $mem = untaintname($mem,$::phr{'Invalidusername'});
    $calendar = "$::o{'spooldir'}/$mem";
    @::caldata=();
    if( -d $calendar and -f "$calendar/data") {
      if($who eq "") { $who = $mem;}
      $::d{'ceditor'} = isre($::d{'remote_user'}, $mem, 'any');
      tryReadCache($mem,2,$zmonth, $zday, $zyear);
      my $ispublic;  { my $tmp=getinfo($mem, 'ctype'); if($tmp and $tmp =~ 'public'){$ispublic=1;}};
      my $reader = ($admin or $ispublic or $::d{'ceditor'} or ($whoami eq $mem) or isvgadmin($whoami,$mem))?1:0; 
      if(!$reader) {
	  my $href;
	  foreach $href (@::caldata) { 
	      my $privacy = $::privacyTable{$href->{'privacy'}};
	      if($privacy < 3) { $href->{'what'} = $::phr{'Protected'};}
	  }
      }
      $title .= " <a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$mem&v=2&d=$smth/$sday/$syr$::vmg\">$mem</a>";

      for($d=0; $d < 7; $d++) {
	my ($key, $htb);
	$htb= $wevents[$d];
	$m=$tday+$d +$::o{'weekstart'};
	($nmonth, $nday, $nyear) = canDate($month, $m, $year);
	getOneDayEvents($nmonth, $nday, $nyear, $todayc);
	if($nusers > 1) {
	    for $key (keys %::oneDayEvents) {
		$htb->{$key} ="<FoNt CoLoR=#0000Ff>$mem:</FoNt> " . $::oneDayEvents{$key};
	    }
	} else {
	    for $key (keys %::oneDayEvents) {
		$htb->{$key} = $::oneDayEvents{$key};
	    }
	}
	%::oneDayEvents =();
     }
      $::d{'ceditor'}="";
   }
    #------------
    if( -d $calendar and -f "$calendar/WorkingHours") {    
        doReadFile("$calendar/WorkingHours");
	my $i;
	for($i=0; $i<7; $i++) {
	    if($::WorkingHours[$i] > $WorkingHours[$i]) { $WorkingHours[$i] = $::WorkingHours[$i];}
	    if($::WorkingHours[8+$i] < $WorkingHours[8+$i]) { $WorkingHours[8+$i] = $::WorkingHours[8+$i];}
	}
	$WorkingHours[7] = $WorkingHours[0]; $WorkingHours[15] = $WorkingHours[8];
       }
    }
    #------------
  my $script="function qa(){q=window.open(\"$::o{'cginame'}?c=qa&w=$who&v=$view&ls=$ls&d=$smth/$sday/$syr$::vmg&mg=$zg\",\"qa\", \"scrollbars=yes,resizable=yes,width=600,height=300\");if(window.focus){q.window.focus(); }}",
  
  $stmp="";
  for($d=0; $d < $wklen; $d++) {
    $m=$tday+$d+$::o{'weekstart'};
    ($nmonth, $nday, $nyear) = canDate($month, $m, $year); $nmonth++;
    $tmp="<font size=-2 color=#cc00cc>&nbsp;".md_nstring($nmonth,$nday)."</font>";
    $utmp = $::swd[$::o{'weekstart'}+$d];
    $stmp .= "<td noWrap width=\"$percent%\">$utmp $tmp</td>";
  }

  $table= "
<table border=0 cellpadding=0 cellspacing=0  bgcolor=\"#c0cccf\" width=\"60%\"><tr><td width=\"100%\" bgcolor=\"#c0cccf\">
<table border=0 cellpadding=0 cellspacing=1 width=\"100%\">
<tr bgcolor=$webcalConfig::r{'backgroundColor'}><td><font size=-1>&nbsp;</font></td>$stmp</tr>";
  if(not $::calinfo{'cmp'}) {
      $start = $::calinfo{'hourB'};
      if($start > $stime) { $start = $stime;}
      $end = $::calinfo{'hourE'};
      if($end < $etime) { $end = $etime;}
  } else {
      $start = $stime;
      $end =$etime;
  }
  my ($ztmp, $ztmp1, $ztmp2, $zbgn, $zend, $zz);
  for($i = $start; $i < $end; $i++) {
    $ttmp=""; $ztmp = $i * 100;
    for($n=0; $n < 60; $n +=$itv) {
      $ttmp .= "<tr><td align=center bgcolor=$webcalConfig::r{'backgroundColor'}><font size=-1>".hm_string($i,$n)."</font></td>";
      $ztmp1 = $ztmp + $n; $ztmp2 = $ztmp1 +$itv;
      for($d=0; $d < $wklen; $d++) {
	$zz = $d+$::o{'weekstart'};
        $m=$tday+$zz;
	$tdate= printDate0($month, $m, $year);
	$zbgn = $WorkingHours[$zz]; $zend = $WorkingHours[8+$zz];
	# compute the busy count
	$bcnt = 0;
	my $tip = "";
	{
	    my ($htb, $key, $ihr, $imn, $fhr, $fmn, $owner, $kind, $jnk);
	    $htb= $wevents[$d];
	    for $key (keys %{$htb}) {
		($ihr, $imn, $fhr, $fmn, $kind, $jnk) = split(/:/, $key); if($kind==4){$ihr=~ s/^\(\d+\)//;}
		my $tmp = intersectTimeinterval($ihr, $imn, $fhr, $fmn, $i, $n, $i, $n+$itv);
		if($tmp) {
		    my ($tcolor, $tim);
		    $bcnt += $tmp;
		    if($kind == 1) { $tcolor="$::o{'tclra'}"; $tim = hm_hm_string($ihr,$imn,$fhr,$fmn);}
		    elsif($kind == 2) { $tcolor="$::o{'tclrt'}"; $tim = hm_string($ihr,$imn);} 
		    elsif($kind == 3) { $tcolor="$::o{'tclrm'}"; $tim = hm_hm_string($ihr,$imn,$fhr,$fmn);} 
                    else {$tim="****";}    my $smp = $htb->{$key};
		    $tip .= "<font color=$tcolor>$tim:</font> $smp<br><br>";
		}
	    }
	}
	my $bgc = "";
	if( $ztmp2 <= $zbgn or $ztmp1 >= $zend) { 
	    my $img; if ($bcnt == 0) { $bcnt = 6; $img="mask.gif";} else { $img="mask1.gif";}
	    $bgc = "background=\"$::o{'imgdirurl'}/$img\" bgcolor=\"\"";
	}
	if($tip) { 
	    my $tpid = addtip($tip);  
	    $tip = "onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"";
	}
	$k=$bcnt;
	my $md;
	if($k || $mixed) { $md = 'ctd';} else {$md = 'ne';}
	if($tdate eq $todayc0) {
	  my $cclr= $webcalConfig::r{'otColors'}->[$k];
	  $cclr = $webcalConfig::r{'otColors'}->[5] if !defined $cclr;
	  if(!$bgc) { $bgc = "bgcolor=$cclr";}
	  $ttmp .= "<td $bgc align=center>
<a href=\"$::o{'cginame'}?c=$md&k=3&v=$view&ls=$ls&w=$iwho&d=$tdate/$i/$n$::vmg&$extra\" $tip><font size=-1 color=$cclr>&nbsp; &nbsp; &nbsp; &nbsp;</font></a></td>";
      } else {
	  my $cclr= $webcalConfig::r{'oColors'}->[$k];
	  $cclr = $webcalConfig::r{'oColors'}->[5] if !defined $cclr;
	  if(!$bgc) { $bgc = "bgcolor=$cclr";}
	  $ttmp .= "<td $bgc align=center>
<a href=\"$::o{'cginame'}?c=$md&k=3&v=$view&ls=$ls&w=$iwho&d=$tdate/$i/$n$::vmg&$extra\" $tip><font size=-1 color=$cclr>&nbsp; &nbsp; &nbsp; &nbsp;</font></a></td>";
        }
      }
      $ttmp .= "</tr>\n";
      if($i == $end) { last;}
    }
    $table .= $ttmp . "\n";
  }
  $table .= "</table></td></tr></table>\n";

  my ($prev, $next);
  {
      my ($m,$d,$y) = canDate($smth, $sday-7, $syr); $m++;
      $prev = <<END;
<a href="$::o{'cginame'}?c=docompare&action=cft&w=$iwho&v=$view&ls=$ls&d=$m/$d/$y$::vmg&$extra&cfd=1"><img src="$::o{'imgdirurl'}/rleft.gif" width=10 height=12 border=0 alt=""></a>
END
    ;
      ($m,$d,$y) = canDate($smth, $sday+7, $syr); $m++;
      $next = <<END;
<a href="$::o{'cginame'}?c=docompare&action=cft&w=$iwho&v=$view&ls=$ls&d=$m/$d/$y$::vmg&$extra&cfd=1"><img src="$::o{'imgdirurl'}/rright.gif" width=10 height=12 border=0 alt=""></a>
END
    ;
  }


  &headers($::phr{'ConflictTable'},$script,undef,1,1);
  print "<center>\n";
  print "<br><font size=+1><b><span class=\"miscTitle\">$::phr{'Calendar'} $::phr{'Conflict'} $::phr{'Table'}</span></b></font><br>";
  print "$title<br>$prev&nbsp;&nbsp;$msg&nbsp;&nbsp;$next $::o{'qadd'}";
  print "<br><br>\n";
  print $table;
  print "</center><br>\n";
  &trailer(0,0);
}


#==============================================================================================
sub domodify {
  my ($tag, $href, $tmp, $who, $author, $others, $hasmme, $themme, $mkey, $msg, $isauthor, $isoauthor, $theE);
  my $kind = 0;
  $who = $::calinfo{'w'};
  $tag = $::calinfo{'t'};
  $hasmme = $themme = $isauthor=$isoauthor=$theE=0;
  $mkey=""; $msg="";

  my ($FHANDLE) = (@_);

  if($::d{'authResult'} == 4) {
    for $href (@::caldata) {
      if( $href->{'key'} == $tag) {
	$kind = $href->{'kind'}; $theE=$href;
        $author = $href->{'author'};        
	$isauthor = ismember($::d{'remote_user'}, $author);
        $isoauthor = 1 if $isauthor == 1;
	if(exists $href->{'mkey'}) { $mkey= $::calinfo{'mkey'} = $href->{'mkey'};}
	if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
	$href->{'deleted'} = 1;
	if(isadmin($::d{'remote_user'}) or isvgadmin($::d{'remote_user'}, $who)){ $isauthor=$isoauthor = 1;}
	last;
      }
    }
  } else {
    if( $::d{'ispublic'} ) {
      for $href (@::caldata) {
	if( $href->{'key'} == $tag) {
	    $author = $href->{'author'};
            $isauthor = ismember($::d{'remote_user'}, $author);
            $isoauthor = 1 if $isauthor == 1;
            if($isauthor) {
                $kind = $href->{'kind'}; $theE=$href;
                if(exists $href->{'mkey'}) { $mkey=$::calinfo{'mkey'} = $href->{'mkey'};}
                if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
                $href->{'deleted'} = 1;
                $::d{'authResult'} = 4 if $isoauthor;
            }
            last;
	}
      }
    }
    if($::d{'authResult'} != 4) {
      $author="";
      for $href (@::caldata) {
	if( $href->{'key'} == $tag) {
          $author = $href->{'author'};
	  $isauthor = ismember($::d{'remote_user'}, $author);
	  $isoauthor = 1 if $isauthor == 1;
	  $kind = $href->{'kind'}; $theE=$href;
	  if(1) {
	    if(exists $href->{'mkey'}) { $mkey= $::calinfo{'mkey'} = $href->{'mkey'};}
	    if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
	    $others=$href->{'attendants'};
	    $href->{'deleted'} = 1;
	  }
	  last;
	}
      }
      # allow edit if
      # 1) remote_user is author or
      # 2) the event is taged editable by participants and remote_user is a member
      if($mkey) {
	$mkey =~ s/_eMe_\d+//g;
	if(isre($::d{'remote_user'}, $mkey, 'editors') or $isoauthor) {
	    $::d{'authResult'} = 4; $::is_authorized_author=8;
	} elsif ($hasmme) {
	  if($themme) {
	    $others =~ s/[,; ]+/:/g;
	    $others =~ s/:$//g;
	    $others = expandMeetingGroups($mkey, $others);
	    if(ismember($::d{'remote_user'}, $others)) { $::d{'authResult'} = 4; $::is_authorized_author=$themme;}
	  }  
        }
      }
    }
  }
  if($::d{'authResult'} != 4) { 
      return (1, "$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToModify'} ($who).");  
  }
  else {
      # It's getting complicated
      # only the owner of the event can change the 'mme' field. Other fields may be modified
      # by group members, or its authors if the calendar is a public calendar.
      $mkey =~ s/_eMe_\d+//g;
      if($mkey and !isre($::d{'remote_user'}, $mkey, 'editors') and $isoauthor == 0) {
	  if($themme == 0) { 
	      my $tmp = "<br>Only '$mkey' is allowed to modify this entry";
	      return (1, "$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToModify'} ($mkey). $tmp");
	  }
	  if($themme != $::calinfo{'imme'}) {
	      $msg = "<font color=#ff0000>Warning: Only '$mkey' is allowed to modify the <b>\"$::phr{'Participants_are_allowed_to'}\"</b> field</font>";
	  }
	  $::calinfo{'imme'} = $themme;
      }
  }
  if($theE){ $::lastOldEvent=copyTask($theE);}
  if( ! $::is_authorized_author ) {
      if($isoauthor) { $::is_authorized_author =  8;}
      elsif($isauthor) { $::is_authorized_author =  4;}
  }

  if($::calinfo{'octd'}) {
      my ($oedate, $date);  
      $oedate = $::calinfo{'oedate'};
      $date = $::calinfo{'sdate'};	# in mm/dd/yy format
      if($date eq $oedate) {
	  $::calinfo{'ctd'} = $::calinfo{'octd'};
      } 
  }

  if($::calinfo{'octds'}) {
      my ($oedate, $date);
      $oedate = $::calinfo{'oedate'};
      $date = $::calinfo{'sdate'};	# in mm/dd/yy format
      if($date eq $oedate) {
	  $::calinfo{'ctds'} = $::calinfo{'octds'};
      }
  }

  if($::calinfo{'oexception'}) {  
      my ($nocc, $nrep, $oocc, $orep, $excep, $tmp, $oedate, $date);
      $oedate = $::calinfo{'oedate'};
      $date = $::calinfo{'sdate'};	# in mm/dd/yy format
      if($date eq $oedate) {
	  $nocc = $::calinfo{'occurs'};	  $nrep = $::calinfo{'repeat'};
	  ($oocc, $orep, $excep) = split(/:/, $::calinfo{'oexception'});
	  if($nocc eq $oocc and $nrep >= $orep) {
	      $::calinfo{'exception'} = $excep;
	  }
      }
  }

  if($::calinfo{'orecurr'}) {
      my ($date, $oedate, $oocc,$rep, $orep, $nocc, $nrep, $tmp);
      $oedate = $::calinfo{'oedate'};
      $date = $::calinfo{'sdate'};	# in mm/dd/yy format
      if($date eq $oedate) {
	  ($oocc, $rep, $orep) = split(/:/, $::calinfo{'orecurr'});
	  $nocc = $::calinfo{'occurs'};	  $nrep = $::calinfo{'repeat'};
	  if($nocc eq $oocc and $nrep == $rep) { $::calinfo{'orepeat'} = $orep;}
      }
  }
  my ($ir0, $sr0, $ir1, $sr1) = &doinsert($msg,0, $FHANDLE);
  return ($ir0, $sr0, $ir1, $sr1);
}

sub deleteAll {
  my ($tag, $who, $href, $mkey, $kind, $others, $hasmme, $themme, $isauthor, $isoauthor, $theE);
  $who = $::calinfo{'w'};
  $mkey = ""; $others="";
  $hasmme=$themme=$isauthor=0;$isoauthor=$theE=0;

  my ($FHANDLE) = (@_);

  if($::d{'authResult'} == 4) {
    $tag = $::calinfo{'t'};
    for $href (@::caldata) {
      if( $href->{'key'} == $tag) {
	$kind = $href->{'kind'};
	$isauthor = ismember($::d{'remote_user'}, $href->{'author'});
	if(exists $href->{'mkey'}) {
            $mkey = $::calinfo{'mkey'} = $href->{'mkey'};
            $isoauthor =  1 if $isauthor == 1 ;
        }
	if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
	$others=$href->{'attendants'};
	$href->{'deleted'} = 1; $theE=$href;
	if(isadmin($::d{'remote_user'}) or isvgadmin($::d{'remote_user'}, $who)){ $isauthor=$isoauthor = 1;}
	last; }
    }
  } else {
    $tag = $::calinfo{'t'};
    if( $::d{'ispublic'} ) {
      for $href (@::caldata) {
	if( $href->{'key'} == $tag) {
          $isauthor =ismember($::d{'remote_user'}, $href->{'author'});
          $isoauthor =  1 if $isauthor == 1 ;
	  if($isauthor) {
	    $kind = $href->{'kind'};
	    if(exists $href->{'mkey'}) {
                $mkey = $::calinfo{'mkey'} = $href->{'mkey'};
            }
	    if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
	    $others=$href->{'attendants'};
	    $href->{'deleted'} = 1; $theE=$href;
	    $::d{'authResult'} = 4 if $isoauthor;
          }
	  last;
	}
      }
    }
    if($::d{'authResult'} != 4) {
      $kind = 0;
      for $href (@::caldata) {
	if( $href->{'key'} == $tag) {
	  $kind = $href->{'kind'};
	  if(1) {
	    if(exists $href->{'mkey'}) {
                $mkey = $::calinfo{'mkey'} = $href->{'mkey'};
                $isauthor = ismember( $::d{'remote_user'}, $href->{'author'});
                $isoauthor =  1 if $isauthor == 1 ;
            }
	    if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
	    $others=$href->{'attendants'};
	    $href->{'deleted'} = 1; $theE=$href;
	  }
	  last;
	}
     }
      # meeting event. allow deletion if
      # 1) remote_user is author or
      # 2) the event is taged editable by participants and remote_user is a member
      if($mkey) {
	my $tkey= $mkey;
	$tkey =~ s/_eMe_\d+//g;
	if(isre($::d{'remote_user'}, $tkey, 'editors') or $isoauthor) {
	    $::d{'authResult'} = 4; $::is_authorized_author=8;
	} elsif ($hasmme) {
	  if($themme > 1) {	# allow deletion
	    my $att = $others;
	    $att =~ s/[,; ]+/:/g;
	    $att =~ s/:$//g;
	    $att = expandMeetingGroups($tkey, $att);
	    if(ismember($::d{'remote_user'}, $att)) { $::d{'authResult'} = 4; $::is_authorized_author=$themme;}
	  }
	}
      }
    }
  }

  if( $::d{'authResult'} != 4) { return (1, "$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToModify'} ($who).");}
  else {
    if( ! $::is_authorized_author ) {
	if($isoauthor) { $::is_authorized_author =  8;}
	elsif($isauthor) { $::is_authorized_author =  4;}
    }
    my $message="";
    $::calinfo{'deleted'} = 1; if($theE) {$::lastOldEvent = copyTask($theE);}
    if($mkey && $others) {
      my ($tmk);
      my $att = $others;
      $att =~ s/[,; ]+/:/g;
      $tmk = $mkey;
      $tmk =~ s/_eMe_\d+//g;
      $att = expandMeetingGroups($tmk, $att);
      if( ! $::is_authorized_author ) { $::is_authorized_author = $themme if &ismember($::d{'remote_user'}, $att);}
      if($tmk eq "$::d{'remote_user'}" or $isoauthor or (ismember($::d{'remote_user'}, $att) and $themme > 1)) {
	$att =~ s/$who//g;
	$att =~ s/:+/, /g;
	$att =~ s/^,//g;
	$att =~ s/, $//g;
        $themme += $isoauthor;
	$message = "$::phr{'Updated_calendars'}<br>$att";
      } else  {
	$att =~ s/$who//g;
	$att =~ s/:+/, /g;
	$att =~ s/^,//g;
	$att =~ s/, $//g;
	$message = "($::d{'remote_user'}) $::phr{'NotAllowedToUpdate'}<br>$att.";
      }
    }
    my ($ir0, $sr0, $ir1, $sr1) = &doinsert($message,0, $FHANDLE);
    if(! defined  $ir1 or ! defined $sr1) { $ir1=0; $sr1="";}
    my ($ir2, $sr2) = (0, "");
    if($mkey && $others && $ir0 != 1 && $ir1 == 0) { ($ir2, $sr2) = &fixMeetingEntry($mkey, $themme, $others, 1, -1, "");  }
    return($ir0, $sr0, $ir1+$ir2, $sr1 . $sr2);
  }
  return (0,"");
}
#==============================================================================================================
sub newrepeat {
    use integer;
    my ($href, $date) = (@_);
    my ($occurs, $occ, $modulo, $twday, $wday, $nth, $wdaymask, $edate, $dm, $dd, $dy, $tm, $td, $ty, $ans);

    $edate = $href->{'date'};
    ($dm, $dd, $dy) = split(/\//, $edate);	#setup date
    ($tm, $td, $ty) = split(/\//, $date);	#date to exclude
    $tm--; $dm--;

    $ans = 0;
    $occurs = $href->{'occurs'};
    if( substr($occurs,0,1) eq 'Z' and $occurs =~ /^Z(.+),(\d+),(\d*)/) {
	my ($word, $c1, $c2)= ($1, $2, $3);
	my ($tmp, $cnt);
	if($word eq 'D') {
	    $nth = ndays($tm, $td, $ty, $dm, $dd, $dy);
	    $ans = ($nth-1+$c1)/$c1;
	} elsif($word eq 'MD') {
	    $tmp = nmonths($tm, $ty, $dm, $dy);
	    $cnt = ($tmp -1)/$c1;	    
	    $ans = $cnt + 1;
	} elsif($word eq 'MWD' or $word eq 'MND' or $word eq 'MNW' ) {
	    $tmp = nmonths($tm, $ty, $dm, $dy);
	    my $cnt = ($tmp -1)/$c1;
	    $ans = $cnt + 1;
	} elsif($word eq 'W') {
	    my @maskary = wdayoffsets($c2); $wdaymask=$c2; 
	    $twday = wday($tm, $td, $ty);
	    $wday =  wday($dm, $dd, $dy);
	    $nth = ndays($tm, $td, $ty, $dm, $dd, $dy);
	    my $wknum = ($nth+$wday-$twday)/7;
	    $cnt = $wknum / $c1;
	    $ans = $cnt * $maskary[9] + $maskary[3+$twday];
	} elsif($word eq 'X') {
	    $twday = wday($tm, $td, $ty);	# weekday for today
	    $nth = ndays($tm, $td, $ty, $dm, $dd, $dy);
	    my $nwks = ($nth-1)/7;
	    my $nwdays = $nwks * 5 + ($twday - $c2); if($twday <$c2) {$nwdays += 5;}
	    $ans = 1+($nwdays / $c1);
	}
        $ans=0 if $ans < 0; 
	return $ans;
    }
    my $oaref = $::occurenceHash{$occurs};
    if($oaref) {
	$occ = $oaref->[0];
	$modulo = $oaref->[1];
	$wdaymask = $oaref->[2];
    } else { $occ = $modulo = $wdaymask=0;}

    if($modulo) {			# repeats at integral number of days
	$nth = ndays($tm, $td, $ty, $dm, $dd, $dy);
	$ans = ($nth-1+$modulo)/$modulo;
    } elsif ($wdaymask) {		# not on all weekdays
	$twday = wday($tm, $td, $ty);
	$wday =  wday($dm, $dd, $dy);
	$nth = ndays($tm, $td, $ty, $dm, $dd, $dy);
	my $aref = $::occurenceHash{$occurs};
	$ans = (($nth+$wday-$twday)/7) * $aref->[9] + $aref->[3+$twday];
    } elsif ($occ == 5) {		#elsif ($occurs eq "MonthlyByDate")
	#if($td != $dd) { return 0; }
	$ans = nmonths($tm, $ty, $dm, $dy);
    } elsif ($occ == 6) {		#elsif ($occurs eq "MonthlyByWeekday")
	$ans = nmonths($tm, $ty, $dm, $dy);
    } elsif ($occ == 7) {		#elsif ($occurs eq "Yearly")
	$ans = $ty - $dy + 1;
    } elsif ($occ == 11) {		#elsif ($occurs eq "YearlyByMonthWeekday")
	$ans = $ty - $dy + 1;
    }
    $ans=0 if $ans < 0; 
    return $ans;
}
#==============================================================================================================
sub newExceptionString {
    my ($exception, $ncnt) =(@_);
    my ($str, $length, $i, $tmp);
    $str = "";
    if($exception) {
	my $length = 0+@{$exception};
	for($i=0; $i < $length; $i++) {
	    $tmp=$exception->[$i];
	    if(abs($tmp) <= $ncnt) { $str .= "$tmp,";}
	}
	$str =~ s/,$//g;
    }
    if($str) { return "[$str]";} 
    return "";
}
#==============================================================================================================
sub deleteForward {
  my ($tag, $who, $href, $mkey, $kind, $others, $hasmme, $themme, $date, $isauthor, $isoauthor);
  my ($ssM, $ssD, $ssY, $rest, $newrepeat, $exceptionString, $enddate, $theE);
  $date = $::calinfo{'sdate'};

  my ($FHANDLE) = (@_);

  $who = $::calinfo{'w'};
  $mkey = ""; $others=""; $exceptionString="";
  $newrepeat = -1;
  $hasmme=$themme=$isauthor=0; $isoauthor=0;
  $tag = $::calinfo{'t'};
  if($::d{'authResult'} == 4) {
    for $href (@::caldata) {
      if( $href->{'key'} == $tag) {
	$kind = $href->{'kind'}; 
	$isauthor = ismember( $::d{'remote_user'},$href->{'author'});
	if(exists $href->{'mkey'}) {
            $mkey = $::calinfo{'mkey'} = $href->{'mkey'};
            $isoauthor = 1 if $isauthor == 1; 
        }
	if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
	$others=$href->{'attendants'};
	$newrepeat = &newrepeat($href, $date); if($newrepeat) { $newrepeat -- ;}
	$exceptionString=newExceptionString($href->{'exception'}, $newrepeat);
	if($exceptionString) { $href->{'exception'} = eval $exceptionString;}
	else { delete $href->{'exception'};}
	$href->{'repeat'} = $newrepeat;
	{
	    my ($ssm,$ssd, $ssy)=split(/\//, $href->{'date'}); $ssm -=1;
	    $href->{'end'} = findEndDate($ssm,$ssd,$ssy,$href->{'occurs'},$newrepeat);
	}
	$theE=$href;
	if(isadmin($::d{'remote_user'}) or isvgadmin($::d{'remote_user'}, $who)){ $isauthor=$isoauthor = 1;}
	last; 
      }
    }
  } else {
    if( $::d{'ispublic'} ) {
      for $href (@::caldata) {
	if( $href->{'key'} == $tag) {
         $isauthor =ismember( $::d{'remote_user'},$href->{'author'});
         $isoauthor = 1 if $isauthor == 1;
         if($isauthor) {
	    $kind = $href->{'kind'};
	    if(exists $href->{'mkey'}) {
                $mkey = $::calinfo{'mkey'} = $href->{'mkey'};

            }
	    if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
	    $others=$href->{'attendants'};
	    $::d{'authResult'} = 4;
	    if($newrepeat < 0) {$newrepeat = &newrepeat($href, $date); if($newrepeat) { $newrepeat -- ;}}
	    $exceptionString=newExceptionString($href->{'exception'}, $newrepeat);
	    if($exceptionString) { $href->{'exception'} = eval $exceptionString;}
	    else { delete $href->{'exception'};}
	    $href->{'repeat'} = $newrepeat;
	    {
		my ($ssm,$ssd, $ssy)=split(/\//, $href->{'date'}); $ssm -=1;
		$href->{'end'} = findEndDate($ssm,$ssd,$ssy,$href->{'occurs'},$newrepeat);
	    }
	    $theE=$href;
	 }
	 last;
	}
      }
    }
    if($::d{'authResult'} != 4) {
      $kind = 0;
      for $href (@::caldata) {
	if( $href->{'key'} == $tag) {
	  $kind = $href->{'kind'};
	  if(1) {
	    if(exists $href->{'mkey'}) { 
                $mkey = $::calinfo{'mkey'} = $href->{'mkey'};
                $isauthor = ismember( $::d{'remote_user'}, $href->{'author'});
                $isoauthor = 1 if $isauthor ==1 ; 
            }
	    if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
	    $others=$href->{'attendants'};
	    if($newrepeat < 0) {$newrepeat = &newrepeat($href, $date);if($newrepeat) { $newrepeat -- ;}}
	    $exceptionString=newExceptionString($href->{'exception'}, $newrepeat);
	    if($exceptionString) { $href->{'exception'} = eval $exceptionString;}
	    else { delete $href->{'exception'};}
	    $href->{'repeat'} = $newrepeat;
	    {
		my ($ssm,$ssd, $ssy)=split(/\//, $href->{'date'}); $ssm -=1;
		$href->{'end'} = findEndDate($ssm,$ssd,$ssy,$href->{'occurs'},$newrepeat);
	    }
	    $theE=$href;
	  }
	  last;
      }
    }
      # meeting event. allow deletion if
      # 1) remote_user is author or
      # 2) the event is taged editable by participants and remote_user is a member
      if(1) {
	my $tkey= $mkey;
	$tkey =~ s/_eMe_\d+//g;
	if(isre($::d{'remote_user'}, $tkey, 'editors') or $isoauthor) { 
	    $::d{'authResult'} = 4; $::is_authorized_author=8;
	} elsif ($hasmme) {
	  if($themme > 1) {	# allow deletion
	    my $att = $others;
	    $att =~ s/[,; ]+/:/g;
	    $att =~ s/:$//g;
	    $att = expandMeetingGroups($tkey, $att);
	    if(ismember($::d{'remote_user'}, $att)) { $::d{'authResult'} = 4; $::is_authorized_author=$themme;}
	}
        }
      }
     }
  }
  if( $::d{'authResult'} != 4) { return (1, "$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToModify'} ($who).");}
  else {
    my $message="";
    my $doit = 1;
    $::calinfo{'deleted'} = 1; 
    if($mkey && $others) {
      if( ! $::is_authorized_author ) {
	  if($isoauthor) { $::is_authorized_author =  8;}
	  elsif($isauthor) { $::is_authorized_author =  4;}
      }
      my ($tmk);
      my $att = $others;
      $att =~ s/[,; ]+/:/g;
      $tmk = $mkey;
      $tmk =~ s/_eMe_\d+//g;
      $att = expandMeetingGroups($tmk, $att);
      if( ! $::is_authorized_author ) { $::is_authorized_author = $themme if &ismember($::d{'remote_user'}, $att);}
      if(isre("$::d{'remote_user'}",$tmk, 'editors') or $isoauthor or (ismember($::d{'remote_user'}, $att) and $themme > 1)) {
	$att =~ s/$who//g;
	$att =~ s/:+/, /g;
	$att =~ s/^,//g;
	$att =~ s/, $//g;
        $themme += $isoauthor;
	$message = "$::phr{'Updated_calendars'}<br>$att";
      } else  {
	$att =~ s/$who//g;
	$att =~ s/:+/, /g;
	$att =~ s/^,//g;
	$att =~ s/, $//g;
	$message = "($::d{'remote_user'}) $::phr{'NotAllowedToUpdate'}<br>$att.";
        $doit = 0;
      }
    }
    if($doit) {
	if($theE){$::lastOldEvent = copyTask($theE);}
        my($ir0, $sr0, $ir1, $sr1) = &doinsert($message,0, $FHANDLE);
	if(! defined  $ir1 or ! defined $sr1) { $ir1=0; $sr1="";}	
	my ($ir2, $sr2) = (0, "");
        if($mkey && $others && $ir0 != 1 && $ir1 == 0) { ($ir2, $sr2) = &fixMeetingEntry($mkey, $themme, $others, -1,  $newrepeat, $exceptionString);}
	return ($ir0, $sr0, $ir1 + $ir2, $sr1 . $sr2);
    } else {
        return (1, "<font color=#009900><b>$::phr{'gEventError'}</b></font> <br><br> $message");
    }
  }
  return(0, ""); # will never be here
}

sub deleteOne {
  use integer;
  my ($who, $tag, $href, $tmp, $exception, $date, $edate, $tm, $td, $ty, $dm, $dd, $dy, $occ, $modulo, $wdaymask, $isoauthor,
	$occurs, $nth, $twday, $wday, $mkey, $kind, $exceptionString, $others, $author, $hasmme, $themme, $isauthor, $theE);
  
  my ($FHANDLE) = (@_);

    $who = $::calinfo{'w'};
    $tag = $::calinfo{'t'};
    $mkey=""; $isauthor=0; $isoauthor = 0;
    if($::d{'authResult'} != 4) {
      if($::d{'ispublic'}) {
	$tag = $::calinfo{'t'};
	for $href (@::caldata) {
	  if( $href->{'key'} == $tag) {
	      $kind = $href->{'kind'};
              $isauthor = ismember( $::d{'remote_user'}, $href->{'author'});
              $isoauthor = 1 if $isauthor == 1; 
	      if($isoauthor) { $::d{'authResult'} = 4;}
              last;
	  }
      }
    }
  }
  if($::d{'authResult'} != 4) {
      $kind = 0; $author=""; $others="";
      $hasmme = $themme = 0;
      for $href (@::caldata) {
	if( $href->{'key'} == $tag) {
	  $kind = $href->{'kind'};
	  if(1) {
            $isauthor = ismember( $::d{'remote_user'}, $href->{'author'});
            $isoauthor = 1 if $isauthor == 1; 
	    if(exists $href->{'mkey'}) { $mkey = $::calinfo{'mkey'} = $href->{'mkey'};}
	    if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
	    $others=$href->{'attendants'};
	    $author = $href->{'author'};
	  }
	  last;
	}
      }
      # meeting event. allow deletion if
      # 1) remote_user is author or
      # 2) the event is taged editable by participants and remote_user is a member
      if(1) {
	my $tkey=$mkey;
	$tkey =~ s/_eMe_\d+//g;
	if(isre($::d{'remote_user'}, $tkey, 'editors') or $isoauthor) {
	    $::d{'authResult'} = 4; $::is_authorized_author=8;
	} elsif ($hasmme) {
	  if($themme > 1 or $isoauthor) {	# allow deletion
	    my $att = $others;
	    $att =~ s/[,; ]+/:/g;
	    $att =~ s/:$//g;
	    $att = expandMeetingGroups($tkey, $att);
	    if(ismember($::d{'remote_user'}, $att)) { $::d{'authResult'} = 4; $::is_authorized_author=$themme;}
	  }
	}
      }
    }
    if($::d{'authResult'} != 4) { return(1, "$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToModify'} ($who).");}

    $::calinfo{'deleted'} = 1;
    $date = $::calinfo{'sdate'};
    $tag = $::calinfo{'t'};
    $kind = 0; $others=""; $theE=0;
    $hasmme = $themme = 0;
    for $href (@::caldata) {
	if( $href->{'key'} == $tag) {
	    my $rcnt = newrepeat($href, $date);
	    if($href->{'exception'}) { $exception = join(',', @{$href->{'exception'}});}
	    else {$exception = ""; }
	    $exception = "$rcnt,$exception";
	    $tmp = "[" . $exception . "]";
	    if ($tmp =~ /^([\[0-9, -\]]*)$/) {
		$tmp = $1;
	    } else {
		calerror("exception $exception",1);
	    }
	    $href->{'exception'} = eval $tmp;

	    $kind = $href->{'kind'};
	    if(exists $href->{'mkey'}) {
                $isauthor = ismember( $::d{'remote_user'}, $href->{'author'});
                if($isauthor == 1) { $isoauthor = 1;}
                $mkey = $::calinfo{'mkey'} = $href->{'mkey'};
            }
	    if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
	    $others = $href->{'attendants'};
	    $exceptionString = $tmp;
	    $theE=$href;
	    last;
	}
    }
  if(isadmin($::d{'remote_user'}) or isvgadmin($::d{'remote_user'}, $who)){ $isauthor=$isoauthor = 1;}
  if( ! $::is_authorized_author ) {
      if($isoauthor) { $::is_authorized_author =  8;}
      elsif($isauthor) { $::is_authorized_author =  4;}
  }
  my $message="";
  my $doit = 1;
  if($mkey && $others) {
    my ($tmk);
    my $att = $others;
    $att =~ s/[,; ]+/:/g;
    $tmk = $mkey;
    $tmk =~ s/_eMe_\d+//g;
    $att = expandMeetingGroups($tmk, $att);
    if( ! $::is_authorized_author ) { $::is_authorized_author = $themme if &ismember($::d{'remote_user'}, $att);}
    if($tmk eq "$::d{'remote_user'}" or $isoauthor or (ismember($::d{'remote_user'}, $att) and $themme > 1)) {
      $att =~ s/$who//g;
      $att =~ s/:+/, /g;
      $att =~ s/^,//g;
      $att =~ s/, $//g;
      $themme += $isoauthor;
      $message = "$::phr{'Updated_calendars'}<br>$att";
    } else  {
      $att =~ s/$who//g;
      $att =~ s/:+/, /g;
      $att =~ s/^,//g;
      $att =~ s/, $//g;
      $message = "($::d{'remote_user'}) $::phr{'NotAllowedToUpdate'}<br>$att.";
      $doit = 0;
    }
  }
  if($doit) {
      if($theE) {$::lastOldEvent = copyTask($theE);}
      my($ir0, $sr0, $ir1, $sr1) = &doinsert($message,0, $FHANDLE);
      if(! defined  $ir1 or ! defined $sr1) { $ir1=0; $sr1="";}
      my($ir2, $sr2) = (0,"");
      if($mkey && $others && $ir0 != 1 && $ir1 == 0) { ($ir2, $sr2)= &fixMeetingEntry($mkey, $themme, $others, 0, -1, "$exceptionString");}
      return ($ir0, $sr0, $ir1 + $ir2, $sr1 . $sr2);
  } else {
      return(1,"<font color=#009900><b>$::phr{'gEventError'}</b></font> <br><br> $message");
  }
  return(0, ""); # will never be here
}
#=====================================================================================================
sub verifyDate {
    my ($date) = (@_); if(not $date) {return("","","","",1);}
    my ($ssM,$ssD, $ssY, $rest)=split(/\//, $date); $ssM -=1; $ssD += 0; $ssY += 0; 
    my $dy=printDate($ssM,$ssD,$ssY);
    my ($ppM, $ppD, $ppY) = split(/\//, $dy);
    my $err="";
    if($ppM - 1 != $ssM or $ppD != $ssD or $ppY != $ssY) {
	$err = "$::phr{'invalid_date'}";
	my $ddate= to_native_date($date);	# convert back to input format
	my $ddy = to_native_date($dy);
	$err .= "($ddate != $ddy) ($date != $dy)";
    }
    return($ssM,$ssD,$ssY,$dy,$err);
}

sub doinsert {
    my ($who, $tmp, $kind, %newentry, $date, $mn,$dy,$yr, $hr, $hrr, $mnn, $href, $role, $mme,$retMsg, $toall,$err,
	$forward,$done, $rest, $stmp, $utmp, $vtmp, $ee, $author, $rurl, $username, $calname, $saved_tag,$saved_seq,
	$me, $ssM, $ssD, $ssY, $bdate, $msg, $imsg, $nextNew, $savedreminder, $occurs, $mkey, $FHANDLE);
    my ($ir1, $sr1) = (0, ""); my $pndmsg="";
    ($imsg, $nextNew, $FHANDLE) = (@_);
    $msg= ""; $retMsg = ""; 
    $::calinfo{'_savedreminder_'} = "";
    $mkey=$me = $who = $::calinfo{'w'};
    if($::d{'authResult'} ne 4) {
      if($::d{'ispublic'}) {
	$::d{'authResult'} = 4;
	if(! $::calinfo{'author'} ) { $::calinfo{'author'} = "$::d{'remote_user'}";}
	elsif(! ismember( $::d{'remote_user'}, $::calinfo{'author'}) ) { $::calinfo{'author'} .= ",$::d{'remote_user'}";}
    }
  }

    # if($::d{'authResult'} ne 4) {calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who).");}
    if($::d{'authResult'} ne 4) { return (1, "$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who).");}
#=======================
    &get_moderated_calendars(); 
#=======================
    $toall= ismember($who, $::o{'corporate_calendar'});
    $mme = 0;
    %newentry=();
#=======================
    my $pending="";
    if($::moderated{$who} and not isre($::d{'remote_user'}, $who, 'editors')) {
	$pending=$newentry{'pnd'}=$who; &markHasPending("$::o{'spooldir'}/$who/pnd");
	$pndmsg .= "calendar \"$who\" is moderated. Event is queued for approval<br>";
    }
    { my ($i,$tmp); for $i (0..5) {$tmp="X$i"; if($::calinfo{$tmp}){$newentry{$tmp}=$::calinfo{$tmp};}}}
#=======================
    $kind = $::calinfo{'k'};		# 1 for appointment and 2 for todo list

    $date = $::calinfo{'sdate'};	# in mm/dd/yy format
    ($ssM,$ssD,$ssY,$dy,$err) = verifyDate($date);
    if($err) { return(1, $err);}
    $date = $dy;

    $author = $::calinfo{'author'};
    if($::calinfo{'rurl'}) {$rurl = $::calinfo{'rurl'};} else {$rurl ="";}
    $username=$::calinfo{'w'};
    if(! $::calinfo{'deleted'}) {
	$newentry{'kind'}= $kind;
	$newentry{'date'}= $date;
	$rurl =~ s/[\\\'\`]//g; $rurl =~ s/^\s+//g; $rurl =~ s/\s+$//g;
	if($rurl ne "") {
	    my (@urls, $a, $b); @urls = split(/\s+/, $rurl); $b="";
	    foreach $a (@urls) {
		if( $a !~ /^[A-Za-z]+:\/\// and $a !~ /\^o\^\//) { $a = 'http://' . $a;}
		if($b) { $b .= " $a";} else { $b = $a;}
	    }
	    $rurl = $b;
	}
	$newentry{'url'}= $rurl;
	if($::calinfo{'r1'}){$newentry{'r1'}= 1;}
	$newentry{'privacy'}= $::calinfo{'eprivacy'};
	if($::calinfo{'fgclr'}) {
	    $tmp = $::calinfo{'fgclr'}; $tmp =~ s/\s|\\|\'|\"|\`//g;  #'"
	    if($tmp) { $newentry{'fg'}=$tmp; }
	}
	if($::calinfo{'bgclr'}) {
	    $tmp = $::calinfo{'bgclr'};   $tmp =~ s/\s|\\|\'|\"|\`//g; #'"
	    if($tmp) { $newentry{'bg'}=$tmp; }
	}
	if($::calinfo{'css'}) {$newentry{'cs'} = $::calinfo{'css'};}
        elsif($::calinfo{'ocss'}) {$newentry{'cs'} = $::calinfo{'ocss'};}

	if($::calinfo{'cp'}) {$newentry{'cp'} = $::calinfo{'cp'};}
	
	if($::calinfo{'cbg'}) {
	    $tmp = $::calinfo{'cbg'};  $tmp =~ s/^\s+|\\|\'|\"|\`|\s+$//g; #'"
	    if($tmp) { $newentry{'cbg'}=$tmp; }
	}

	if($::calinfo{'ctp'}) {$tmp = $::calinfo{'ctp'}; $tmp =~ s/\\//g; $tmp=~ s/\'/\\\'/g; $newentry{'ctp'} = $tmp;}
	if($::calinfo{'ctm'}) {$tmp = $::calinfo{'ctm'};   $tmp =~ s/\\//g; $tmp=~ s/\'/\\\'/g; $newentry{'ctm'} = $tmp;}
        if(defined $::calinfo{'cat'} and  $::calinfo{'cat'}) { 
	    my $tmp = $::calinfo{'cat'};
	    $tmp=~ s/^\s+|\s+$//g; $tmp =~ s/\s+/ /g; $tmp =~ s/\\//g; $tmp=~ s/\'/\\\'/g; 
	    $::calinfo{'cat'} = $tmp; 
	    if($tmp){ $newentry{'cat'} = $tmp;  update_catlist($who, $tmp); }
	}
        if(defined $::calinfo{'kwd'} and  $::calinfo{'kwd'}) { 
	    my $tmp = $::calinfo{'kwd'}; $tmp =~ s/\\//g; $tmp=~ s/\'/\\\'/g; $newentry{'kwd'} = $tmp; 
	}
        if(exists $::calinfo{'sroom'} and $::calinfo{'sroom'}) {
	    my $tmp = $::calinfo{'sroom'};  $tmp =~ s/\\//g; $tmp =~ s/\'//g; $newentry{'room'}= $tmp;
	}
	if(defined $::calinfo{'done'} and $::calinfo{'done'} eq 'y') {
	    if($::calinfo{'ctd'}) { $newentry{'ctd'} = $::calinfo{'ctd'};} 
	    else { $newentry{'ctd'} = printDate($::now{'month'},$::now{'day'}, $::now{'year'}) . "/$::now{'hour'}/$::now{'min'}/" . $::d{'remote_user'};}
	    $newentry{'done'}='y';
	}
	if(defined $::calinfo{'ctds'}) { $newentry{'ctds'} = $::calinfo{'ctds'};}
	if(defined $::calinfo{'smin'}) {$mn=$::calinfo{'smin'};} else {$mn = 0;} if($mn == 0) { $mn = "00";}
	if(defined $::calinfo{'shour'}) {$hr=$::calinfo{'shour'};} else {$hr = 0;}
	if (not $::o{'hourformat'} and defined $::calinfo{'sampm'}) {
	   if($kind == 2 and $::calinfo{'sampm'} eq 'am' and $hr eq 12) { $hr=24;}
	   elsif($::calinfo{'sampm'} eq 'pm') { $hr += 12 unless $hr eq 12;}
	}
        $hr = "00" if $hr == 0;
	$newentry{'start'}= "$hr:$mn";

	if(! $::calinfo{'repeat'}) { $::calinfo{'repeat'} = 0;}
        else { 
            $::calinfo{'repeat'} =~ s/\D//g; 
            if($::calinfo{'repeat'} eq "") {$::calinfo{'repeat'}= 0;}
            elsif($::calinfo{'repeat'} > 730) {$::calinfo{'repeat'}= 730;}
            elsif($::calinfo{'repeat'} <0) {$::calinfo{'repeat'}= 0;}
        }
	$rest = $::calinfo{'repeat'};
	# if recurring *weekly*  ..., the repeat is the num of weeks
	if($::calinfo{'occurs'}) {$occurs = $::calinfo{'occurs'};} else {$occurs = $::calinfo{'occurs'} = "OneTime";}
	my $oaref = $::occurenceHash{$occurs};
	if($oaref and $oaref->[2]){	# Occurs on certain weekdays
	   $::calinfo{'repeat'} = $oaref->[9] * $rest;
	   if($::calinfo{'orepeat'}) { $::calinfo{'repeat'} = $::calinfo{'orepeat'};}
	   # make sure the first occurence lands on a correct weekday.
	   # This is necessary for 'domodify' to save old exceptions, and repeat counts
	   my($tmp, $wcode); $wcode = wday($ssM, $ssD, $ssY);
	   if($occurs eq 'MTWThF') {
	       if($wcode == 0) {  $newentry{'date'}= printDate($ssM, $ssD+1, $ssY); }
	       elsif($wcode == 6) {$newentry{'date'}= printDate($ssM, $ssD+2, $ssY);}
	   } elsif( $occurs eq 'MWF') {
	       if( ($wcode & 1) == 0) {
		   if($wcode == 6) { $newentry{'date'}= printDate($ssM, $ssD+2, $ssY); } 
		   else { $newentry{'date'}= printDate($ssM, $ssD+1, $ssY); }
	       }
	   } elsif( $occurs eq 'TTh') {
	       if($wcode != 2 and $wcode != 4) {
		   if($wcode == 0) { $tmp = 2;} elsif($wcode == 1 or $wcode == 3) { $tmp = 1;}  else {$tmp = 9 - $wcode;}
		   $newentry{'date'}= printDate($ssM, $ssD+$tmp, $ssY);		   
	       }
	   }
	   $date = $::calinfo{'sdate'} =  $newentry{'date'};
	   ($ssM,$ssD, $ssY, $rest)=split(/\//, $date); $ssM -=1;
       } elsif(substr($occurs,0,2) eq 'ZW' and $occurs =~ /^Z(.+),(\d+),(\d*)/ ) {
	   my($c1, $c2) = ($2,$3);
	   if($c2==0){
	       my $wcode=wday($ssM,$ssD,$ssY);$c2=1<<$wcode;
	       $occurs="ZW,$c1,$c2";$::calinfo{'occurs'}=$occurs;
	   } else {
	       my @maskary = wdayoffsets($c2); 
	       $::calinfo{'repeat'} = $maskary[9] * $rest;
	       if($::calinfo{'orepeat'}) { $::calinfo{'repeat'} = $::calinfo{'orepeat'};}	   
	       my($tmp, $wcode, $i, $j, $k); $wcode = wday($ssM, $ssD, $ssY);
	       $i=0; for($j=$wcode; $j<7+$wcode; $j++) { $k=$j%7; if($c2 & (1<<$k)) {last;} else { $i++;}}
	       if($i) { $newentry{'date'}= printDate($ssM, $ssD+$i, $ssY); }
	   }
       } elsif(substr($occurs,0,2) eq 'ZX' and $occurs =~ /^Z(.+),(\d+),(\d*)/ ) {
	   my($c1, $c2) = ($2,$3);
	   $c2=wday($ssM,$ssD,$ssY);$occurs="ZX,$c1,$c2";$::calinfo{'occurs'}=$occurs;
       }
	
	if( $::calinfo{'repeat'} == 1 or $occurs eq "OneTime") { $::calinfo{'repeat'} = 0; }
	$rest = $::calinfo{'repeat'};
	$newentry{'repeat'}=$rest;

	if(($kind == 2 or $kind == 4) and defined $::calinfo{'bdate'}) {
	  my($bdate, $ma,$da,$ya,$mb,$db,$yb);
	  $bdate = $::calinfo{'bdate'};
	  ($ma,$da,$ya) = split(/\//, $bdate); $ma += 0; $da +=0; $ya += 0;
	  ($mb,$db,$yb) = split(/\//, $date);  $mb += 0; $db +=0; $yb += 0;
	  if($ya < 1900) { if($ya < 90) { $ya += 100;} $ya += 1900;}
	  if($yb < 1900) { if($yb < 90) { $yb += 100;} $yb += 1900;}
          if(dtAafterB($ma,$da,$ya,0,0, $mb,$db,$yb,1, 0)){
              $bdate=$date;
              # return (1,"$::phr{Start_date} $bdate $::phr{is_after_due_date} $date");
          }
	  $newentry{'bdate'} = $bdate;

	  if(defined $::calinfo{'forward'} and $::calinfo{'forward'} eq 'y')
	    {
	      if($rest > 0) {$msg = "$::phr{'Warning'}: $::phr{'NoRemindForward'}!";}
	      else { $newentry{'forward'} = 'y'}
	    };
	}
	if(defined $::calinfo{'pri'}) { 
	    my $tmp= $::calinfo{'pri'}; $tmp =~ s/\\//g; $tmp =~ s/\'//g; $newentry{'pri'} = $tmp;
	}
	if(defined $::calinfo{'spkr'} and  $::calinfo{'spkr'}) { 
	    my $tmp = $::calinfo{'spkr'}; $tmp =~ s/\\//g; $tmp=~ s/\'/\\\'/g;  $newentry{'spkr'} = $tmp;
	}

	if(! $toall) {
	  my ($att, $mgp);
	  if(exists $::calinfo{'imme'}) { $mme = $::calinfo{'imme'};}	#modifiable meeting entry?
	  $newentry{'mme'}=  $mme;
	  if($::calinfo{'mattendants'}) {  $att = $::calinfo{'mattendants'}; } else {$att="";}
	  if(defined $::calinfo{'smtgp'}) {$mgp = $::calinfo{'smtgp'};} else {$mgp="";}
	  if($mgp eq "$::phr{'none'}") { $mgp = "";}
	  if($att and $mgp) { $att .= ",". $mgp;}
	  else { $att = $att ? $att : $mgp;}
	  $att =~ s/\\//g; $att =~ s/\'//g; 
          $att =~ s/[,; ]+/:/g;
          $att =~ s/:$//g;
          $att = unique($att);
	  if(not $att and $::o{'dependency'} and $::calinfo{'dcs'}) { $att = "$::calinfo{'dcs'}:$who";}
          my $eatt=$att;
	  if($att) { 
              my ($tmp);
	      if(exists $::calinfo{'mkey'}) {$tmp =  $::calinfo{'mkey'}; $tmp =~ s/_eMe_\d+//g; $mkey=$tmp;}
	      elsif( $::calinfo{'eme'}) { $tmp=$::calinfo{'eme'};} 
              else {$tmp = $who;}
              $eatt = expandMeetingGroups($tmp, $eatt);
              if( ! ismember($who, $eatt) ) { $att .= ":$who";}
          }
	  $::calinfo{'mattendants'} = $att;
	  $att =~ s/:/,/g;
	  $newentry{'attendants'}=  $att;

	  if(defined $::calinfo{'acc'} or defined $::calinfo{'dec'}) {
	      my @att = split(/[,: ]+/, $eatt);  
	      if(defined $::calinfo{'acc'}) {
		  my $acc =  $::calinfo{'acc'}; $acc =~ s/[,: ]+/:/g;
		  my @acc =  split(/:/, $acc);	      
		  my ($s, $t, @rrr); @rrr=();
		  foreach $s (@acc) { foreach $t (@att) { if($s eq $t) { push @rrr, $s; last;}}};
		  $::calinfo{'acc'} = join(',', @rrr);
		  $newentry{'acc'} = $::calinfo{'acc'};
	      }
	      if(defined $::calinfo{'dec'}) { 
		  my $dec =  $::calinfo{'dec'}; $dec =~ s/[,: ]+/:/g;
		  my @dec =  split(/:/, $dec);	      
		  my ($s, $t, @rrr); @rrr=();
		  foreach $s (@dec) { foreach $t (@att) { if($s eq $t) { push @rrr, $s; last;}}};
		  $::calinfo{'dec'} = join(',', @rrr);
		  $newentry{'dec'} = $::calinfo{'dec'};
	      }
	  }
	  if(defined $::calinfo{'rsvp'}) { $newentry{'rsvp'} = $::calinfo{'rsvp'};}
        }
	
	# author
	{
	    my $tmp="$::d{'remote_user'}";
	    if($tmp eq 'anonymous') { $tmp = 'ANONYMOUS';}
	    else { $tmp =~ s/\\//g; $tmp =~ s/\'//g;}
	    if(! $author) { $newentry{'author'}= "$tmp";}
	    else { 
		$tmp =~ s/\\//g; $tmp =~ s/\'//g;
		if(! ismember($tmp, $author)) { $author .= ",$tmp";}
                $author =~ s/anonymous,//gi; 
                $newentry{'author'}= $author;
            }
	}
	
	if($kind != 2 and defined $::calinfo{'ehour'}) {
	    $hrr=$::calinfo{'ehour'};
	    if(defined $::calinfo{'emin'}) {$mnn=$::calinfo{'emin'};} else {$mnn = 0;}
	    if (not $::o{'hourformat'}  and defined $::calinfo{'eampm'}) {
	       if($::calinfo{'eampm'} eq 'am' and $hrr eq 12) { $hrr = 24;}
	       elsif($::calinfo{'eampm'} eq 'pm') { $hrr += 12 unless $hrr eq 12;}
	    }
	    $mnn = ($hrr - $hr)* 60 + ($mnn -$mn);
	    if($mnn < 0){ $mnn = 0;}
	} elsif($::calinfo{'oduration'}) {
	    $mnn = $::calinfo{'oduration'};
	}  else {$mnn = 0;}
	
	$newentry{'duration'}= $mnn;
	$tmp = $::calinfo{'description'};
	$tmp =~ s/\n(\r*\n\s*)+/\n\n/g; $tmp =~ s/\\//g; $tmp =~ s/\'/\\\'/g; 
	$newentry{'what'}= $tmp;
	if( $::calinfo{'detail'}) { $tmp = $::calinfo{'detail'}; $tmp =~ s/\n(\r*\n\s*)+/\n\n/g; $tmp=~ s/^\s+//; $tmp=~ s/\s+$//;} else {$tmp ="";}
	$tmp =~ s/\\//g; $tmp =~ s/\'/\\\'/g; 
	$newentry{'detail'}= $tmp;
	$newentry{'occurs'}=$::calinfo{'occurs'};

    if($::calinfo{'adrm'} and $::calinfo{'fromqadd'} and $::calinfo{'drem'}) {
	$newentry{'rem'} = $::calinfo{'drem'};  # from quickadd
    } elsif($::calinfo{'orem'}) {
	$newentry{'rem'} = $::calinfo{'orem'}; 
    } else {
	if(defined  $::calinfo{'rflash'}) {
	  $stmp = $::calinfo{'rflash'};
	  $utmp = $::calinfo{'rflashu'}; 
	  $vtmp = $::calinfo{'rflashv'}; $vtmp=~ s/,/;/g; $vtmp=~ s/[^\d;]//g; $vtmp=~ s/\D+$//g; $vtmp=~ s/^\D+//g;
	  $tmp="rf:" . "$stmp:$vtmp:$utmp,rm:";
	} else { $tmp ="rf:n:5:m,rm:";}
	if(defined $::calinfo{'rmail'}) {
	    $stmp = $::calinfo{'rmail'};
	    $utmp = $::calinfo{'rmailu'};
	    $vtmp = $::calinfo{'rmailv'}; $vtmp=~ s/,/;/g; $vtmp=~ s/[^\d;]//g; $vtmp=~ s/\D+$//g; $vtmp=~ s/^\D+//g;
	    $tmp .= "$stmp:$vtmp:$utmp,rp:";
	} else { $tmp .= "n:5:m,rp:";}
	if(defined $::calinfo{'rpopup'}) {
	  $stmp = $::calinfo{'rpopup'};
	  $utmp = $::calinfo{'rpopupu'};
	  $vtmp = $::calinfo{'rpopupv'}; $vtmp=~ s/,/;/g; $vtmp=~ s/[^\d;]//g; $vtmp=~ s/\D+$//g; $vtmp=~ s/^\D+//g;
	  $tmp .= "$stmp:$vtmp:$utmp,rc:";
	  $stmp = $::calinfo{'rchime'};
	  $utmp = $::calinfo{'rchimeu'};
	  $vtmp = $::calinfo{'rchimev'};$vtmp=~ s/,/;/g; $vtmp=~ s/[^\d;]//g; $vtmp=~ s/\D+$//g; $vtmp=~ s/^\D+//g;
	  $tmp .= "$stmp:$vtmp:$utmp";
	} else {
	  $tmp .= "n:5:m,rc:n:5:m";
	}
	$newentry{'rem'}=$tmp;
    }
        $::calinfo{'_savedreminder_'} = $newentry{'rem'};
	if($::calinfo{'enddate'}) {
	    my ($sM,$sD,$sY,$ndate,$error) = verifyDate($::calinfo{'enddate'});
	    if($error) { return(1, $error);}
	    if(mdyAafterB($ssM,$ssD, $ssY,$sM,$sD,$sY)>1) { return(1, "Impossible Event: End date is before starting date");}
            $newentry{'end'} = $ndate;
        } else {
	    $tmp=findEndDate($ssM,$ssD, $ssY, $::calinfo{'occurs'}, $::calinfo{'repeat'});
	    if($tmp) { $newentry{'end'} = $tmp;}
	}
	
	# check for overlapping events
	my $ckconflict=0;
	if(defined $::calinfo{'aol'} and $::calinfo{'aol'} != 0) {  $ckconflict = $::calinfo{'aol'}; }
	if($ckconflict or $::calinfo{'mattendants'}) {
	    my $others="";
	    my $timespec = "$newentry{'date'}/$newentry{'start'}:$newentry{'duration'}/$newentry{'occurs'}/$newentry{'repeat'}";
	    if($kind == 3 or $kind ==1) {
		$others = "$::calinfo{'mattendants'}";
		my $cmsg = checkOverlap($timespec,$others,$mkey,$ckconflict, $newentry{'what'});
		if($cmsg) { return(10, $cmsg, 0, "");}
	    }
	}

	# if no invitee is supplied, there is no need to store the following fields.
	if( ! $newentry{'attendants'} or $toall) {
	    if(exists $newentry{'rsvp'}) { delete $newentry{'rsvp'};}
	    if(exists $newentry{'mme'}) { delete $newentry{'mme'};}
	    if(exists $newentry{'acc'}) { delete $newentry{'acc'};}
	    if(exists $newentry{'dec'}) { delete $newentry{'dec'};}
	}
    }

    #$calname="$::o{'spooldir'}/$username";
    #if( -d $calname && -f "$calname/data" ) {
    #	if (sysopen(FILEF, "$calname/data", O_WRONLY | O_CREAT, 0644 ) ) {
    #       &webcalLock::doflock( \*FILEF, LOCK_EX, "$calname/data") or calerror("Cannot lock file '$calname/data': $!\n");     
            my $tcal = $::calinfo{'owho'} || $who;
            truncate($FHANDLE, 0);
	    print $FHANDLE "\@::caldata = (\n";
	    for $href (@::caldata) {
		next if $href->{'deleted'};
		if( ! $href->{'end'} ) { my $enddate = findEndDateHref($href); if($enddate) { $href->{'end'} = $enddate;}}
		$tmp = $href->{'key'};
		if($tmp > $::d{'eventCounter'}) { $::d{'eventCounter'} = $tmp;}
		$tmp = print1Entry($href);
		print $FHANDLE $tmp;
	    }
	    $::d{'eventCounter'}++;
            $saved_tag = $newentry{'key'}=$::d{'eventCounter'};
            if(!$::calinfo{'seq'} or ($tcal ne $who)) {
		if($toall){$::calinfo{'seq'}= "C" . time;}else{$::calinfo{'seq'}=time;}
	    }
            $saved_seq = $newentry{'seq'} = $::calinfo{'seq'};
	    if( $newentry{'attendants'} or $::calinfo{'oattendants'} ) {
	      my $tmp;
	      if(exists $::calinfo{'mkey'}) { $tmp =  $::calinfo{'mkey'};}
	      elsif(exists $::calinfo{'eme'}) { $tmp =  $::calinfo{'eme'} . "_eMe_" . $::d{'eventCounter'};}
	      else { $tmp = $who . "_eMe_" . $::d{'eventCounter'};}
	      $newentry{'mkey'}= $tmp;
	    }

	    if(! $::calinfo{'deleted'}) {
		print $FHANDLE "{\n";
		for $role (keys %newentry) { if(! $newentry{$role}) { $newentry{$role} = "";} 
		    print $FHANDLE "$role=>\'$newentry{$role}\',\n";
		}
		if($::calinfo{'exception'}) { print $FHANDLE "exception=>$::calinfo{'exception'},\n"; }
		print $FHANDLE "},\n";
	    }
	    print $FHANDLE ");\n$::d{'eventCounter'};\n";

#========================================
            delete $newentry{'pnd'};
#========================================
            if($toall) {
		$::lastNewEvent=copyTask(\%newentry);
		if($::calinfo{'exception'}) {$::lastNewEvent->{'exception'} = eval($::calinfo{'exception'});}
	    }
            if($nextNew == 0) {
		my ($who, $view, $ls, $mn, $dy, $yr, $mg, $refresh, $ncmd);
		$who = $::calinfo{'w'};
		$view = $::calinfo{'v'};
                $ls = $::calinfo{'ls'};
		($mn, $dy, $yr)=split(/\//, $date); $mn--;
                if(defined $::calinfo{'mg'} and $::calinfo{'mg'} ne "") {$mg="&mg=$::calinfo{'mg'}";} else {$mg="";}
		if($::calinfo{'sk'}) {$ncmd="task";} else {$ncmd='get';}
		
		#$refresh = undef;
		if(!defined $::calinfo{'inpopup'} and $msg eq "" and $imsg eq "" and 
		   ( !$::calinfo{'mattendants'} || $::calinfo{'deleted'} )) {
		    $::calinfo{'_header_refresh_code_'} =
			"1; URL=$::o{'cginame'}?c=$ncmd&ls=$ls&w=$tcal&v=$view&d=$mn/$dy/$yr$mg$::vmg";
		}
		
                #&headers($::phr{'Acknowledgement'},undef,$refresh);
		$retMsg .= "<br>&nbsp;<br>&nbsp;<br><center><font color=#009900><b>$::phr{'UpdatedOK'}</b></font>";
		if($msg) {
		    $retMsg .= "<p><font color=#ff0000><b>$msg</b></font>";
		}
		if($pndmsg) {
		    $retMsg .= "<p><font color=#ff0000><b>$pndmsg</b></font>";
		}
		
		if(!defined $::calinfo{'inpopup'}) {
		    $retMsg .= "<p><table bgcolor=$webcalConfig::r{'dkbackground'} border=2 cellpadding=2><tr><td><a href=\"$::o{'cginame'}?c=$ncmd&ls=$ls&w=$tcal&v=$view&d=$mn/$dy/$yr$mg$::vmg\">$::phr{'BackToCalendar'}</a></tr></table>";
		} else {
		    $retMsg .= "<form><b><input type=button  class=\"fmBtnSt\" value=\"$::phr{'Close'}\" onclick=\"self.close();opener.document.location.reload(1)\">&nbsp;&nbsp;&nbsp;<input type=button class=\"fmBtnSt\" value=\"$::phr{'GoBack'}\" onclick=\"history.go(-1)\"></b></form>";
		}
		$retMsg .=  "<p><font color=#006600>$imsg</font></center>\n";
	    }
	#} else { return (1, "$::phr{'OpenFailed'}");}
        
	# modify attendee's calendars
	if(!$toall && ($::calinfo{'mattendants'} or $::calinfo{'oattendants'}) && ! $::calinfo{'deleted'}) {
            my ($tmp, $others, $who, @members, $mkey, %hh, @tmem, $mem, $tmsg, $mail, @deletedMembers, %oldmembers);
	    my ($rattns, @rmembers); $rattns = ""; @rmembers = ();
            my (%newmembers, %members, $newaddr); %members=(); %newmembers=();
	    $mkey = $newentry{'mkey'};
	    $mkey =~ s/_eMe_\d+//g;
	    if($::calinfo{'mattendants'}) {
		$others = $::calinfo{'mattendants'}; 
		$others =~ s/[,; ]+/:/g;
		$others =~ s/:$//g;
		$rattns = expandMeetingGroups($mkey, $others, 1);		
		$others = removeCorporateCal(list_dependents($rattns));
	    } else {$others =""; $rattns="";}
	    (@members) = split(/:/, $others); (@rmembers) = split(/:/, $rattns);
	    @deletedMembers = (); %oldmembers=();
	    if($::calinfo{'oattendants'}) {
		my $tmpm = $::calinfo{'oattendants'}; $tmpm =~ s/[,; ]+/:/g;  $tmpm =~ s/:$//g;
		$tmpm = expandMeetingGroups($mkey, $tmpm);
		my @tmpm = split(/:/, $tmpm);
                map { $oldmembers{$_}=1;} (@tmpm); 
                map { $members{$_}=1;} (@members);
		my ($s);
		for $s (@tmpm) { if(not $members{$s}) { push @deletedMembers, $s;} }
		for $s (@members) { if(not $oldmembers{$s}) { $newmembers{$s}=1; } }
	    }
            $tmsg=$newaddr="";
	    if($::calinfo{'email'} ne "") {$mail="$::calinfo{'email'},";} else {$mail="";}
	    $mkey = $newentry{'mkey'};
#=======================
	    my $ok_2_write = &read_permission_table(); 
	    my $permission_problem="";
#	    calerror("$ok_2_write = $is_current_author = $::calinfo{'imme'}");
#=======================
	    my %doneHash=();
	    if($pending and $::dependency{$me}) { 
		my @deps = split(/:/,$::dependency{$me});
		my ($c);
		for $c (@deps) {
                    my ($Nir1, $Nsr1, $Nmail, $Nnewaddr, $Ntmsg, $Nproblem)=
			insert1($c, $me, \%oldmembers, \%newmembers, \%newentry, $mkey, $pending, $ok_2_write, \%doneHash);
		    $mail .= $Nmail; $permission_problem .= $Nproblem; $tmsg .= $Ntmsg; $newaddr .= $Nnewaddr;
		    $sr1 .= $Nsr1; $ir1 |=  $Nir1;
		}
	    }
	    for $who (@rmembers) {
		my ($Nir1, $Nsr1, $Nmail, $Nnewaddr, $Ntmsg, $Nproblem)=
		    insert1($who, $me, \%oldmembers, \%newmembers, \%newentry, $mkey, $pending, $ok_2_write, \%doneHash);
		$mail .= $Nmail; $permission_problem .= $Nproblem; $tmsg .= $Ntmsg; $newaddr .= $Nnewaddr;
		$sr1 .= $Nsr1; $ir1 |=  $Nir1;
		update_catlist($who, $newentry{'cat'}) if $newentry{'cat'};
	    }
	    for $who (@deletedMembers) { # remove the entry from those who is no longer on the invitee list
		my ($calendar);
		next if $who eq $me;
		$_ = $who;
		if(/.+\@.+/ and ! -d "$::o{'spooldir'}/$who") { $tmp = findWhoFromEmail($who); if($tmp) {$who = $tmp;}}
		next if $who eq $me;
		next if $who =~ /\//;
#=======================
		if( !($ok_2_write or is_authorized_author($::d{'remote_user'}, $who))) { $permission_problem .= "$who, "; next;}
#=======================
		$who = untaintname($who,$::phr{'Invalidusername'});
		$calendar = "$::o{'spooldir'}/$who";
		@::caldata=(); $::d{'eventCounter'}=1;
		if( -d $calendar and -f "$calendar/data") {
                    # doReadFile("$calendar/data");
		    my $fhhh = gensym;
		    if(sysopen($fhhh, "$calendar/data",O_WRONLY | O_CREAT, 0644) and &webcalLock::doflock( \*$fhhh, LOCK_EX, "$calendar/data")) {
                        do "$calendar/data";
                        truncate($fhhh, 0);
			$tmsg .= "<strike>$who</strike>, ";
			# if(-f "$calendar/info") {  doReadFile("$calendar/info"); }
			print $fhhh "\@::caldata = (\n";
			for $href (@::caldata) {
			    next if $href->{'deleted'};
			    next if defined $href->{'mkey'}  and $href->{'mkey'} eq $mkey;
			    $tmp = $href->{'key'};
			    if($tmp > $::d{'eventCounter'}) { $::d{'eventCounter'} = $tmp;}
			    $tmp=print1Entry($href);
			    print $fhhh $tmp;
			}
			$::d{'eventCounter'}++;
		    }
		    print $fhhh ");\n$::d{'eventCounter'};\n";
                    if(! &webcalLock::doflock( \*$fhhh, LOCK_UN,"$calendar/data")){$ir1 = 1; $sr1 .= "Cannot unlock file '$calname/data': $!<br>";}
		    close $fhhh;
		}
	    }
            if($nextNew == 0) {
                $tmsg =~ s/, $//;
                if($tmsg) {
		    $retMsg .= "<center><br><font color=#009900>$::phr{'Updated_calendars'}<br>$tmsg</font></center>";
		    my $tree = dependency_tree($me, \@rmembers);
		    $retMsg .= $tree if $tree;
		}
#=======================
		if($permission_problem) {
		    $retMsg .= "<center><br>The owner of the following calendars has not yet authorized you to write to their calendars. These calendars are not updated.<br><font color=red>$permission_problem</font></center>";
		}
#=======================
                $mail =~ s/,$//;
                if($mail) {
		    if ($webcalConfig::r{'builtinmail'}) {
			my ($who, $view, $ls, $mn, $dy, $yr, $mg);
			$who = $me;
			$view = $::calinfo{'v'};
			$ls = $::calinfo{'ls'};
			($mn, $dy, $yr)=split(/\//, $date); $mn--;
			if(defined $::calinfo{'mg'} and $::calinfo{'mg'} ne "") {$mg="&mg=$::calinfo{'mg'}";} else {$mg="";}
			my $inpopup="";if($::calinfo{'inpopup'}) { $inpopup="<input type=hidden name=inpopup value=1>";} 
			$retMsg .= <<END;
<center>
<Form name=m3 action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value="fm2">$inpopup
<input type=hidden name=w value="$who">
<input type=hidden name=v value=$view>
<input type=hidden name=t value=$saved_tag>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$mn/$dy/$yr">
<input type=hidden name=seq value=$saved_seq>
<input type=hidden name=invitee_addresses value="$mail">
<table border=0 width=400 bgcolor="#ccccff"><tr><td align=center>
<font color=red><b><input type=submit name=a  class="fmBtnSt" value="  $::phr{'MailToAll'} $::phr{'Participants'}  "></b></font>
</td></tr></table>
END
    ;
                        if($newaddr) { 
                            $retMsg .= <<END;
<input type=hidden name="new_invitee_addresses" value="$newaddr">
<table border=0 width=400 bgcolor="#ccccff"><tr><td align=center>
<font color=red><b><input type=submit name="to_new_invitee_only" class="fmBtnSt" value=" Mail To New Invitee Only "></b></font>
</td></tr></table>
END
    ;
                        }
                        
                        $retMsg .= "</Form></center>";
		    } else {
			$mail .= "?subject=".urlencode("$::phr{'Meeting'}");
			$retMsg .= "<p><center><table bgcolor=$webcalConfig::r{'dkbackground'} border=2 cellpadding=2><tr><td><a href=\"mailto:$mail\">$::phr{'MailToAll'} $::phr{'Participants'}</a></tr></table></center>";
		    }
                }
            }
        }
        if($pndmsg and $::calinfo{'nap'}) { # this hack only works when posting directly to a moderated cal
            my $email = $::calinfo{'email'};
            my $subj = "New posting on calendar $who"; my ($em, $ed, $ey) =split(/\//, $newentry{'date'}); $em--; 
            my $msgbody = genEMsgBdy(\%newentry, $who, 4, 0, 1, 0, "$em/$ed/$ey", "$subj\n");
	    SimpleMail($email, $email, $subj, $msgbody);
        }
        if($nextNew != 0) {
	    if($ir1 == 0) { return (1000,"", 0, "");}
	    else { return (0, "", $ir1, $sr1);}
        } else {
	    return (20, $retMsg, $ir1, $sr1);
	    #&trailer;
        }
    #} else {calerror("$::phr{'OpenFailed'}");}
}
#=============================================================================================

sub insert1 {
    my ($who, $me, $oldmembers, $newmembers, $newentry, $mkey, $pending, $ok_2_write, $doneHash) =(@_);
    my ($mail, $problem, $tmsg, $newaddr, $ir1, $sr1); 
    $mail = ""; $problem = ""; $tmsg=""; $newaddr=""; $sr1="", $ir1=0;
    if($who eq $me or $doneHash->{$who}) { 
	$doneHash->{$who}=1;
	return($ir1, $sr1, $mail, $newaddr, $tmsg, $problem);
    }
    my ($calendar, $tmp);
    $_ = $who;
    if(/.+\@.+/ and ! -d "$::o{'spooldir'}/$who") {
	$tmp = findWhoFromEmail($who); 
	$doneHash->{$who} = 1;
	if($tmp) {$who = $tmp;} else { $mail .= "$who,";}
    }
    if($who eq $me or $who =~ /\//) {
	$doneHash->{$who}=1;
	return($ir1, $sr1, $mail, $newaddr, $tmsg, $problem);
    }
#=======================
    my $ok1 = 1;
    if(!$ok_2_write) {
	$ok1 = (($::is_authorized_author and $oldmembers->{$who}) or &is_authorized_author($::d{'remote_user'}, $who));
	if(!$ok1) { $problem .= "$who, "; $doneHash->{$who} = 1;}
    }
    if(! $ok1) { return($ir1, $sr1, $mail, $newaddr, $tmsg, $problem);} 
#=======================
    my $newpending = "";
    if(! $pending) {
	if($::moderated{$who} and not isre($::d{'remote_user'}, $who, 'editors')) {
	    $newpending = $newentry->{'pnd'}=$who; &markHasPending("$::o{'spooldir'}/$who/pnd");
	}
    } else { $newentry->{'pnd'} = $pending;}
    #$::debugInfo{'I'} .= "Doing $who, pnd=$pending npnd=$newpending<br>";
#=======================
    $doneHash->{$who}=1;
    $who = untaintname($who,$::phr{'Invalidusername'});
    $calendar = "$::o{'spooldir'}/$who";
    @::caldata=();
    $::d{'eventCounter'} = 1;		
    if( -d $calendar and -f "$calendar/data") {
	my $fhh = gensym;
	if(sysopen($fhh,"$calendar/data",O_WRONLY | O_CREAT, 0644 ) and &webcalLock::doflock(\*$fhh, LOCK_EX, "$calendar/data")){
	    do  "$calendar/data";
	    truncate($fhh, 0);
	    $tmsg .= "$who, ";
	    $::calinfo{'email'}="";
	    if(-f "$calendar/info") {
		doReadFile("$calendar/info");
		if($::calinfo{'email'} ne ""){
		    if($newmembers->{$who}){$newaddr .= "$::calinfo{'email'}," }
		    $mail .= "$::calinfo{'email'}," ;
		}
	    }
	    my $href;
	    print $fhh "\@::caldata = (\n";
	    for $href (@::caldata) {
		next if $href->{'deleted'};
		next if defined $href->{'mkey'}  and $href->{'mkey'} eq $mkey;
		$tmp = $href->{'key'};
		if($tmp > $::d{'eventCounter'}) { $::d{'eventCounter'} = $tmp;}
		$tmp=print1Entry($href);
		print $fhh $tmp;
	    }
	    $::d{'eventCounter'}++;
	    $newentry->{'key'}=$::d{'eventCounter'};
	}
	if(! $::calinfo{'deleted'}) {
	    print $fhh "{\n";
	    my $role;
	    for $role (keys %$newentry) {
		print $fhh "$role=>\'$newentry->{$role}\',\n";
	    }
	    if($::calinfo{'exception'}) { print $fhh "exception=>$::calinfo{'exception'},\n"; }
	    print $fhh "},\n";
	}
	print $fhh ");\n$::d{'eventCounter'};\n";
	if(!&webcalLock::doflock(\*$fhh, LOCK_UN, "$calendar/data")){
	    $ir1 = 1; $sr1 .= "Cannot unlock file '$calendar/data': $!<br>";
	}
	close $fhh;

	delete $newentry->{'pnd'};

	if($pending or $newpending and $::dependency{$who}) {
	    my @dependents = split(/:/, $::dependency{$who} || "");
	    my ($cal, $np);
	    $np = $pending? $pending: $newpending;
	    for $cal (@dependents) {
		my ($Nir1, $Nsr1, $Nmail, $Nnewaddr, $Ntmsg, $Nproblem)=
		    insert1($cal, $me, $oldmembers, $newmembers, $newentry, $mkey, $np, $ok_2_write, $doneHash);
		$mail .= $Nmail; $problem .= $Nproblem; $tmsg .= $Ntmsg; $newaddr .= $Nnewaddr;
		$sr1 .= $Nsr1; $ir1 |=  $Nir1;
	    }
	}
    }
    return($ir1, $sr1, $mail, $newaddr, $tmsg, $problem);
}

#=============================================================================================
sub dependency_tree { #fixme
    my ($who, $rmembers) = (@_);
    my ($file,%seen, $ret, $c);
    $ret = "";
    $file = "$::o{'spooldir'}/.dependency";
    if( -f "$file") {
	%::dependency=(); doReadFile($file); %seen=();
	for $c (@$rmembers) {
	    my $tmp =  descendants($c, \%seen, 0);
	    if($tmp) { $ret .=  "$tmp<br>";}
	}
    }
    if($ret){
	$ret ="
<br>
<center>
<table border=0 bgcolor=#ccddff  border=0 cellspacing=1>
 <tr><td><table border=0 cellpadding=6 cellspacing=0><tr><td bgcolor=#ECFFF0 align=center>
 <font color=#999999>Dependency Relations<br></font>
</td></tr>
<tr><td bgcolor=#ECFFF0>
<font size=-1 color=#666699>
<pre>$ret</pre>
</font>
</td></tr></table>
</td></tr></table>
</center>
<br>
";
    }
    return $ret;
}
sub descendants {
    my ($c, $seen, $level) = (@_);
    return "" if $seen->{$c};
    my $ret = "";
    $seen->{$c}=1;
    if($::dependency{$c}) {
	my $tmp = " " x $level;
	$ret .= $tmp . "$c=>" . $::dependency{$c} . "\n";
	my @members = split(/:/, $::dependency{$c});
	my $d;
	for $d (@members) {
	    $ret .= descendants($d, $seen, 2+$level);
	}
    }
    return $ret;
}
#=============================================================================================

sub read_permission_table {
    return 1 if (not $::o{'authorize_author'}) or isadmin($::d{'remote_user'}) 
	or isvgadmin($::d{'remote_user'}, $::calinfo{'w'});
    %::authors=();
    my ($file, $me, $authors);
    $file = "$::o{'spooldir'}/.authors";
    if( -f "$file") {	doReadFile("$file");	return 0;  }
    return 1;
}
sub is_authorized_author {
    if($::o{'authorize_author'}) {        
	my ($me, $cal) = (@_);
	my ($authors);
	$authors = $::authors{$cal};
	if((! $authors) or $authors =~ /:$me:/ or isre($me, $cal, 'editors')) { return 1;}
	return 0;
    }
    return 1;
}
sub get_moderated_calendars {
    %::moderated=();
    my $file = "$::o{'spooldir'}/.moderated";
    if( -f "$file") { doReadFile("$file"); }
}
#=============================================================================================

sub expandMeetingGroups {	#input is : separated fields, return the same kind
  my ($input, @members, $retvalue, $mm, $gp, $tmp, $who, $flag);
  ($who, $input, $flag) = (@_);
  $who=$::calinfo{'w'} unless $who;
  @members = get_mgroups($who);
  if(scalar @members) {
      $retvalue="";
      (@members) = split(/[:,;]/, $input);
      for $mm (@members) {
          next if $mm !~ /^[\w|\(|\)|\.|\-|\@]+$/;
          if ($mm =~ m/\($::phr{'global'}\)/) {
              $mm =~ s/\($::phr{'global'}\)//g;
              $gp="mgp_" . $mm;
              if( $::GlobalMeetingGroups{$gp} ) {
                  $tmp = $::GlobalMeetingGroups{$gp};
                  if($retvalue) {	$retvalue .= ":$tmp";}
                  else { $retvalue = $tmp;}
              } else { if($retvalue) {$retvalue .= ":$mm"; } else {$retvalue = "$mm";}}
          } else {
              $gp="mgp_" . $mm;
              if( $::meetingGroups{$gp} ) {
                  $tmp = $::meetingGroups{$gp};
                  if($retvalue) {	$retvalue .= ":$tmp";}
                  else { $retvalue = $tmp;}
              } else { if($retvalue) {$retvalue .= ":$mm"; } else {$retvalue = "$mm";}}
          }
      }
  } else { $retvalue = $input;}
  # complete dependency list
  if(not $flag) { $retvalue = list_dependents($retvalue) if $::o{'dependency'} ; }

  return removeCorporateCal($retvalue);
}

sub removeCorporateCal {
    my ($retvalue) =(@_);
    if($::o{'corporate_calendar'}) { # corporate calendar cannot be in any group
	my @ccals = split(/[:;, ]+/, $::o{'corporate_calendar'});
	my @gcals = split(/[:;, ]+/, $retvalue);
	my (%cc, %gc); %cc=(); %gc=();
	map { $cc{$_} = 1;} (@ccals);
	map { $gc{$_} = 1 if not $cc{$_};} (@gcals);
	$retvalue= join(':', (keys %gc));
    } 
    return unique($retvalue);
}

sub list_dependents {
    my ($retvalue)=(@_);
    my ($file); %::dependencyHash =();
    $file = "$::o{'spooldir'}/.dependency";

    if( -f "$file") {
	%::dependency=(); doReadFile($file);
	my @members = split(/:/, $retvalue);
	map {  if(not $::dependencyHash{$_}){&traverseDependencyGraph($_, 1);} } (@members);
	$retvalue = join(':', (keys %::dependencyHash));
    }
    return $retvalue;
}

sub traverseDependencyGraph {
    my ($w, $level) = (@_);
    if($::dependencyHash{$w}) { return;}
    $::dependencyHash{$w} = $level;
    my $dependants = $::dependency{$w};
    if($dependants) {
	my (@list) = split(/:/, $dependants);
	map { traverseDependencyGraph($_, 1+$level); } (@list);
	map { $::dependencyHash{$_} = $level} (@list);
    }
}
#=============================================================================================
sub getdependants {
    my ($cal) =(@_);
    if($::o{'dependency'} and $cal) {
	my ($file, $v);
	$file = "$::o{'spooldir'}/.dependency";
	if( -f "$file") {
	    %::dependency=(); doReadFile($file);
	    $v = $::dependency{$cal};
	    return $v if $v;
	}
    }
    return "";
}

sub getauthors {
    my ($cal) =(@_);
    if($::o{'authorize_author'}) {    
	my ($file, $v);
	$file = "$::o{'spooldir'}/.authors";
	if( -f "$file") {
	    %::authors=(); doReadFile($file);
	    $v = $::authors{$cal};
	    return $v if $v;
	}
	return "";
    }
}
#=============================================================================================
sub unique {
  my ($in)=(@_);
  my %hh=();
  my @members=();
  my @tmp = split(/:/, $in);
  my $t;
  for $t (@tmp) {
    if(! exists $hh{$t} ) {
      push @members, $t;
      $hh{$t} = 1;
    }
  }
  $t = join(':', @members);
  return $t;
}
#=============================================================================================
sub findEndDateHref {
    my ($href) = (@_);
    if($href) {
        my ($enddate, $ssm, $ssd, $ssy,$sso, $ssr, $sst);
        $sst= $href->{'date'};
        ($ssm,$ssd,$ssy)=split(/\//, $sst); $ssm--;
        $sso=$href->{'occurs'};
        $ssr=$href->{'repeat'};
        $enddate = findEndDate($ssm,$ssd,$ssy,$sso,$ssr);
        return $enddate;
    }
    return "";
}
sub findEndDate {
  use integer;
  my ($mn,$dy, $yr, $occurs, $repeat, $tmp);

  ($mn,$dy, $yr, $occurs, $repeat) = (@_);

  if(!$repeat or ! $occurs) { $mn++; $tmp="$mn/$dy/$yr"; }
  elsif($occurs eq "Daily") {
    $dy += $repeat;
    ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif($occurs eq "Weekly") {
    $dy += ($repeat -1) * 7 + 1;
    ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif ($occurs eq "Every2Weeks") {
    $dy += ($repeat -1) * 14 + 1;
    ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif ($occurs eq "MonthlyByDate") {
    $mn += ($repeat -1); $dy += 1;
    ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif ($occurs eq "MonthlyByWeekday") {
    $mn += ($repeat -1);
    ($mn, $dy, $yr)=canDate($mn, $dy+7, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif ($occurs eq "MTWThF") {
    my $wcode = wday($mn, $dy, $yr);
    $dy +=  int(($repeat + 4)/5) * 7 - $wcode ;
    ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif ($occurs eq "MWF") {
    my $wcode = wday($mn, $dy, $yr);
    $dy += int(($repeat + 2)/3) * 7 - $wcode;
    ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif ($occurs eq "TTh") {
    my $wcode = wday($mn, $dy, $yr);
    $dy += int(($repeat + 1)/2) * 7 - $wcode;
    ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif ($occurs eq "Yearly") {
    $yr += $repeat;
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif ($occurs eq "YearlyByMonthWeekday" ) {
    $yr += $repeat; $dy += 7;
    ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";      
  } elsif($occurs eq "EveryOtherDay") {
    $dy += $repeat * 2;
    ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif($occurs eq "Every3rdDay") {
    $dy += $repeat * 3;
    ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif($occurs eq "Every4thDay") {
    $dy += $repeat * 4;
    ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif($occurs eq "Every5thDay") {
    $dy += $repeat * 5;
    ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif($occurs eq "Every6thDay") {
    $dy += $repeat * 6;
    ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
    $mn++;
    $tmp="$mn/$dy/$yr";
  } elsif(substr($occurs,0,1) eq 'Z' and $occurs =~ /^Z(.+),(\d+),(\d*)/ ) {
      my ($word, $c1, $c2) =($1, $2, $3);
      if($word eq 'D') { 
	  $dy += ($repeat -1) * $c1 + 1;
	  ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
	  $mn++;
	  $tmp="$mn/$dy/$yr";	  
      } elsif($word eq 'MD') {
	  $mn += ($repeat - 1) * $c1; $dy += 1;
	  ($mn, $dy, $yr)=canDate($mn, $dy, $yr);
	  $mn++;
	  $tmp="$mn/$dy/$yr";
      } elsif($word eq 'MWD' or $word eq 'MND' or $word eq 'MNW' ) {
	  $mn += ($repeat -1) * $c1; 
	  ($mn, $dy, $yr)=canDate($mn, $dy + 7, $yr);
	  $mn++;
	  $tmp="$mn/$dy/$yr";
      } elsif($word eq 'W') {
	  my $nbits = unpack "%8b*", pack("C", $c2);
	  my $nwks = ($repeat + $nbits -1) / $nbits;
	  my $wcode = wday($mn, $dy, $yr);
	  $dy += ($nwks - 1) * $c1 * 7;
	  ($mn, $dy, $yr)=canDate($mn, $dy + 7, $yr);
	  $mn++;
	  $tmp="$mn/$dy/$yr";	  
      } elsif($word eq 'X') {
	  my $nwdays = $c1 * ($repeat-1);
	  my $ndays= ($nwdays/5)*7 + 2 + ($nwdays % 5);
	  ($mn, $dy, $yr)=canDate($mn, $dy + $ndays, $yr);
	  $mn++;
	  $tmp="$mn/$dy/$yr";	  
      } else { $tmp = "";} 
  } else {$tmp= "";}
  return($tmp);
}

#=============================================================================================
sub findWhoFromEmail {
    my ($tmp,$addr, $dir, @filenames);
    $addr=(@_)[0];
    @filenames = &listcals;
    for $dir (@filenames) {
        my $tname = "$::o{'spooldir'}/$dir/info";
	my $fhi = gensym;
	if(open($fhi, "<$tname")) {
            &webcalLock::doflock( \*$fhi, LOCK_SH, "$tname") or calerror("Cannot lock file '$tname': $!\n",1);
	    while (<$fhi>) {
		if(/\$::calinfo{\'email\'}=\'$addr\'/) {
                    &webcalLock::doflock( \*$fhi, LOCK_UN,"$tname")  or calerror("Cannot unlock file '$tname': $!\n",1);
		    close $fhi;
		    return $dir;
		}
	    }
            &webcalLock::doflock( \*$fhi, LOCK_UN,"$tname")  or calerror("Cannot unlock file '$tname': $!\n",1);
	    close $fhi;
	}
    }
    return "";
}
#=============================================================================================
#
# called by deleteOne and deletAll after inserstion. Delete one entry or all repeating entries
#
# cmdname=
#         -1 delete Forward, modify EndDate and repeat count
#         0  delete one, modify exception
#         1  delete
#         2  mark task complete, may modify exception.
#         3  modify confirmation string
sub fixMeetingEntry {
    my ($mkey, $themme, $others, $cmdname,  $nrepeat, $exceptionString, $acc, $dec, $cstr) = (@_);
    my ($who, $me, $tmp, @members, $j, $role, $href, $ee, @tmem, %hh, $mem, $tmk, $ok, $date);
    my ($ir0, $sr0) = (0, "");

    # check authentication
    if(exists $::calinfo{'sdate'} and $cmdname == -1) {
      my ($ssM, $ssD, $ssY, $rest);
      $date = $::calinfo{'sdate'};
      ($ssM,$ssD, $ssY, $rest)=split(/\//, $date); $ssM -=1; $ssD -= 1; # new enddate, one day before sdate
      $date=printDate($ssM,$ssD,$ssY);
    } else {
      $date = "";
    }
    $me = $::calinfo{'w'};
    if($others and $mkey) {	# meeting editor, try to edit other calendars
	$others =~ s/[,; ]+/:/g;
	$tmk = $mkey;
	$tmk =~ s/_eMe_\d+//g;
	$others = expandMeetingGroups($tmk, $others);
	(@tmem) = split(/:/, $others);
	(@members) = ();
	%hh = ();
	for $mem (@tmem) {
	  if( ! exists $hh{$mem}) {
	    push @members, $mem;
	    $hh{$mem} = 1;
	  }
	}
	$ok = 0;
	if(isadmin($::d{'remote_user'}) or isvgadmin($::d{'remote_user'},$me)){ $ok = 1;}
	elsif(isre("$::d{'remote_user'}", $tmk, 'editors') or $cmdname == 3 or
           (ismember($::d{'remote_user'}, $others) and ($themme > 1 or $themme and $cmdname == 2) )) {$ok = 1;}
	if($ok == 0) {  return (0, ""); }

	for $who (@members)  {
	    my ($calendar);
	    next if $who eq $me ;
	    $_ = $who;
	    if(/.+\@.+/ and ! -d "$::o{'spooldir'}/$who") { $tmp = findWhoFromEmail($who); $who = $tmp; }
	    next if $who eq $me or $who eq "" ; 
	    next if $who =~ /\//;
	    $who = untaintname($who,$::phr{'Invalidusername'});
	    $calendar = "$::o{'spooldir'}/$who";
	    @::caldata=();
	    if( -d $calendar and -f "$calendar/data") {
		$j=0;
		$::d{'eventCounter'}=1;
		# doReadFile( "$calendar/data");
		my $fhk = gensym;
		if(sysopen($fhk, "$calendar/data", O_WRONLY | O_CREAT, 0644) ) {
                    if( &webcalLock::doflock( \*$fhk, LOCK_EX, "$calendar/data") ) {
			do "$calendar/data";
			truncate($fhk, 0);
			print $fhk "\@::caldata = (\n";
			for $href (@::caldata) {
			    $tmp = $href->{'key'};
			    if($tmp > $::d{'eventCounter'}) { $::d{'eventCounter'} = $tmp;}
			    if(defined $href->{'mkey'} and $href->{'mkey'} eq $mkey) {
				if($cmdname == 2) { # called from TaskManager, mark complete
				    if( ! $href->{'deleted'} ) {
					if(!$exceptionString) {
					    $href->{'done'} = 'y';
					    $href->{'ctd'}=printDate($::now{'month'},$::now{'day'}, $::now{'year'}) . "/$::now{'hour'}/$::now{'min'}/" . $::d{'remote_user'};
					} else {
					    $href->{'exception'} = eval $exceptionString;
					    if($cstr) {$href->{'ctds'} = $cstr;}
					}
					$tmp = print1Entry($href);
					print $fhk $tmp;
				    }
				} elsif($cmdname == 3) { # modify attendee confirmation string
				    $href->{'acc'} = $acc;
				    $href->{'dec'} = $dec;
				    $tmp = print1Entry($href);
				    print $fhk $tmp;
				} elsif($cmdname == 1 or $href->{'repeat'} eq '0') { next; }
				# cmdname = 0 or -1
				else { # delete One occurance or forward occurance of an recurring event.
				    if($cmdname == -1 and $date ne "") { #delete forward
					$href->{'end'} = $date; 
					$href->{'repeat'} = $nrepeat if $nrepeat >=0;
				    }
				    if($exceptionString) { $href->{'exception'} = eval $exceptionString;}
				    else {delete $href->{'exception'} if $href->{'exception'};}
				    if(! ismember($::d{'remote_user'}, $href->{'author'})) {$href->{'author'} .= ",$::d{'remote_user'}";}
				    $tmp = print1Entry($href);
				    print $fhk $tmp;				
				}
			    } else  {
				$tmp = print1Entry($href);
				print $fhk $tmp;
			    }
			}
			$::d{'eventCounter'}++;
			print $fhk ");\n$::d{'eventCounter'};\n";
			if(!&webcalLock::doflock( \*$fhk, LOCK_UN, "$calendar/data")) {$ir0 = 1;$sr0 .="Cannot unlock file '$calendar/data': $!<br>";}
			close $fhk;
		    } else { $ir0 = 1;  $sr0 .= "Cannot lock file '$calendar/data': $!<br>";}
		} else {  $ir0 = 1;  $sr0 .= "Cannot open file '$calendar/data': $!<br>";}
	    }
	}
    }
    return ($ir0, $sr0);
}

#=====================================================================================================
sub authorize_misc_screens {
    my ($flag) = (@_);
    my $who = $::calinfo{'w'};
    my $rlevel = 0;
    if( isre($::d{'remote_user'}, $who, 'editors') ) { $rlevel = 10;}
    elsif( $::d{'ispublic'} == 0) {
	if( isre($::d{'remote_user'}, $who, 'readers') ) { $rlevel = 1;}
    } else { $rlevel = 1;}

    if($flag and $rlevel == 0) { calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who)."); }
    return $rlevel;
}
#=====================================================================================================

sub option_admin {
    my ($command)=(@_);
    my ($who, $view, $ls); 
    $who = $::calinfo{'w'}; $view = $::calinfo{'v'}; $ls = $::calinfo{'ls'}; 
    my $isadm = isadmin($::d{'remote_user'}); my $isvgadm= $isadm || isvgadmin($::d{'remote_user'},$who);
    if(! $isadm and ! $isvgadm) { &authorize_misc_screens(1);}

    my ($body,$script) = &getClockScript(); 
    &headers($::phr{'CalendarOptions'},"$script",undef,1, 1, $body);

    my $headerForm=&newHeader('option', 0);
    print $headerForm;

    #========================================================================
    # preference options
    my @opnames = ( $::phr{'dateTime'},                        # 0
		    $::phr{'dpysettings'},                     # 1
		    $::phr{'Privacy'},                         # 2  
		    $::phr{'Reminders'},                       # 3
		    $::phr{'Colors'},                          # 4
		    $::phr{'StyleSheet'},                      # 5
		    "$::phr{'Editors'}/$::phr{'Readers'}",     # 6
		    $::phr{'otherCals'},                       # 7
		    $::phr{'personalInfo'},                    # 8
		    "$::phr{'Header'}/$::phr{'Footer'}",       # 9
		    $::phr{'allOptions'},                      #10
		    );

    # administrative options    
    my %adnames = (
		   '126_download' => $::phr{'downloadCalendar'},
		   '128_danger'  =>  $::phr{'DangerousOperations'},
		   );
    if(not &webcalAuth::disallowPasswordChange() ){
	$adnames{'120_changePassword'} = $::phr{'Change_Password'};
	if($isadm or $isvgadm) {
	    $adnames{'127_resetPassword'} = $::phr{'ResetPasswd'};
	}
    }
    if(! ismember($who, $::o{'corporate_calendar'})) { 
	$adnames{'122_meetingGP'}  = $::phr{'Create_Meeting_Group'};
	if($isadm or $isvgadm) {
	    $adnames{'123_GmeetingGP'}  = $::phr{'Create_Global_Meeting_Group'};
	}
    }
    if(!ismember($who, $::o{'corporate_calendar'}) ) {
	$adnames{'124_mergeCal'} = $::phr{'Merge_Calendars'};
    }
    if($isadm or $isvgadm) {
	$adnames{'129_delete'}  =  $::phr{'DeleteCalendars'};
	$adnames{'121_deleteCache'}  =  $::phr{'DeleteCache'};
        if($::o{'create'} == 0) {$adnames{'251_createNew'}  =  $::phr{'CreateNewCal'}; }
	if($::o{'vgroup'} and $isadm) {	$adnames{'261_vgroup'}  =  $::phr{'VirtualGroup'}; }   
    }
    #========================================================================

    my $opcode = $::calinfo{'opcode'} || 0;
    my $navtable = option_nav($opcode,$who,$view,$ls,\@opnames);
    my $anavtable= admin_nav($opcode, $who, $view, $ls, \%adnames);

    if($::d{'authResult'} ne 4) {
	print "<img src=\"$::o{'imgdirurl'}/spacer.gif\" width=160 height=1 border=0><font color=\"#999900\"><b><span class=\"authWarn\">$::phr{'AuthRequired'}!</span></b></font>\n";

	print <<END;
<table cellspacing=0 cellpadding=0 border=0 width="100%">
<tr><td bgcolor="#bbbbbb" height=1><img src="$::o{'imgdirurl'}/spacer.gif" height=1 width=1 border=0></td></tr>
</table>
END
;
	 }
    
    print <<END;
<table class="oaContainer" border=0 cellspacing=2 cellpadding=2>
<tr><td class="oaleft" valign=top align=center width="10%">$navtable<br>$anavtable</td>
<td><td class="oadivider" width=1 height=800 valign=top><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=20 border=0><img src="$::o{'imgdirurl'}/vline.gif" width=1 height=640 border=0></td>
<td class="oaright"  valign="top" width="90%">
END
;

    if($command =~ /^o/i) {
	&option($opcode, 10, \@opnames);
    } else {
	&admin($opcode, \%adnames, $isadm, $isvgadm);
    }
    print "</td></tr></table>";

    &trailer(0,0);    
}
#=====================================================================================================
sub admin_nav {
    my ($code, $who,$view,$ls, $names) = (@_);
    my ($mg, $aref, $bref, $i, $out, $tmp, $nopts,$key);
    if($::d{'megaCal'} ne "") {$mg="&mg=$::d{'megaCal'}"; } else {$mg="";}
    $aref = "$::o{'cginame'}?c=admin&w=$who&v=$view&ls=$ls&$mg$::vmg&opcode=";
    $out = "<table border=0 cellspacing=0 cellpadding=2 class=\"lntab\" width=\"100%\">";
    $out .= <<END;
<tr class=lnheaderrow><td align=center class=lnheadercell><font color="$::themeColor"><b><span class="lnheadertxt">$::phr{'Administration'}</span></b></font></td></tr>
END
;

    for $key (sort keys %$names) {
	my ($hbg,$bg, $oname, $hover, $css, $arr, $icode, $jnk, $cssa);
	($icode,$jnk) = split(/_/,$key,2);
	$oname = $names->{$key};
	$cssa=$css=$arr="";
	if($icode == $code) {
	    $bref = "javascript:void(0)"; $css= $cssa = "h"; $hover=""; $arr=">";
	} else {
	    if($icode == 251) { # create new cal
		$bref="$::o{'cginame'}?c=setup";
	    } elsif($icode == 261) { # vgrp
		$bref="$::o{'cgimisc'}?cmd=vgp";	
	    } else {
		$bref = "$aref$icode"; $css = ""; $arr="&nbsp;";
	    }
	    if($icode & 1) { $cssa = "a";}
	    $hover="onmouseover=\"chover(this,1,'lncellHover','lncell')\" onmouseout=\"chover(this,0,'lncellHover','lncell')\" onclick=\"ngoto(this,'$bref')\"";
	}
	$out .= <<END;
<tr class="lnrow"><td class="lncell$css" nowrap $hover>
<a href="$bref" class="transparent"><font color="#333333"><span class="lnav$cssa">&nbsp;$arr&nbsp;$oname</span></font></a>
</td></tr>
END
;
    } 
    $out .= "</table>";
    return $out;
}
#=====================================================================================================
sub option_nav {
    my ($code, $who,$view,$ls, $names) = (@_);
    my ($mg, $aref, $bref, $i, $out, $tmp, $nopts);
    if($::d{'megaCal'} ne "") {$mg="&mg=$::d{'megaCal'}"; } else {$mg="";}
    $aref = "$::o{'cginame'}?c=option&w=$who&v=$view&ls=$ls&$mg$::vmg&opcode=";
    $out = "<table border=0 cellspacing=0 cellpadding=2 class=\"lntab\" width=\"100%\">";
    $out .= <<END;
<tr class=lnheaderrow><td align=center class=lnheadercell><font color="$::themeColor"><b><span class="lnheadertxt">$::phr{'Preferences'}</span></b></font></td></tr>
END
;

    for $i (0,1,4,5,3,9,2,8,6,7,10) {
	my ($hbg,$bg, $oname, $hover, $css, $arr, $icode);
	$icode = $i;
	$oname = $names->[$i];
	if($icode == $code) {
	    $bref = "javascript:void(0)"; $css= "h"; $hover=""; $arr=">";
	} else {
	    $bref = "$aref$icode"; $css = ""; $arr="&nbsp;";
	    $hover="onmouseover=\"chover(this,1,'lncellHover','lncell')\" onmouseout=\"chover(this,0,'lncellHover','lncell')\" onclick=\"ngoto(this,'$bref')\"";
	}

	$out .= <<END;
<tr class="lnrow"><td class="lncell$css" nowrap $hover>
<a href="$bref" class="transparent"><font color="#333333"><span class="lnav$css">&nbsp;$arr&nbsp;$oname</span></font></a>
</td></tr>
END
;
    } 
    $out .= "</table>";
    return $out;
}
#=====================================================================================================
sub add_option_tips {
    my ($opcode, $nopts) = (@_);

}
#=====================================================================================================
sub option {
    my ($opcode, $nopts, $opnames) = (@_);
    my ($jj, $who, $view, $ctype, $name, $homepage, $tzone, $shr, $ehr, $tt, $ss, $uu, $vv, 
	$ampm, $ls, $hdr,$ftr);
    $who=$::calinfo{'w'};

    if(exists $::calinfo{'dview'}) { $view=$::calinfo{'dview'};} else {$view=$::calinfo{'v'};}
    if(exists $::calinfo{'dlist'}) { $ls=$::calinfo{'dlist'};} elsif(defined $::calinfo{'ls'}) {$ls=$::calinfo{'ls'};} else {$ls=0;}
    if(exists $::calinfo{'ctype'}) { $ctype=$::calinfo{'ctype'};} else {$ctype="";}
    if(exists $::calinfo{'name'}) { $name=$::calinfo{'name'};} else {$name="";}
    if(exists $::calinfo{'homepage'}) { $homepage=$::calinfo{'homepage'};} else {$homepage="";}
    if(exists $::calinfo{'tzone'}) { $tzone=$::calinfo{'tzone'};} else {$tzone="";}
    if(exists $::calinfo{'hdr'}) { $hdr=$::calinfo{'hdr'};} else {$hdr="";}    
    if(exists $::calinfo{'ftr'}) { $ftr=$::calinfo{'ftr'};} else {$ftr="";}    
    $shr = $::calinfo{'hourB'};
    $ehr = $::calinfo{'hourE'};

    add_option_tips($opcode, $nopts); 

    print <<END;
<Form name=webcalo action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name="ret_p" value="option">
<input type=hidden name="opcode" value="$opcode">
<input type=hidden name=c value="dooption">
<input type=hidden name=w value="$who">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=homepage value="$homepage">
END
    ;
    

    if($opcode == 0 || $opcode == $nopts) {
	my $opname=$opnames->[0];
	print <<END;
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>
END
;

	use tzlist;
	my ($toffset,$svrtime) =("","");

	print "<table border=0 cellpadding=2 cellspacing=0 class=\"option\">";
	
	my @loct = localtime(time);
	$svrtime = "<font color=\"#006600\">" . mdy_string($loct[4], $loct[3], $loct[5]+1900) . 
	    "</font> <font color=blue>" .  hm_string($loct[2], $loct[1]) ."</font>";
	print "<tr><td><b><span class=\"fmLabel\">$::phr{'Time_zone'}:&nbsp;</span></b></td>
<td align=left>",select_option("tzone",$tzone,@tzlist::timezonelist), 
"<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o0_zone.html\','ohelp',680,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", "</td></tr>\n";
	print "<tr><td valign=top colspan=2>";

	print <<END;
<table border=0><tr><td nowrap>
<font size=-1 color="#ff3300"><span class="fmLabel">$::phr{'OrTimeOffset'}:&nbsp;</span><br></font>
<font size=-1 color="#993300"><span class="fmLabel"> $::phr{'ServerTime'}: $svrtime</span></font>
</td><td><input name='toffset' type=text class="fmEntryS" size=8 value="$toffset"></font></td></tr></table>
</td></tr>
END
    ;

    print "<tr><td colspan=4>&nbsp;</td></tr>";

    my @longformats= @::ldateformat;
    my @shortformats= @::sdateformat;
    my ($dayname, $monthname, $nn, $i, $wcode, $mm, $dd, $yy, $dstyle);
    $mm = $::now{'month'}; $dd = $::now{'day'}; $yy= $::now{'year'};
    $dd = 20 if $dd <= 12;	# make sure the day is not a valid monthnumber
    $wcode=wday($mm, $dd, $yy);
    $dayname = $::wdays[$wcode]; $monthname=$::mname[$mm];
    $nn = 0 +@longformats;
    $mm++;
    for($i=1; $i < $nn; $i+=2) {
	$longformats[$i] =~ s/mm/$mm/g;
	$longformats[$i] =~ s/Dayname/$dayname/g;
	$longformats[$i] =~ s/Monthname/$monthname/g;
	$longformats[$i] =~ s/dd/$dd/g;
	$longformats[$i] =~ s/yyyy/$yy/g;
    }
    $nn = 0 +@shortformats;
    $mm="0$mm" if $mm < 10;
    $dd="0$dd" if $dd < 10;
    for($i=1; $i < $nn; $i+=2) {
	$shortformats[$i] =~ s/mm/$mm/g;
	$shortformats[$i] =~ s/dd/$dd/g;
	$shortformats[$i] =~ s/yyyy/$yy/g;
    }

    print "<tr><td><b><span class=\"fmLabel\">$::phr{'Date_Format'}:&nbsp;</span></b></td><td colspan=3>",
        select_value("dformat",$::o{'dateformat'}, @shortformats),
        select_value("dformat2",$::o{'dateformat2'}, @longformats), "</td></tr>";

    print "<tr><td><b><span class=\"fmLabel\">$::phr{'Time_Format'}:&nbsp;</span></b></td><td colspan=3>",
	select_value("tformat",$::o{'hourformat'},
		     (0,"12 $::phr{'hours'} am/pm",1,"24 $::phr{'hours'}"));
    if($::calinfo{'estyle'}) {$dstyle = 1;} else {$dstyle = 0;}

    print "</tr><tr><td>
<font color=#cd3b3b><b><span class=\"fmLabel\">$::phr{'DpyETimeAs'}:&nbsp;</span></b></font></td><td colspan=3>",   
        select_value("estyle",$dstyle,
		(0,"hh:mm",1,"hh:mm-hh:mm")),
"<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o0_hm.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
"</td></tr>\n";

    if($::calinfo{'toffset'}){
	use integer;
	my ($h, $m, $s, $v); $v = $::calinfo{'toffset'}/60;
	if($v<0) { $s="-"; $v=-$v;} else {$s="";}
	$h= $v/60; $m=$v%60;
	$toffset = $s . sprintf "%02d:%02d", $h, $m;
    }


    print "<tr><td colspan=4>&nbsp;</td></tr>";

    my $dei =60;  if(defined $::calinfo{'dei'}) { $dei = $::calinfo{'dei'};}
    print "<tr><td><b><span class=\"fmLabel\">$::phr{'Calendar'} $::phr{'Interval'}:&nbsp;</span></b></td>
<td>",select_value("interval",$::calinfo{'interval'},
		   (0,"5$::phr{'min'}",10,"10$::phr{'min'}", 15,"15$::phr{'min'}",30,"30$::phr{'min'}",60,"60$::phr{'min'}")),
"<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o0_intv.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", "</td>";

    print "</tr><tr><td><font color=#0099000><b><span class=\"fmLabel\">$::phr{'EventInterval'}:</span></td><td colspan=3><input type=text  class=\"fmEntry\" name=\"dei\" size=3 value=$dei> <span class=\"fmLabel\">$::phr{'mins'}</span></b></font></td></tr>";

    print "<tr><td colspan=4>&nbsp;</td></tr>";

    print "<tr><td><b><span class=\"fmLabel\">$::phr{'Week_begins_on'}:&nbsp;</span></b></td><td colspan=3>",
	select_value("weekstart",$::o{'weekstart'},
		(0,$::wdays[0],1,$::wdays[1]));
    print "</td></tr><tr><td><b><span class=\"fmLabel\">$::phr{'include_weekend'}:&nbsp;</span></b></td><td>";
    print input_radio("eweekend",$::o{'excludeWeekend'}, @::boolList);
    print "</td></tr>\n";

    print "<tr><td colspan=4>&nbsp;</td></tr>";

    print " <tr><td nowrap><b><span class=\"fmLabel\">$::phr{'My_day_starts_at'}:&nbsp;</span></b></td>
<td colspan=3>", selectHour("hourB", $shr), 
"<b><span class=\"fmLabel\">&nbsp;&nbsp;$::phr{'ends_at'}:</span></b>&nbsp;&nbsp;", selectHour("hourE", $ehr), 
"</td></tr>";


	print "<tr><td colspan=4>";

	print "<table border=0 cellpadding=0 cellspacing=1>";
	print "<tr><td colspan=3 class=\"optionx\"><font color=\"#ff0000\"><b><span class=\"fmLabelS\">$::phr{'DetailedWorkingHours'}</span></b></font></td></tr>";
	$ss = 1;
	my ($wklen, $start, $cid);
	$start = $::o{'weekstart'};
	if($::o{'excludeWeekend'}) { $wklen = 5; $start = 1;} else { $wklen = 7;}
	for($jj=0; $jj < $wklen; $jj++) {
	    my ($bname, $ename, $j, $wn, $bgn, $end, $bgnm, $endm, $bgclr,$bmname, $emname);
	    $j = $start + $jj; if($j == 7) { $j = 0;}
	    $wn = $::wdays[$j];
	    $bname = "hourB$j"; $ename = "hourE$j";  $bmname = "minuB$j"; $emname = "minuE$j";
	    if(exists $::calinfo{$bname}) {$bgn = $::calinfo{$bname};} else {$bgn = $shr;}
	    if(exists $::calinfo{$ename}) {$end = $::calinfo{$ename};} else {$end = $ehr;}
	    if(exists $::calinfo{$bmname}) {$bgnm = $::calinfo{$bmname};} else {$bgnm = 0;}
	    if(exists $::calinfo{$emname}) {$endm = $::calinfo{$emname};} else {$endm = 0;}
	    if($j == 0 || $j == 6) { $bgclr="bgcolor=#cccccc"; $cid="option0";}
	    else { $bgclr="bgcolor=$webcalConfig::r{'dkbackground'}"; $cid="option1";}
	    print "<tr><td class=\"$cid\" $bgclr><font color=#ff0099><b><span class=\"fmLabelS\">$wn</span></b></font></td><td class=\"$cid\" $bgclr><font><span class=\"fmLabelS\">$::phr{'Start'}:</span>",
	    selectHour($bname,$bgn), ":", selectMinu($bmname, $bgnm),
	    "<span class=\"fmLabelS\">&nbsp;$::phr{'End'}:</span>", selectHour($ename, $end), ":", selectMinu($emname, $endm),
	    "</font></td></tr>";
	}
	print "</table></td></tr></table>";

    }


  if($opcode == 1 || $opcode == $nopts) {
      my $opname=$opnames->[1];
      print <<END;
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>
END
;


    print "<input type=hidden name=selecttabs value=1>\n";
    print "<table border=0 cellpadding=2 cellspacing=0 class=\"option\">";   
    {
	my($tabs, @alltabs, $tab, $in, $sel, $i);
	$tabs = $::o{'tabs'};
	@alltabs = ('get','task','ad','diary','notes','option');
	$i=0;
	print "<tr><td colspan=4 nowrap><font color=#990000><b><span class=\"fmLabel\">$::phr{'MasterheadTabs'}:</span></b>",
	"<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o1_tab.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
	"</td></tr>";
	print "<tr><td colspan=4 nowrap>&nbsp;";	
	foreach $tab (@alltabs) {
	    $in = ismember($tab, $tabs); if($in){$sel = " checked";} else {$sel="";}
	    print "<input type=checkbox class=\"fmRadio\" name=tab$i value=\"$tab\" $sel><span class=\"fmLabelS\">&nbsp;$::tabNames{$tab}&nbsp;&nbsp;</span>";
	    $i++;
	}
	print "<br></td></tr>\n";
    }
    if($::o{'listAllCals'}) {
	my $ulist=0;
	if(exists  $::calinfo{'ulist'}) { $ulist= $::calinfo{'ulist'};}
	print "<tr><td height=2 colspan=4><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=2 height=2></td></tr>";
	print "<tr><td><table border=0>";
	print "<tr><td height=20 nowrap><font color=\"#000000\"><span class=\"fmLabelS\">&nbsp;&nbsp;$::phr{'MasterHeadInput'} </span></font></td><td>";	
	print "<input type=radio name=ulist value=\"-1\" style=\"background-color:#cccc00\"";
 	print " checked" if $ulist == -1;
	print "><input type=radio name=ulist value=1";
	print " checked" if $ulist == 1;
	print "><font color=#cc00cc><b><span class=\"fmLabelS\">&nbsp;$::phr{'TextEntry'}</span></b></font>",
	"<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o1_entry.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
	"</td></tr>";
	
	print "<tr><td><font size=1>&nbsp;</font></td><td>";
	print "<input type=radio name=ulist value=2";
	print " checked" if $ulist == 2;
        print "><input type=radio name=ulist value=3 style=\"background-color:#cccc00\"";
	print " checked" if $ulist == 3;
	print ">";
	print "<font color=#0066ff><b><span class=\"fmLabelS\">&nbsp;$::phr{'PulldownMenu'}</span></b></font>";
	print "</td></tr>";
	print "</table></td></tr>";
    }
    print "<tr><td colspan=4>
<table border=0 cellspacing=0 cellpadding=2><tr><td>&nbsp;<br></td></tr>";
    if($::d{'multilingual'}) {
      print "<tr><td><b><font color=#ff0000><span class=\"fmLabel\">$::phr{'Language'}:</span></font>&nbsp;</b></td>
<td colspan=3 align=left>",select_option("slanguage",$::o{'language'},@{$webcalConfig::r{'languageList'}}),"</td></tr>\n";
    }
    my $atmp; if(defined $::calinfo{'aname'}) { $atmp =$::calinfo{'aname'};} else { $atmp=0;}
    print "<tr><td>
<b><span class=\"fmLabel\">$::phr{'DpyAuthorName'}&nbsp;</span></b></td><td colspan=3>",
	select_value("aname",$atmp,
		     (1, $::phr{'RealName'}, 2, $::phr{'CalendarName'}, 0, $::phr{'Rname_Cname'})
		     ),
		     "</td></tr>";
    print "
<tr><td><b><span class=\"fmLabel\">$::phr{'Default_view'}:</span>&nbsp;</b></td>
<td colspan=3>", select_value("dview",$view, (1,"$::phr{'DayView'}",2,"$::phr{'WeekView'}",3,"$::phr{'MonthView'}",4,"$::phr{'YearView'}")), "&nbsp;+&nbsp;", select_value("dlist",$ls, @::lsList),
"<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o1_views.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
"</td></tr>";
    my $dayview = $::calinfo{'dayview'} || 0;
    print "
<tr><td><b><span class=\"fmLabel\">$::phr{'DayViewOptions'}:&nbsp;</span></b></td>
<td colspan=3>", select_value("dayview",$dayview, (0x10000,"$::phr{'DetailedView'}",0x20000,"$::phr{'BannerView'}",0x40000,"$::phr{'CombinedView'}",)),
"<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o1_dayview.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
"</td></tr>";

    my $weekview = $::calinfo{'weekview'} || 0;
    print "
<tr><td><b><span class=\"fmLabel\">$::phr{'WeekViewOptions'}:&nbsp;</span></td>
<td colspan=3>", select_value("weekview",$weekview, (0x100000,"$::phr{'DetailedView'}",0x0,"$::phr{'CombinedView'}")),
"<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o1_weekview.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
"</td></tr>";
    my $tooltipdelay=0; if($::calinfo{'tooltipDelay'}){$tooltipdelay=$::calinfo{'tooltipDelay'};}
    print <<END;
<tr><td><span class="fmLabel">$::phr{'TooltipDelay'}:</span></td>
<td colspan=3><input type=text name=tdelay value="$tooltipdelay" size=10 class="fmEntry"></td></tr>
END
    ;
    print "<tr><td><font size=1>&nbsp;</font></td></tr>";
    {
	print "<tr><td colspan=2 align=center><table border=0>";
	if($::o{'autostart'}) {
	    my $autotmp; if($::calinfo{'autostart'}) { $autotmp = 0;} else {$autotmp = 1;}
	    print "
<tr><td><font color=#cd3b3b><b><span class=\"fmLabel\">$::phr{'AutoStart'}:&nbsp;</span></b></font></td><td align=left colspan=2>";
	    print "<font color=#cd3b3b><b>", input_radio("autostart",$autotmp, @::boolList), "</b></font>";
	    print "</td></tr>";
	}

	 print "<tr><td><table border=0>";	
	my $tmp;
	 if($::o{'category_filter'}) {
	     my $url="$::o{'cgimisc'}?w=$who&cmd=efile&file=cats";
	     my $v = "<a href=\"javascript:openpopup('$url','cats',680,600)\"><img src=\"$::o{imgdirurl}/q1.gif\" width=15 height=15 border=0></a>";
	     $tmp = 0;  if($::calinfo{'cfilter'}) { $tmp=1;}
	     print "<tr><td><span class=\"fmLabel\">$::phr{'catfilter'} &nbsp;$v</span></td><td>";
	     print input_radio("cfilter", $tmp, @::switchList);	 
	     print "</td></tr>\n";
	 }
	$tmp = 0;  if($::calinfo{'dmode'}) { $tmp=1;}
	 print "<tr><td><span class=\"fmLabel\">$::phr{'popdetail'} &nbsp;</span></td><td>";
	 print input_radio("dmode", $tmp, @::switchList);	 
	 print "</td></tr>\n";
	my($ck1, $ck0, $tk1, $tk0) = ("","","","");
	if($::calinfo{'dctoc'}) { $ck1 = "checked";} else { $ck0="checked";}
	if($::calinfo{'tarf'}) { $tk1 = "checked";} else { $tk0="checked";}
	print "<tr><td><font size=1>&nbsp;</font></td></tr>";
	print <<END;
<tr><td>
<span class="fmLabel">$::phr{'DispCompletedTasks'}:&nbsp;</span></td><td>
<input type=radio name=dctoc value=1 class="fmRadio" $ck1><span class="fmLabel"> $::phr{'Y'} </span>
<input type=radio name=dctoc value=0 class="fmRadio" $ck0><span class="fmLabel"> $::phr{'N'}</span>
</td></tr>
<tr><td>
<span class="fmLabel">$::phr{'RemindForwardNewTask'}:&nbsp;</span></td><td>
<input type=radio name=tarf value=1 $tk1><span class="fmLabel"> $::phr{'Y'} </span>
<input type=radio name=tarf value=0 $tk0><span class="fmLabel"> $::phr{'N'}</span>
</td></tr>
END
    ;
	print "</table></td></tr>";
    }
    print "</table></td></tr></table>";
    print "</td></tr></table>";
} 


 if($opcode == 2 || $opcode == $nopts) {
     my $opname=$opnames->[2];
     print <<END;
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>
END
;

    print "<table border=0 cellpadding=0 cellspacing=0 class=\"option\">";
    print "<tr><td><b><span class=\"fmLabel\">$::phr{'CalendarType'}:&nbsp;</span></b></td>
<td nowrap>", select_value("ctype",$ctype, @::ctypeList), 
    "<input type=hidden name=\"octype\" value=\"$ctype\">",
"<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o2_ctype.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
"</td></tr>"; 
    print "<tr><td nowrap>
<span class=\"fmLabel\"><font color=#ff0000><b>$::phr{'Privacy'}:</b>&nbsp;</font></span><span class=\"fmLabelS\"><font size=1>($::phr{'ForPrivateCalendar'})</font></span></td><td>",select_value("privacy",$::calinfo{'privacy'},@::privacyList),
"<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o2_privacy.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
"</td></tr>";
    
    print "<tr><td><font size=1>&nbsp;</td></tr>";
    {
	my $oltmp; if(defined $::calinfo{'ol'}) { $oltmp = $::calinfo{'ol'};} else {$oltmp = 0;} # 0 allow, 1 disallow
	print "<tr><td><font color=#cd3b3b><b><span class=\"fmLabel\">$::phr{'AllowOverlap'}:&nbsp;</span></b></font></td><td nowrap>";
	print "<font color=#cd3b3b size=2><b>", input_radio("sol",$oltmp, 
							    (0,"$::phr{'Y'}", 1,"$::phr{'N'}", 2, "$::phr{'Never'}")),"</b></font>";

	print "<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o2_overlap.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>"; 
	print "</td></tr>";    
    }

    print "<tr><td><font size=1>&nbsp;</td></tr>";
    print "<tr><td colspan=2><table border=0 cellpadding=0>"; 
    my $tmp = 0;  if($::calinfo{'aap'}) { $tmp=1;}
    print "<tr><td><font color=#000099><span class=\"fmLabel\">$::phr{'AllowAP'} &nbsp;</span>",
     "<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o2_anapost.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
     "</td><td>";
    print input_radio("aap", $tmp, @::switchList);
    print "</font></td></tr>\n";
    $tmp = 0;  if($::calinfo{'nap'}) { $tmp=1;}
    print "<tr><td><font color=#000099><span class=\"fmLabel\">$::phr{'NotifyAP'} &nbsp;</span>",
     "<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o2_emailpost.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
     "</td><td>";
    print input_radio("nap", $tmp, @::switchList);
    print "</font></td></tr>\n";
    $tmp =0; if($::calinfo{'resrc'}) { $tmp=1;}
    print "<tr><td><font color=#009900><span class=\"fmLabel\">$::phr{'ResrcCal'} &nbsp;</span>",
     "<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o2_rsrccal.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
     "</td><td>";
    print input_radio("resrc", $tmp, @::switchList);
    print "</font></td></tr>\n";
    print "</table></td></tr>";
    print "</table>";
}


    if($opcode == 3 || $opcode == $nopts) {
	my $opname=$opnames->[3];
	print <<END;
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>
END
;
    print "
<input type=hidden name=setdefaultreminder value=1>
<table border=0 cellpadding=2 cellspacing=0 class=\"option\">    
";
    print "<tr><td colspan=2>\n";
    print "<table border=0 cellpadding=2 cellspacing=0>\n";
    {
      my ( $reminder, $mail, $flash, $popup, $chime,
	   $mailu, $maili, $maily, $flashi, $flashu, $flashy, $popupi, $popupu, $popupy,
	   $chimeu, $chimei, $chimey);
      if(defined $::calinfo{'drem'}) {$reminder= $::calinfo{'drem'}; } else { $reminder="rf:n:5:m,rm:n:5:m,rp:n:5:m,rc:n:5:m";}
      ($flash,$mail,$popup, $chime)=split(/,/, $reminder);
      (undef, $maily, $maili,$mailu) = split(/:/, $mail);
      (undef, $flashy, $flashi,$flashu) = split(/:/, $flash);
      (undef, $popupy, $popupi,$popupu) = split(/:/, $popup);
      (undef, $chimey, $chimei,$chimeu) = split(/:/, $chime);
      if(not $maili) { $maili = 5;}
      if(not $flashi) { $flashi = 5;}
      if(not $popupi) { $popupi = 5;}
      if(not $chimei) { $chimei = 5;}

      print "<tr><td><b><span class=\"fmLabel\">$::phr{'Popup'}:</span></b>&nbsp;</td>\n<td noWrap colspan=3>";
      print input_radio("drpopup",$popupy,@::nyList);
      print "
<input type=text size=4 maxlength=36 name=drpopupv value=\"$popupi\" class=\"fmEntry\"> ";
      print "\n",select_value("drpopupu",$popupu,@::unitmList),
      "<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o3_reminder.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
      "</td>";

      print "</tr><tr>\n";
      print "<td><b><span class=\"fmLabel\">$::phr{'Blink'}:</span></b>&nbsp;</td>\n<td noWrap colspan=3>";
      print input_radio("drflash",$flashy,@::nyList);
      print "
<input type=text size=4 maxlength=36 name=drflashv value=\"$flashi\" class=\"fmEntry\"> ";
      print "\n",select_value("drflashu",$flashu,@::unitmList),"</td></tr>\n";
      
      print "<tr><td><b><span class=\"fmLabel\">$::phr{'Mail'}:</span></b>&nbsp;</td>\n<td noWrap colspan=3>";
      print input_radio("drmail",$maily,@::nyList);
      print "<input type=text size=4 maxlength=36 name=drmailv value=\"$maili\" class=\"fmEntry\"> ";
      print "\n",select_value("drmailu",$mailu,@::unitmList),"</td>\n";
      print "</tr><tr>\n";
      print "<td><b><span class=\"fmLabel\">$::phr{'Chime'}:&nbsp;</span></b></td>\n<td colspan=3>";
      print input_radio("drchime",$chimey,@::nyList);
      print "<input type=text size=4 maxlength=36 name=drchimev value=\"$chimei\" class=\"fmEntry\"> ";
      print "\n",select_value("drchimeu",$chimeu,@::unitmList),"</td></tr>\n";
      print "</table></td></tr>";
  }
    print "<tr><td><font size=1>&nbsp;</font></td></tr>";

    print "<tr><td><b><span class=\"fmLabel\">$::phr{'mailVcal'}:&nbsp;</span></td><td>";
    my $vtmp; if($::calinfo{'vcal'}) { $vtmp = 0;} else {$vtmp = 1;} #0 for yes
    print input_radio("vcal", $vtmp, @::boolList);
    print "</td></tr>";
    print "<tr>
<td><font color=#cd3b3b><b><span class=\"fmLabel\">$::phr{'DailyReminder'}:&nbsp;</span></td><td>";
    if($::calinfo{'dr'}) { $vtmp = 0;} else {$vtmp = 1;} #0 for yes
    print input_radio("dr", $vtmp, @::boolList);
    print "</b></font></tr>\n";

    print "<tr><td><font size=1>&nbsp;</font></td></tr>";
    print "</table>\n";

}

    if($opcode == 4 || $opcode == $nopts) {
	my $opname=$opnames->[4];
	print <<END;
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>
END
;

	print "<table border=0 cellpadding=2 cellspacing=0 class=\"option\">";
    {
	my ($themecolor, $i, $clr);
	if(exists  $::calinfo{'themecolor'}) { $themecolor= $::calinfo{'themecolor'};} else { $themecolor= -1;}
	print "<tr><td nowrap><b><span class=\"fmLabel\">$::phr{'HeaderColor'}:&nbsp;</span></b></td><td>";
	for($i=0; $i<=6; $i++) {
	    $clr = $::themeColors[$i];
	    print "<input type=radio name=themecolor class=\"fmRadio\" value=$i";
	    print " checked" if $themecolor == $i;
	    print "><span class=\"fmLabelS\"><font color=$clr>&nbsp;ABC&nbsp;&nbsp;</font></span>";
	    if($i==4) { print "</td></tr><td>&nbsp;</td><td>";}
	}
	print "<input type=radio class=\"fmRadio\" name=themecolor value=\"-1\"";
	if($themecolor== -1) { print " checked"; }
	print "><span class=\"fmLabel\">&nbsp;$::phr{'All'}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>";
	print "<input type=radio class=\"fmRadio\" name=themecolor value=\"-2\"";
	if($themecolor== -2) { print " checked"; }
	print "><span class=\"fmLabel\">&nbsp;$::phr{'Default'}</span><br><br></td></tr>";
    }

      my ($afg, $abg, $tfg, $tbg, $sfg, $sbg, $mfg, $mbg)=("","","","","","","","");
      if(exists $::calinfo{'dafg'}) {$afg= $::calinfo{'dafg'};} if(exists $::calinfo{'dabg'}) {$abg= $::calinfo{'dabg'};}
      if(exists $::calinfo{'dtfg'}) {$tfg= $::calinfo{'dtfg'};} if(exists $::calinfo{'dtbg'}) {$tbg= $::calinfo{'dtbg'};}
      if(exists $::calinfo{'dmfg'}) {$mfg= $::calinfo{'dmfg'};} if(exists $::calinfo{'dmbg'}) {$mbg= $::calinfo{'dmbg'};}
      if(exists $::calinfo{'dsfg'}) {$sfg= $::calinfo{'dsfg'};} if(exists $::calinfo{'dsbg'}) {$sbg= $::calinfo{'dsbg'};}

      print "<tr><td colspan=2><span class=\"fmLabel\"><b>$::phr{'defaultEColors'}</b></span>",
	"<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o4_colors.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>",
	"</td></tr>";
      print "<tr>";
      print "<td nowrap><input type=button name=\"abtn\" class=\"fmBtn\" onclick=\"openpopup('$::o{'cginame'}?c=showclra&w=$who','clrs',500,480)\" value=\"$::phr{'Appointment'}\"></td>
<td noWrap>";
      print "<span class=\"fmLabel\">&nbsp;$::phr{'Fg'}:</span> <input type=text class=\"fmEntry\" size=7 name=afg value=\"$afg\" onChange=\"showclr('a')\"><span class=\"fmLabel\">&nbsp;$::phr{'Bg'}: </span><input type=text size=7  class=\"fmEntry\" name=abg value=\"$abg\" onChange=\"showclr('a')\"></td>\n";
      print "</tr><tr>\n";
      print "<td nowrap><input type=button name=\"tbtn\" class=\"fmBtn\" onclick=\"openpopup('$::o{'cginame'}?c=showclrt&w=$who','clrs',500,480)\" value=\"$::phr{'Todo'}\"></td>
<td noWrap colspan=3>";
      print "<span class=\"fmLabel\">&nbsp;$::phr{'Fg'}: </span><input type=text class=\"fmEntry\" size=7 name=tfg value=\"$tfg\" onChange=\"showclr('t')\"><span class=\"fmLabel\">&nbsp;$::phr{'Bg'}: </span><input type=text size=7 class=\"fmEntry\" name=tbg value=\"$tbg\" onChange=\"showclr('t')\"></td>\n";
      print "</tr>\n";
      print "<tr>";
      print "<td nowrap><input type=button name=\"mbtn\" class=\"fmBtn\" onclick=\"openpopup('$::o{'cginame'}?c=showclrm&w=$who','clrs',500,480)\" value=\"$::phr{'Meeting'}\"></td>
<td noWrap colspan=3>";
      print "<span class=\"fmLabel\">&nbsp;$::phr{'Fg'}: </span><input type=text class=\"fmEntry\" size=7 name=mfg value=\"$mfg\" onChange=\"showclr('m')\"><span class=\"fmLabel\">&nbsp;$::phr{'Bg'}: </span><input type=text size=7 class=\"fmEntry\" name=mbg value=\"$mbg\" onChange=\"showclr('m')\"></td>\n";
      print "</tr><tr>\n";
      print "<td nowrap><input type=button name=\"sbtn\" class=\"fmBtn\" value=\"$::phr{'Special'}\" onclick=\"openpopup('$::o{'cginame'}?c=showclrs&w=$who','clrs',500,480)\"></td>
<td noWrap colspan=3>";
      print "<span class=\"fmLabel\">&nbsp;$::phr{'Fg'}: </span><input type=text class=\"fmEntry\" size=7 name=sfg value=\"$sfg\" onChange=\"showclr('s')\"><span class=\"fmLabel\">&nbsp;$::phr{'Bg'}: </span><input type=text size=7  class=\"fmEntry\" name=sbg value=\"$sbg\" onChange=\"showclr('s')\"></td>\n";
    print "</tr>\n";

      my ($apair, $tpair,$mpair,$spair);
      $apair = $::calinfo{'apair'};      $tpair = $::calinfo{'tpair'};
      $mpair = $::calinfo{'mpair'};      $spair = $::calinfo{'spair'};
      $apair ="" unless $apair; $tpair ="" unless $tpair; $mpair ="" unless $mpair; $spair ="" unless $spair;
      print <<END;
<tr><td colspan=4 nowrap><br>
<input type=hidden name="apair" value="$apair">
<input type=hidden name="tpair" value="$tpair">
<input type=hidden name="mpair" value="$mpair">
<input type=hidden name="spair" value="$spair">
<b><span class="fmLabel">$::phr{'PredefineColorPairs'} &nbsp;</span>
<a href="javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o4_colorpair.html\','ohelp',640,600)"><img src="$::o{imgdirurl}/q.gif" width=17 height=15 border=0></a> 
<br><br>
<font color="#ff0000"><input type=button name=bapair value=" $::phr{'Appointment'} " class="fmBtn"
onclick="openpopup('$::o{'cginame'}?c=cpair&e=a','cpairs',500,500)"></font>
&nbsp;
<font color="#009900"><input type=button name=btpair value=" $::phr{'Todo'} " class="fmBtn"
onclick="openpopup('$::o{'cginame'}?c=cpair&e=t','cpairs',500,500)"
></font> 
&nbsp;
<font color="#cc00cc"><input type=button name=bmpair value=" $::phr{'Meeting'} " class="fmBtn"
onclick="openpopup('$::o{'cginame'}?c=cpair&e=m','cpairs',500,500)"
></font>
&nbsp;
<font color="#0066ff"><input type=button name=bspair value=" $::phr{'Special'} " class="fmBtn"
onclick="openpopup('$::o{'cginame'}?c=cpair&e=s','cpairs',500,500)"
></font>
</b> 
<br>
<br>
</td>
</tr>
</table>
END
    ;

}


    if($opcode == 5 || $opcode == $nopts) {
	my $opname=$opnames->[5];
	print <<END;
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>
END
;

    print "<table border=0 cellpadding=2 cellspacing=0 class=\"option\">";

    my $aref = $webcalConfig::r{'cssFiles'};
    if( 0+@$aref > 1) {
	my (@array,$lst, $editcss); $editcss="";
	my ($cfile, $dcsf); $cfile = "$::o{'spooldir'}/$who/default.css"; $dcsf= $::calinfo{'dcsf'} || "";
	my $eurl="$::o{'cgicss'}?c=pdefault&w=$who";    
	my $bgcolor= $::calinfo{'bgcolor'} || "";
	my $sheet_name = ""; my $label;
	if(-f $cfile) {
	    (@array) = ("$who-default.css", @$aref);
	    $sheet_name = "$who-default.css";   $label = $::phr{'editCSS'};
	} else {
	    (@array) = (@$aref);   $label = $::phr{'createCSS'};
	}
	$editcss =<<END;
<a href="javascript:openpopup('$eurl','editcss',680,600)"><img src="$::o{'imgdirurl'}/carrow.gif" width=17 height=17 border=0 title=""><span class="fmLabel"><font color=blue><b>$label.</b></font> $sheet_name</span></a>
END
    ;
	$lst = select_optionV('dcsf',$dcsf, "onchange=\"javascript:spbg()\"", ("????", @array));
	print <<END;
<tr><td>
<script language="javascript">
var pdbg="$bgcolor";
function spbg() {
var fm=window.document.webcalo; var si= fm.dcsf.selectedIndex; var sv=fm.dcsf.options[si].value; 
if(sv=="default.css"||sv=="harry.css"||sv=="transparent.css"){fm.dbgcolor.value="#ffffff";}
else if(sv == "dark.css") { fm.dbgcolor.value="#000000";} else {fm.dbgcolor.value=pdbg;}
}
function showcss(i) {
var s=eval('window.document.webcalo.css'+i);var j=s.selectedIndex; var v=s.options[j].value; 
var t=document.getElementById('axcss'+i); if(t) {t.className=v;}
}
</script>
<b><span class="fmLabel">$::phr{StyleSheet}:</span></b></td nowrap><td>$lst</td>
<td><span class="fmLabel"> $::phr{'BackgroundColor'}:</span>
<input type=text class="fmEntry" size=7 name="dbgcolor" value="$bgcolor">
<a href="javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o5_bgclr.html\','ohelp',680,600)"><img src="$::o{imgdirurl}/q.gif" width=17 height=15 border=0></a>
</td></tr>
<tr><td colspan=2><br>$editcss
<a href="javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=csi.html\','ohelp',680,600)"><img src="$::o{imgdirurl}/q.gif" width=17 height=15 border=0></a>
<br><br></td></tr>
END
    ;
    }

#if(-f "$::o{'spooldir'}/$who/css.css") {
    my($cst, $sid) = user_defined_css('css1', $::calinfo{'css1'},1, "onchange=\"showcss(1)\"");
    my $eurl="$::o{'cgicss'}?c=post&w=$who"; 
    print "<tr><td nowrap colspan=2><a href=\"javascript:openpopup('$eurl','cfonts',680,600)\"";
    if($sid) { print "onMouseOver=\"showtip(event,\'$sid\')\" onMouseOut=\"hidetip(\'$sid\')\""; }
    print "><img src=\"$::o{'imgdirurl'}/carrow.gif\" width=17 height=17 border=0 title=\"\"><font color=blue><span class=\"fmLabel\"><b>$::phr{'eventCSS'}.</b></span></font></a> ",
	"<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o5_css4.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
	"</td></tr>";
    if( scalar keys %::css > 0) {
	my $zid; $zid=$::calinfo{'css1'} || 'noborder';
	print "<tr>";
        print "<td nowrap><span class=\"fmLabel\">$::phr{'Appointment'}:</span></td><td>", $cst, 
	"</td><td id='axcss1' class=\"$zid\">ABCD1234</td></tr>";
	($cst, $sid) = user_defined_css('css2', $::calinfo{'css2'},0,"onchange=\"showcss(2)\"");
	$zid=$::calinfo{'css2'} || 'noborder';
	print "<tr><td><span class=\"fmLabel\">$::phr{'Todo'}:</span></td><td>", $cst, 
	"</td><td id='axcss2' class=\"$zid\">ABCD1234</td></tr>";
	print "<tr>";
	($cst, $sid) = user_defined_css('css3', $::calinfo{'css3'},0,"onchange=\"showcss(3)\""); 
	$zid=$::calinfo{'css3'} || 'noborder';
	print "<td nowrap><span class=\"fmLabel\">$::phr{'Meeting'}:</span></td><td>", $cst, 
	"</td><td id='axcss3' class=\"$zid\" >ABCD1234</td></tr>";
	($cst, $sid) = user_defined_css('css4', $::calinfo{'css4'},0,"onchange=\"showcss(4)\"");
	$zid=$::calinfo{'css4'} || 'noborder';
	print "<tr><td ><span class=\"fmLabel\">$::phr{'Special'}:</span></td><td>", $cst, 
	"</td><td id='axcss4' class=\"$zid\">ABCD1234</td></tr>";
    }
#}
    print "</table>\n";

}

    if($opcode == 6 || $opcode == $nopts) {
	my $opname=$opnames->[6];
	print <<END;
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>
END
;

    $::calinfo{'_clist_'} = 1;    
    my ($textfield,$selectfield) = select_multicals("editors",$::calinfo{'editors'}, 50);

    print <<END;
<table border=0 class="option"><tr><td align=center>   
<table border=0 cellpadding=0 cellspacing=0 width="100%">
<tr><td></td><td colspan=3 nowrap><font color="#ff0000" size=-1><span class=\"fmLabelS\">$::phr{'ListEditors'}</span></font></td></tr>
<tr><td align=right>
<a href="javascript:openpopup('$::o{'cginame'}?c=listcal&w=$who',\'calendars\',500,400)"><font color="#000000"><b><span class=\"fmLabel\">$::phr{'Editors'}:&nbsp;</span></b></font></a></td><td colspan=3>$textfield</td></tr>
END
    ;    
    if ($::o{'listAllCals'}) {
	print "<tr><td><br></td><td colspan=3>",
	"<table border=0 cellspacing=0 cellpadding=0><tr><td valign=top>",
	$selectfield, "&nbsp;&nbsp;</td><td width=400 align=left>",
	"<blockquote class=\"fmMsg\">", $::phr{'MkEditorListInstruction'}, "</blockquote>",	
	"</td></tr></table>",
	"</td></tr>\n";
    }

    print "<tr><td><br></td></tr>", 
    "<tr><td></td><td colspan=3><font color=#0000cc size=-1><span class=\"fmLabelS\">$::phr{'ListReaders'}</span></font></td></tr>";
    if(!defined $::calinfo{'readers'}) { $::calinfo{'readers'} = "";}
    ($textfield,$selectfield) = select_multicals("readers",$::calinfo{'readers'},50);
    print "<tr><td align=right>
<a href=\"javascript:openpopup(\'$::o{'cginame'}?c=listcal&w=$who\',\'calendars\',500,400)\"><font color=#000000><b><span class=\"fmLabel\">$::phr{'Readers'}:&nbsp;</span></b></font></a></td><td colspan=3>$textfield</td></tr>\n";    
    if ($::o{'listAllCals'}) {
	print "<tr><td><br></td><td colspan=3>",
	"<table border=0 cellspacing=0 cellpadding=0><tr><td valign=top>",
	$selectfield, "&nbsp;&nbsp;</td><td width=400>",
	"<blockquote class=\"fmMsg\">", $::phr{'MkReaderListInstruction'}, "</blockquote>",	
	"</td></tr></table>",
	"</td></tr>\n";
    }
    delete $::calinfo{'_clist_'};

    if(not $::calinfo{'ctype'} or $::calinfo{'ctype'} !~ 'public') {
	my $tmp;
	if(defined $::calinfo{'pnotes'}) { $tmp = $::calinfo{'pnotes'};} else {$tmp = 0;}
	print "<tr><td colspan=4 class=\"option\"><br><table border=0>";
	print "<tr><td>&nbsp;</td><td><span class=\"fmLabel\">$::phr{'G_A_Notes'}</span></td><td>", select_value("pubnotes",$tmp,@::accessList), "</td></tr>";
	if(defined $::calinfo{'paddress'}) { $tmp = $::calinfo{'paddress'};} else {$tmp = 0;}
	print "<tr><td>&nbsp;</td><td><span class=\"fmLabel\">$::phr{'G_A_Address'}</span></td><td>",select_value("pubaddr",$tmp,@::accessList), "</td></tr>";
	if(defined $::calinfo{'pdiary'}) { $tmp = $::calinfo{'pdiary'};} else {$tmp = 0;}
	print "<tr><td>&nbsp;</td><td><span class=\"fmLabel\">$::phr{'G_A_Diary'}</span></td><td>", select_value("pubdiary",$tmp,@::accessList), "</td></tr>";
	print "</table></td></tr>\n";
    } else {
	my $tmp;
	if(defined $::calinfo{'pnotes'}) { $tmp = $::calinfo{'pnotes'};} else {$tmp = 0;}
	print "<input type=hidden name=\"pubnotes\" value=\"$tmp\">";
	if(defined $::calinfo{'paddress'}) { $tmp = $::calinfo{'paddress'};} else {$tmp = 0;}	
	print "<input type=hidden name=\"pubaddr\" value=\"$tmp\">";
	if(defined $::calinfo{'pdiary'}) { $tmp = $::calinfo{'pdiary'};} else {$tmp = 0;}
	print "<input type=hidden name=\"pubdiary\" value=\"$tmp\">";
    }

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


}


    if($opcode == 7 || $opcode == $nopts) {
	my $opname=$opnames->[7];
	print <<END;
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>
END
;

    my ($textfield,$selectfield);

    print <<END;
<table border=0 cellpadding=0 cellspacing=0 width="100%" class="option">
END
    ;
    print "<tr><td><br></td><td colspan=3><br><span class=\"fmLabelS\">$::phr{'InterestedCalendars'}</span></td></tr>";
    ($textfield,$selectfield) = select_multicals("clist",$::calinfo{'clist'}, 50);
    print "<tr><td align=right>
<a href=\"javascript:openpopup(\'$::o{'cginame'}?c=listcal&w=$who\',\'calendars\',500,400)\">
<b><font color=#ff0000><span class=\"fmLabel\">$::phr{'CalendarNames'}:&nbsp;</span></font></b></a></td><td colspan=3>$textfield</td></tr>\n";    
    if ($::o{'listAllCals'}) {
        print "<tr><td><br></td><td colspan=3>",
	"<table border=0 cellspacing=0 cellpadding=0><tr><td valign=top>",
	$selectfield, "&nbsp;&nbsp;</td><td width=400>",
	"<blockquote class=\"fmMsg\">", $::phr{'CalendarListInstruction'}, "</blockquote>",	
	"</td></tr></table>",
	"</td></tr>\n";
    }


#=========================
    if($::o{'dependency'} and !ismember($who, $::o{'corporate_calendar'}))  {
	($textfield,$selectfield) = select_multicals("dcs",$::calinfo{'dcs'}, 50);
	print "<tr><td>&nbsp;</td></tr>";
	print "<tr><td>&nbsp;</td></tr>";
	print "<tr><td align=right nowrap>
<a href=\"javascript:openpopup(\'$::o{'cginame'}?c=listcal&w=$who\',\'calendars\',500,400)\">
<b><font color=#009900><span class=\"fmLabel\">$::phr{'DependentCals'}</span></font>:&nbsp;</b></a></td><td colspan=3>$textfield</td></tr>\n";    
	if ($::o{'listAllCals'}) {
	    print "<tr><td ><br></td><td colspan=3>",
	    "<table border=0 cellspacing=0 cellpadding=0><tr><td valign=top>",
	    $selectfield, "&nbsp;&nbsp;</td><td width=400>",
	    "<blockquote class=\"fmMsg\">", $::phr{'DepCalInstruction'}, "</blockquote>",	
	    "</td></tr></table>",
	    "</td></tr>\n";
	}
    }
#=========================
    if($::o{'authorize_author'}) {
	($textfield,$selectfield) = select_multicals("authors",$::calinfo{'authors'}, 50);
	print "<tr><td>&nbsp;</td></tr>";
	print "<tr><td>&nbsp;</td></tr>";
	print "<tr><td align=right>
<a href=\"javascript:openpopup(\'$::o{'cginame'}?c=listcal&w=$who\',\'calendars\',500,400)\">
<b><font color=#0000ff><span class=\"fmLabel\">$::phr{'ListAuthors'}</span></font>:&nbsp;</b></a></td><td colspan=3>$textfield</td></tr>\n";    
	if ($::o{'listAllCals'}) {
	    print "<tr><td><br></td><td colspan=3>",
	    "<table border=0 cellspacing=0 cellpadding=0><tr><td valign=top>",
	    $selectfield, "&nbsp;&nbsp;</td><td width=400>",
	    "<blockquote class=\"fmMsg\">", $::phr{'AuthorInstruction'}, "</blockquote>",	
	    "</td></tr></table>",
	    "</td></tr>\n";
	}
    }

#=========================
    if($::o{'corporate_calendar'}) {
	my $ignore = 0; if( -f "$::o{'spooldir'}/$who/no_ccal") { $ignore=1;}
	my $tmp = input_radio("ignore_ccal",$ignore, @::switchList);
	print "<tr><td><br></td></tr>";
	print "<tr><td colspan=4><b><span class=\"fmLabel\">&nbsp; &nbsp; &nbsp; $::phr{'IgnoreCCal'}:</span> $tmp</b>",
	"<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o7_ignoreccal.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>", 
	"</td></tr>";
    }
#=========================
    print "</table>\n";

}


    if($opcode == 8 || $opcode == $nopts) {
	my $opname=$opnames->[8];
	print <<END;
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>
END
;

    my ($dname); 
    if(exists $::calinfo{'name'}){  $tt=$::calinfo{'name'};} else {$tt="";}
    if(exists $::calinfo{'dname'}){ $dname=$::calinfo{'dname'};} else {$dname="";}
    if(exists $::calinfo{'email'}){  $uu=$::calinfo{'email'};} else {$uu="";}
    if(exists $::calinfo{'homepage'}) {$vv=$::calinfo{'homepage'};} else {$vv="";}
    print <<END;
<br>
<table border=0 width="85%" class="option"><tr><td align=center>   
 <table border=0 cellpadding=0 cellspacing=0  width="100%">
<tr><td align=right><b><span class="fmLabel">$::phr{'OwnerName'}:&nbsp;</span></b></td>
<td colspan=3><input type=text size=40 maxlength=256 name=name value="$tt" class="fmEntry"></td></tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'DescriptiveName'}:&nbsp;</span></b></td>
<td colspan=3><input type=text size=40 maxlength=256 name=dname value="$dname" class="fmEntry"></td></tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'OwnerEmailAddress'}:&nbsp;</span></b></td>
<td colspan=3><input type=text size=40 maxlength=256 name=email value="$uu" class="fmEntry"></td></tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'OwnerHomepage'}:&nbsp;</span></b></td>
<td colspan=3><input type=text size=40 maxlength=256 name=homepage value="$vv" class="fmEntry"></td></tr>
</table></td></tr></table>
END
    ;


}


    if($opcode == 9 || $opcode == $nopts) { #header footer
	my $opname=$opnames->[9];
	print <<END;
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>
END
;


    my ($xcode,$ycode,$dcode);
    if(exists $::calinfo{'xcode'}) {$xcode=$::calinfo{'xcode'};} else {$xcode="";}
    if($::calinfo{'ycode'}) {$ycode=1;} else {$ycode=0;}
    $dcode=input_radio('dcode',$ycode,@::switchList);	
    print <<END;
<br>
<br>
<input type=hidden name=hx value=4>
<table border=0 width="85%" class="option"><tr><td align=center>   
   <table border=0 cellpadding=0 cellspacing=0  width="100%">
<tr><td><br></td><td colspan=3>
<font size=-1 color="#ff0000"><span class="fmLabelS">$::phr{'HeaderFooter'}.&nbsp;</span>
<a href="javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=o9_hdrftr.html\','ohelp',640,600)"><img src="$::o{imgdirurl}/q.gif" width=17 height=15 border=0></a>&nbsp;&nbsp;&nbsp;&nbsp;
<input name=ccode size=8 value="$xcode" style="font-size:xx-small;border-width:0"></font>
</td></tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'Header'}:&nbsp;</span></b></td>
<td colspan=3><textarea rows=6 cols=40 name=hdr class="fmText">$hdr</textarea></td></tr>
 <tr><td>&nbsp;</td></tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'Footer'}:&nbsp;</span></b></td>
<td colspan=3><textarea rows=6 cols=40 name=ftr class="fmText">$ftr</textarea></td></tr>
<tr><td><br></td><td colspan=3><span class="fmLabel">$::phr{'UseHeaderCode'}:$dcode</td></tr>
</table></td></tr></table>
END
    ;
    }

    print <<END;
<br>
<table border=0 width="85%" class="option"><tr><td align=center>
 <tr><td align=center ><br>
 <input type=submit name=action class="fmBtnSt" value="$::phr{'Submit'}">&nbsp;&nbsp;
 <input type=submit name=action class="fmBtnSt" value="$::phr{'Cancel'}"></td></tr>
</table>
</center></Form>
END
;


}
#==================================================================================================================
sub selectMinu {
    my ($name, $value) = (@_);
    my @ary = ();
    my ($i,$out);
    for($i=0;$i<12;$i++){$ary[$i] = sprintf "%02d", $i*5;}
    $out = select_option($name, $value,@ary) ;
    return $out;
}
#==================================================================================================================
sub selectHour {
    my ($name, $value) = (@_);
    my $out="<select name=\"$name\" class=\"fmList\">";
    my ($tt, $jj, $ss, $tmp);
    if (not $::o{'hourformat'}) {
	for($tt = 0; $tt< 12; $tt++) {
	    if($value == $tt) { $out .= "<option value=\"$tt\" selected>$tt am"; }
	    else { $out .= "<option value=\"$tt\">$tt am";}
	}
	for($jj = 0; $jj< 12; $jj++) {
	    $tt = $jj + 12;
	    if($jj==0) {$ss = 12;} else { $ss = $jj;}
	    if($value == $tt) { $out .= "<option value=\"$tt\" selected>$ss pm"; }
	    else { $out .= "<option value=\"$tt\">$ss pm";}
	}
    } else {
	for($tt=0; $tt < 24; $tt++) {
	    if($value == $tt) { $tmp = sprintf "<option value=\"%d\" selected>%02.2d",$tt,$tt; $out .= $tmp;}
	    else {$tmp = sprintf "<option value=\"%d\">%02.2d",$tt,$tt; $out .= $tmp;}
	}
    }
    $out .= "</select>";
    return $out;
}
#==================================================================================================================
sub rebuildWorkingHourTable {
    my ($username) = (@_);
    my $calname="$::o{'spooldir'}/$username";
    my @table=(0,0,0,0,0,0,0,0,2500,2500,2500,2500,2500,2500,2500,2500);

    if( -d $calname && -f "$calname/info" ) {
	my ($i, $hname, $mname, $shr, $ehr, $hnameE, $mnameE, $mark, $sh, $sm, $eh, $em);
	$shr = $::calinfo{'hourB'};  $ehr = $::calinfo{'hourE'}; $mark = 0;
	for($i=0; $i<7; $i++) {
	    $sh = $shr; $eh = $ehr; $sm=$em = 0;
	    $hname = "hourB$i"; $mname = "minuB$i";
	    if(exists $::calinfo{$hname} and exists $::calinfo{$mname}) {
		$table[$i] = $::calinfo{$hname} * 100 + $::calinfo{$mname};
		$sh = $::calinfo{$hname}; $sm = $::calinfo{$mname};
	    }
	    $hnameE = "hourE$i"; $mnameE = "minuE$i";
	    if(exists $::calinfo{$hnameE} and exists $::calinfo{$mnameE}) {
		$table[8+$i] = $::calinfo{$hnameE} * 100 + $::calinfo{$mnameE};
		$eh = $::calinfo{$hnameE}; $em = $::calinfo{$mnameE};
	    }
	    if($sm != 0 or $em != 0 or $sh != $shr or $eh != $ehr) { $mark ++; }
	}
	$table[7] = $table[0]; $table[15] = $table[8]; $table[16] = $mark;
	my $fname = "$calname/WorkingHours";
	my $cts =  '@::WorkingHours=(' . join(',', @table) . ');';
	write_file($fname, $cts);
    }
    return @table;
}
#=====================================================================================================

sub dooption {
    my ($who, $username, $calname, $shr, $ehr, $tmp, $smp, $err, $day, $month, $year, $dependants, $msg, $thename,$thedname, $on, $ov);
    if($::calinfo{'action'} and $::calinfo{'action'} eq "$::phr{'Cancel'}") { &readData; &calendar; myexit(0);}
    $who = $::calinfo{'w'};
    if($::d{'authResult'} ne 4) {calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who).");}
    $err = $msg = "";
    
    $username=$::calinfo{'w'}; $thename=$thedname="";
    $calname="$::o{'spooldir'}/$username";
    if( -d $calname && -f "$calname/info" ) {
	$dependants="";
	my $fhl = gensym; 
	if (sysopen($fhl, "$calname/info", O_WRONLY | O_CREAT, 0644) ) {
            &webcalLock::doflock( \*$fhl, LOCK_EX, "$calname/info") or calerror("Cannot lock file '$calname/info': $!\n",1);
            truncate($fhl, 0);
	    $shr = $::calinfo{'hourB'};  $ehr = $::calinfo{'hourE'};
	    if($ehr==$shr) { $ehr++;}  if($ehr < $shr) { $tmp=$ehr; $ehr=$shr; $shr=$tmp};
	    print $fhl "\$::calinfo{\'hourB\'}=\'$shr\';\n";
	    print $fhl "\$::calinfo{\'hourE\'}=\'$ehr\';\n";
	    # record detailed daily schedule
	    {
		my ($i, $bname, $ename, $st, $ed);
		for($i = 0; $i<7; $i++) {
		    $bname = "hourB$i"; $ename = "hourE$i"; 
		    if(exists $::calinfo{$bname} and exists $::calinfo{$ename}) {
			$st = $::calinfo{$bname}; $ed = $::calinfo{$ename};
			if($ed < $st) { $tmp = $ed; $ed=$st; $st = $tmp;}
			print $fhl "\$::calinfo{\'$bname\'}=\'$st\';\n";
			print $fhl "\$::calinfo{\'$ename\'}=\'$ed\';\n";			
		    }
		}
		for($i = 0; $i<7; $i++) { # start/end minute
		    $bname = "minuB$i"; $ename = "minuE$i"; 
		    if(exists $::calinfo{$bname} and exists $::calinfo{$ename}) {
			$st = $::calinfo{$bname}; $ed = $::calinfo{$ename};
			print $fhl "\$::calinfo{\'$bname\'}=\'$st\';\n";
			print $fhl "\$::calinfo{\'$ename\'}=\'$ed\';\n";			
		    }
		}
	    }

	    #=========================================
	    $tmp = $::calinfo{'tzone'};
	    if($tmp and $tmp ne 'localtime') {
		print $fhl "\$::calinfo{\'tzone\'}=\'$tmp\';\n";
	    }
	    if($::calinfo{'toffset'}) {
		my ($v,$h,$m);
		$v = $::calinfo{'toffset'};
		if($v=~/:/ or abs($v)<3000){ ($h, $m) = split(/:/,$v,2);$m=0 if not $m; if(0+$h < 0){ $v= -(-$h*60+$m);}else {$v=$h*60+$m;} $v *= 60;}
		print $fhl "\$::calinfo{\'toffset\'}=\'$v\';\n";		
	    }
	    #=========================================
	    $tmp = $::calinfo{'ctype'};
	    if($tmp and $tmp =~ 'public' and ismember($who, $::o{'corporate_calendar'})) { 
		$msg .= "<br>Corporate calendar \"$who\" must be a private calendar";
		$tmp = 'private'; 
	    };
	    print $fhl "\$::calinfo{\'ctype\'}=\'$tmp\';\n";

	    # =============== 0/1 flags ======================
	    for $on ( 'resrc', 'aap', 'nap', 'cfilter', 'dmode', 'dctoc', 'tarf', 'eweekend', 'weekstart') 
	    {
		if($::calinfo{$on}) { print $fhl "\$::calinfo{\'$on\'} = \'1\';\n";}
		else { print $fhl "\$::calinfo{\'$on\'} = \'0\';\n";}
	    }

	    # ============== n/v pairs ======================
	    for $on ('w', 'dview', 'dayview', 'weekview', 'dlist', 'dformat', 'dformat2', 'tformat', 'estyle',
		     'privacy', 'aname', 'dei', 'interval', 'ulist') 
	    {
		$tmp = $::calinfo{$on};
		if($tmp) {  print $fhl "\$::calinfo{\'$on\'}=\'$tmp\';\n";}
	    }

	    # =========== inverted 0/1 flags ==================
	    for $on ( 'vcal', 'dr') 
	    {
		if($::calinfo{$on}) { print $fhl "\$::calinfo{\'$on\'} = \'0\';\n";}
		else { print $fhl "\$::calinfo{\'$on\'} = \'1\';\n";}
	    }

	    # =========== funky ops ==================
	    my %fops = (
		'pubnotes'   => 'pnotes',
		'pubaddr'    => 'paddress',
		'pubdiary'   => 'pdiary',
		'slanguage'  => 'language',
		'sol'        => 'ol',
		'tdelay'     => 'tooltipDelay',
	    );
	    
	    for $on (keys %fops) {
		$ov = $fops{$on};
		if(defined $::calinfo{$on}) { $tmp = $::calinfo{$on};}
		else { $tmp = $::calinfo{$ov};} $tmp = $tmp || 0;
		print $fhl "\$::calinfo{\'$ov\'}=\'$tmp\';\n";		
	    }

	    # ========= Rob Janssen's option ===============
            if($::o{'autostart'}) {
		if ($::calinfo{'autostart'}) { $tmp = 0; } else { $tmp = 1; }
		print $fhl "\$::calinfo{\'autostart\'}=\'$tmp\';\n";
	    }


	    $tmp = $::calinfo{'dcsf'}; 
	    if($tmp and $tmp !~ /\?+/) {
		$tmp =~ s/\\|\/|\'|\"|\`//g; #"
		print $fhl "\$::calinfo{\'dcsf\'}=\'$tmp\';\n";
	    }
	    

	    $thename = $::calinfo{'name'} || "";  $thename =~ s/\\//g; $thename =~ s/\'/\\\'/g;
	    if($thename) { print $fhl "\$::calinfo{\'name\'}=\'$thename\';\n";}
	    $tmp = $::calinfo{'homepage'}; $tmp =~ s/\\//g;  $tmp =~ s/\'/\\\'/g;
	    if($tmp) { print $fhl "\$::calinfo{\'homepage\'}=\'$tmp\';\n"; }
            $tmp = $::calinfo{'email'};  $tmp =~ s/\\|\"|\'|\`//g; #"
	    print $fhl "\$::calinfo{\'email\'}=\'$tmp\';\n";
            $thedname = $::calinfo{'dname'}; $thedname =~ s/\\|\"|\`//g;  $thedname =~ s/\'/\\\'/g; #"
	    print $fhl "\$::calinfo{\'dname\'}=\'$thedname\';\n";
	    

            if(defined $::calinfo{'editors'}) {
		$tmp = $::calinfo{'editors'};   $tmp =~ s/\\|\/|\'|\"|\`//g; #"
		print $fhl "\$::calinfo{\'editors\'}=\'$tmp\';\n";
	    }
            if(defined $::calinfo{'readers'}) {
		$tmp = $::calinfo{'readers'};  $tmp =~ s/\\|\/|\'|\"|\`//g; #"
		print $fhl "\$::calinfo{\'readers\'}=\'$tmp\';\n";
            }
            if(defined $::calinfo{'clist'}) {
		$tmp = $::calinfo{'clist'};   $tmp =~ s/\\|\/|\'|\"|\`//g;  #"
                if($tmp and ! ismember($who, $tmp)) { $tmp = $tmp . ":$who";}
		print $fhl "\$::calinfo{\'clist\'}=\'$tmp\';\n";
            }
	    
	    #=================================================================
	    if($::o{'dependency'}) {
		if(defined $::calinfo{'dcs'}) {
		    $tmp = $::calinfo{'dcs'}; $tmp =~ s/\\|\'|\"|\`//g; $tmp =~ s/\\|\/|\'|\"|\`//g; #"
		    my %ccals=();
		    map { $ccals{$_} = 1;} split(/[:;, ]/, $::o{'corporate_calendar'});
		    my (@list) = split(/[:,;\s]/, $tmp); 
		    my $s; $tmp="";
		    foreach $s (@list) {
			if(not $ccals{$s} and $s ne $who) {$tmp .= "$s:";}
			elsif ($s eq $who) { $msg .= "<br><b>$s</b> cannot dependend on itself";}
			else { $msg .= "<br><b>$s</b> is the corporate calendar, it cannot be a dependend calendar";}
		    }
		    $tmp=~ s/:$//g;
		    if($tmp) { print $fhl "\$::calinfo{\'dcs\'}=\'$tmp\';\n";}
		    $dependants=$tmp;
		}
	    }

	    #=================================================================

	    if($::calinfo{'hdr'}) {
		$tmp = $::calinfo{'hdr'}; $tmp =~ s/\\//g;  $tmp =~ s/\'/\\\'/g; $tmp =~ s/\n/ /g;
		print $fhl "\$::calinfo{\'hdr\'}=\'$tmp\';\n";
	    }
	    if($::calinfo{'ccode'}) {
		my $tmp = (0+$::calinfo{'ccode'});
		if($tmp>0){print $fhl "\$::calinfo{\'xcode\'}=\'$tmp\';\n";}
	    }
	    if($::calinfo{'dcode'}) {
		my $tmp = (0+$::calinfo{'dcode'});
		if($tmp){print $fhl "\$::calinfo{\'ycode\'}=\'$tmp\';\n";}
	    }
	    if($::calinfo{'ftr'}) {
		$tmp = $::calinfo{'ftr'};  $tmp =~ s/\\//g; $tmp =~ s/\'/\\\'/g; $tmp =~ s/\n/ /g;
		print $fhl "\$::calinfo{\'ftr\'}=\'$tmp\';\n";
	    }

	    if($::calinfo{'selecttabs'}) {
		my ($i, $tabs, $nam);
		$tabs = "";
		for($i=0; $i<10; $i++) {
		    $nam = "tab$i";
		    if($::calinfo{$nam}) { $tabs .= "$::calinfo{$nam},";}
		}
		if(! ismember('option', $tabs)) { $tabs .= 'option';}
		if(! ismember('get', $tabs)) { $tabs = 'get,' . $tabs;}
		print $fhl "\$::calinfo{\'tabs\'}=\'$tabs\';\n";
	    }
	    
	    #============ color settings =============================
	    map {
		$tmp = $::calinfo{$_}; 
		if($tmp) { $tmp =~ s/\s|\\|\'|\"|\`//g;  #"
			   print $fhl "\$::calinfo{\'$_\'}=\'$tmp\';\n";
		       }
	    } ('apair','tpair','mpair','spair');
	    if(exists $::calinfo{'themecolor'}) { 
		$tmp=$::calinfo{'themecolor'}; print $fhl "\$::calinfo{\'themecolor\'}=\'$tmp\';\n";
	    }
#	    map {
#		if(exists $::calinfo{$_}) { 
#		    $tmp = $::calinfo{$_}; $tmp =~ s/\s|\\|\'|\"|\`//g;  #"
#		    if($tmp =~ /^\#?[0-9abcdef]+$/) {print $fhl "\$::calinfo{\'$_\'}=\'$tmp\';\n"; }
#		    else { my $k=lc($tmp); $tmp=$::sixteenColors{$k}; if($tmp){ print $fhl "\$::calinfo{\'d$_\'}=\'$tmp\';\n";}}
#		}
#	    } ('bgcolor', 'tabcolor', 'tabcolorh', 'wkendclr', 'clr2');

	    {
		my $bgcolor=$::calinfo{'bgcolor'} || "";
		if(exists $::calinfo{'dbgcolor'}) { $bgcolor= $::calinfo{'dbgcolor'};}
		$tmp = $bgcolor; $tmp =~ s/\s|\\|\'|\"|\`//g;  #"
		if($tmp =~ /^\#?[0-9abcdef]+$/) {print $fhl "\$::calinfo{\'bgcolor\'}=\'$tmp\';\n"; }
		else { my $k=lc($tmp); $tmp=$::sixteenColors{$k}; if($tmp){ print $fhl "\$::calinfo{\'bgcolor\'}=\'$tmp\';\n";}}
	    }

	    if(exists($::calinfo{'tfg'})) {
		map {
		    $tmp = $::calinfo{$_}; $tmp =~ s/\s|\\|\'|\"|\`//g;  #"
		    if($tmp =~ /^\#?[0-9abcdef]+$/) { print $fhl "\$::calinfo{\'d$_\'}=\'$tmp\';\n";}
		    else { my $k=lc($tmp); $tmp=$::sixteenColors{$k}; if($tmp){ print $fhl "\$::calinfo{\'d$_\'}=\'$tmp\';\n";}}
		} ('afg', 'abg', 'tfg', 'tbg', 'mfg', 'mbg', 'sfg', 'sbg'); 
	    }


	    if($::calinfo{'setdefaultreminder'}) {
	      my ($stmp, $utmp, $vtmp);
	      $stmp = $::calinfo{'drflash'};
	      $utmp = $::calinfo{'drflashu'};
	      $vtmp = $::calinfo{'drflashv'}; $vtmp=~ s/,/;/g; $vtmp=~ s/[^\-\d;]//g; $vtmp=~ s/^;+|\D+$//g;
	      if($vtmp eq "") { $vtmp = "5";} if($vtmp=~/^\-/){print $fhl "\$::calinfo{'NFR'}=1;\n";}
	      $tmp="rf:" . "$stmp:$vtmp:$utmp,rm:"; 
	      $stmp = $::calinfo{'drmail'};
	      $utmp = $::calinfo{'drmailu'};
	      $vtmp = $::calinfo{'drmailv'}; $vtmp=~ s/,/;/g;  $vtmp=~ s/[^\-\d;]//g; $vtmp=~ s/^;+|\D+$//g;
	      if($vtmp eq "") { $vtmp = "5";} if($vtmp=~/^\-/){print $fhl "\$::calinfo{'NMR'}=1;\n";}
	      $tmp .= "$stmp:$vtmp:$utmp,rp:";
	      $stmp = $::calinfo{'drpopup'};
	      $utmp = $::calinfo{'drpopupu'};
	      $vtmp = $::calinfo{'drpopupv'}; $vtmp=~ s/,/;/g; $vtmp=~ s/[^\-\d;]//g; $vtmp=~ s/^;+|\D+$//g;
	      if($vtmp eq "") { $vtmp = "5";} if($vtmp=~/^\-/){print $fhl "\$::calinfo{'NPR'}=1;\n";}
	      $tmp .= "$stmp:$vtmp:$utmp,rc:";
	      $stmp = $::calinfo{'drchime'};
	      $utmp = $::calinfo{'drchimeu'};
	      $vtmp = $::calinfo{'drchimev'}; $vtmp=~ s/,/;/g; $vtmp=~ s/[^\-\d;]//g; $vtmp=~ s/^;+|\D+$//g;
	      if($vtmp eq "") { $vtmp = "5";} if($vtmp=~/^\-/){print $fhl "\$::calinfo{'NCR'}=1;\n";}
	      $tmp .= "$stmp:$vtmp:$utmp";
	      print $fhl "\$::calinfo{\'drem\'}=\'$tmp\';\n";
          }
	    
	    #===== default font styles
	    {
		my ($i, $k, $css);
		for $i (1..4) { 
		    $k="css$i";  $css = $::calinfo{$k};
		    if($css and $css !~ /^\?/) { print $fhl "\$::calinfo{\'$k\'}=\'$css\';\n";}
		}
	    }
	    #===== default font styles

	    my $authors="";
	    if($::o{'authorize_author'}) {
		$authors = $::calinfo{'authors'} || ""; $authors =~ s/\\|\/|\'|\"|\`//g; #"
		$authors =~ s/[:,;\s]+/:/g; $authors =~ s/^:|:$//g;
		if($authors) {print $fhl "\$::calinfo{\'authors\'}=\':$authors:\';\n";}
	    }
	    
	    print $fhl "\n1;\n";
            &webcalLock::doflock( \*$fhl, LOCK_UN, "$calname/info") or calerror("Cannot unlock file '$calname/info': $!\n",1);
	    close $fhl;

	    #=============================================
	    if($::o{'corporate_calendar'} and exists $::calinfo{'ignore_ccal'}) {
		my $file = "$calname/no_ccal";
		if($::calinfo{'ignore_ccal'}) {
		    if( ! -f $file) {my $fhn = gensym; if(open($fhn, ">$file")) { print $fhn "1\n"; close $fhn;}}
		} else {
		    if( -f $file) {unlink $file;}
		}
	    }
	    #=============================================
	    
	    &rebuildWorkingHourTable($username);
	    if($::o{'dependency'}) { &rebuildDependencyTable($username, $dependants); }   
	    if($::o{'authorize_author'}) { &rebuildAuthorTable($username, $authors);}
	    if($::calinfo{'octype'} and $::calinfo{'ctype'} ne $::calinfo{'octype'}) { 
		rebuildModeratedCalendarTable($who, $::calinfo{'ctype'});
	    }
            # invalidate cache. Weekstart may have changed
            if($::calinfo{'expirecache'}) {
                my $cachedir = "$calname/cache";
		my $DIR4= gensym;
		if( opendir($DIR4, $cachedir )) {
		    my @filenames = readdir($DIR4);
		    closedir($DIR4);
		    my $cname;
		    for $cname (@filenames) {
                        $cname = untaintname($cname, "");
			next if "$cname" =~ /^\./;
			if($cname =~ m/^w.+/) { unlink("$cachedir/$cname");}
		    }
		}
            }
        } else {$err = "$::phr{'OpenFailed'}";}
      } else { $err = "$::phr{'NoCalendar'}";}
    {
	my ($view, $ls, $who, $month, $dat,$year, $cmd);
	$who=$::calinfo{'w'};
	$view=$::calinfo{'v'};
        $ls = $::calinfo{'ls'};
	$month= $::calinfo{'month'};
	$day  = $::calinfo{'day'};
	$year = $::calinfo{'year'};
	if($::calinfo{'ret_p'}) {  $cmd = $::calinfo{'ret_p'};} else {$cmd='get';}
	if($::calinfo{'opcode'}) { $cmd .= "&opcode=$::calinfo{'opcode'}";}
	if($::calinfo{'hx'}) { $cmd .= "&hx=4";}
        &headers($::phr{'Acknowledgement'},undef,"1; URL=$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=$view&d=$month/$day/$year$::vmg");
	print "<center><br>";
	print "<br><font color=#ff0000>$::phr{'Options'} $::phr{'Set'}</font><p>$msg</p><p>";
	print "<table bgcolor=$webcalConfig::r{'dkbackground'} border=2 cellpadding=2><tr><td><a href=\"$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=$view&d=$month/$day/$year$::vmg\">$::phr{'BackToCalendar'}</a></tr></table>";
	print "</center>";
	&trailer(0,0);
	&update_name_list($username, $thename, $thedname,'u');
    }
}

#========================================================================================
sub rebuildModeratedCalendarTable {
    my ($who, $ctype) = (@_);
    my ($file, $k, $v, $exist);
    $file = "$::o{'spooldir'}/.moderated";
    if( -f "$file") { $exist = 1;} else {$exist=0;}
    my $fhdp = gensym;
    if(sysopen($fhdp, "$file", O_WRONLY | O_CREAT, 0644 ) ) {
	&webcalLock::doflock(\*$fhdp, LOCK_EX, $file) or calerror("Cannot lock file '$file': $!\n",1);     
	%::moderated=(); if($exist) { do "$file";}
	for $k (keys %::moderated) { if(! -d "$::o{'spooldir'}/$k") { delete $::moderated{$k};}} 
	if($ctype eq "public_m") { $::moderated{$who} =1;} else { delete $::moderated{$who}; }
	truncate($fhdp, 0);
	print $fhdp "\%::moderated=(\n";	    
	foreach $k (keys %::moderated) { print $fhdp "\'$k\'=>1,\n";}
	print $fhdp ");\n1;\n";	    	    
	&webcalLock::doflock( \*$fhdp, LOCK_UN,"$file") or calerror("Cannot unlock file '$file': $!\n",1);
	close $fhdp;	    
    }
} 
#========================================================================================   
sub rebuildDependencyTable {
    my ($username, $dependants) = (@_);
    my ($file, $k, $v, $exist);
    $file = "$::o{'spooldir'}/.dependency";
    if( -f "$file") { $exist = 1;} else {$exist=0;}
    my $fhdp = gensym;
    if(sysopen($fhdp, "$file", O_WRONLY | O_CREAT, 0644 ) ) {
	&webcalLock::doflock(\*$fhdp, LOCK_EX, $file) or calerror("Cannot lock file '$file': $!\n",1);     
	%::dependency=(); if($exist) { do "$file";}
	if(! $dependants) { delete $::dependency{$username} ;}
	else { $::dependency{$username} = $dependants;}
	for $k (keys %::dependency) {
	    if(! -d "$::o{'spooldir'}/$k") { delete $::dependency{$k};}
	    else {
		my @all = split(/:/, $::dependency{$k}); my ($tmp, $f); $tmp="";
		for $f (@all) { if( -d "$::o{'spooldir'}/$f") {if(!$tmp) {$tmp = "$f";} else {$tmp .= ":$f";}}}
		if($tmp) { $::dependency{$k} = $tmp;} else { delete $::dependency{$k} ;}
	    }
	} 
	truncate($fhdp, 0);
	print $fhdp "\%::dependency=(\n";	    
	foreach $k (keys %::dependency) { print $fhdp "\'$k\'=>\'", $::dependency{$k}, "\',\n";}
	print $fhdp ");\n1;\n";	    	    
	&webcalLock::doflock( \*$fhdp, LOCK_UN,"$file") or calerror("Cannot unlock file '$file': $!\n",1);
	close $fhdp;	    
    }
}
sub rebuildAuthorTable {
    my ($username, $authors) = (@_);
    my ($file, $k, $v, $exist);
    $file = "$::o{'spooldir'}/.authors";
    if( -f "$file") { $exist = 1;} else {$exist=0;}
    my $fhdp = gensym;
    if(sysopen($fhdp, "$file", O_WRONLY | O_CREAT, 0644 ) ) {
	&webcalLock::doflock(\*$fhdp, LOCK_EX, $file) or calerror("Cannot lock file '$file': $!\n",1);     
	%::authors=(); if($exist) { do "$file";}
	if(!$authors) { delete $::authors{$username} ;}	else { $::authors{$username} = ":$authors:"; }
	for $k (keys %::authors) {
	    if(! -d "$::o{'spooldir'}/$k") { delete $::authors{$k};}
	    else {
		my @all = split(/:/, $::authors{$k}); my ($tmp, $f); $tmp="";
		for $f (@all) { if( -d "$::o{'spooldir'}/$f") {if(!$tmp) {$tmp = "$f";} else {$tmp .= ":$f";}}}
		if($tmp) { $::authors{$k} = $tmp;} else { delete $::authors{$k} ;}
	    }
	} 
	truncate($fhdp, 0);
	print $fhdp "\%::authors=(\n";	    
	foreach $k (keys %::authors) { print $fhdp "\'$k\'=>\'", $::authors{$k}, "\',\n";}
	print $fhdp ");\n1;\n";	    	    
	&webcalLock::doflock( \*$fhdp, LOCK_UN,"$file") or calerror("Cannot unlock file '$file': $!\n",1);
	close $fhdp;	    
    }
}
#========================================================================================

sub admin {
    my ($opcode, $adnames, $isadm, $isvgadm) = (@_);
    my ($jj, $who, $view, $name, $homepage, $shr, $ehr, $itv, $tt, @timezonelist, $ampm, $disabled, $ls, $bmore);
    $who=$::calinfo{'w'};
    $view=$::calinfo{'v'};
    $ls = $::calinfo{'ls'};

    my $common_fields= <<END;
<input type=hidden name=w value="$who">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name="ret_p" value="admin">
<input type=hidden name="opcode" value="$opcode">
<input type=hidden name="c" value="doadmin">
END
;

    if($opcode == 120) { # $adnames{'120_changePassword'} = $::phr{'Change_Password'};
	my $opname = $::phr{'Change_Password'};
	print <<END;
<Form action="$::o{'cginame'}" name=cpasswd method=POST>$::vmp
$common_fields
<input type=hidden name=ac value="acpasswd">
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>

<table cellpadding=2 cellspacing=2  width="85%" class="admin">
   <tr><td align=right><span class="fmLabel">$::phr{'Old_Password'}:</span> </td>
       <td align=left><input type="password" size=20 maxlength=20 name=opasswd value="" class="fmEntryP"></td>
   </tr>
   <tr><td align=right><span class="fmLabel">$::phr{'New_Password'}:</span> </td>
       <td align=left><input type="password" size=20 maxlength=20 name=npasswda value="" class="fmEntryP"></td>
   </tr>
   <tr><td align=right><span class="fmLabel">$::phr{'New_Password_Again'}:</span> </td>
	<td align=left><input type="password" size=20 maxlength=20 name=npasswdb value="" class="fmEntryP"></td>
 </tr>
</table>

END
;
    }

    if($opcode == 127) { #  $adnames{'127_resetPassword'} = $::phr{'ResetPasswd'};
        my $aaai="";
        my $aainfo=&webcalAuth::additionalAdminAuthInfo();
        if($aainfo and ref($aainfo) eq 'HASH') {
            my ($k, $v, $l, $t, $href); $href = $aainfo;
            for $k (sort keys %{$href}) {
                $l = $k; $l =~ s/_/ /g;
                if($l =~ /password/i) { $t = 'password';} else { $t='text';}
                $v = $href->{$k};
                $aaai .= <<EOL;
<tr><td align=right><span class="fmLabel"><font color=red>$l:</font> </span></td>
<td align=left><input type="$t" name="$k" size=40 maxlength=120 value="$v" class="fmEntryP"></td>
</tr>
EOL
    ;
            }
        }
	my $opname = $::phr{'ResetPasswd'};

        print <<END;
<Form action="$::o{'cginame'}" name=rpasswd method=POST>$::vmp
$common_fields
<input type=hidden name=ac value="rspasswd">
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>

<table cellpadding=2 cellspacing=2 width="85%" class="admin">
   <tr><td align=right><span class="fmLabel">$::phr{'CalendarName'}: </span></td>
       <td align=left><input type="text" size=20 maxlength=20 name=pcname value="$who" class="fmEntry"></td>
   </tr>
   <tr><td align=right><span class="fmLabel">$::phr{'New_Password'}: </span></td>
       <td align=left><input type="password" size=20 maxlength=20 name=npasswda value="" class="fmEntryP"></td>
   </tr>
   <tr><td align=right><span class="fmLabel">$::phr{'New_Password_Again'}: </span></td>
	<td align=left><input type="password" size=20 maxlength=20 name=npasswdb value="" class="fmEntryP"></td>
   </tr>
   $aaai
</table>
END
;
    }

    if($opcode == 122) { # $adnames{'122_meetingGP'}  = $::phr{'Create_Meeting_Group'};
	my $opname = $::phr{'Create_Meeting_Group'};
        print <<END;
<Form action="$::o{'cginame'}" name=mgpeditor method=POST>$::vmp
$common_fields
<input type=hidden name=ac value="acmtgrp">
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>

<table cellpadding=2 cellspacing=2 width="85%" class="admin"><tr>
END
;
	{
	    my (@gkeys, @fgkeys, $n);
	    if($isadm or $isvgadm) {@gkeys = get_private_mgroups($who);}
	    else {@gkeys = get_mgroups($who);}
	    if(scalar @gkeys) {
		@fgkeys=(); for $n (@gkeys) { $n=~ s/\(\)//g; push @fgkeys, $n;}
		print "<td align=right><span class=\"fmLabel\">$::phr{'Existing_Groups'}: </span></td><td>",
		select_option("null",undef,@fgkeys);
	    } else {
		print "<td></td><td>";
	    }
	}
	print "</td></tr>";
	my $amore = ""; 
	{
	    if( ($::d{'authResult'} | $::d{'ispublic'}) == 4 and $::o{'tabs'} =~ /ad,|,ad$/) {
		$amore="<br><a href=\"javascript:openpopup(\'$::o{'cginame'}?c=gEaddr&fmname=mgpeditor&eltname=mpts\','ew',800,500)\"><font color=blue size=1><span class=\"fmLabelS\">$::phr{'AddressBook'}&nbsp;&nbsp;</span></font></a>";
		$bmore="<br><a href=\"javascript:openpopup(\'$::o{'cginame'}?c=gEaddr&fmname=gmgpeditor&eltname=gmpts\','ew',800,500)\"><font color=blue size=1><span class=\"fmLabelS\">$::phr{'AddressBook'}&nbsp;&nbsp;</span></font></a>";
	    }
	}
	print "
   <tr><td align=right><input type=Button  class=\"fmBtn\" onclick=\"openpopup('$::o{'cginame'}?c=showmgps&w=$who','Mps',500,200)\" value=\"$::phr{'Group_Name'}:\"></td>
   <td align=left><input type=text size=20 maxlength=20 name=mgpname value=\"\" class=\"fmEntry\">
<a href=\"javascript:openpopup(\'$::o{'cgimisc'}?cmd=oah&f=a122_mtgp.html\','ohelp',640,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a> 
</td></tr>
    <tr><td></td><td colspan=3><font size=-1 color=\"#cc00cc\"><span class=\"fmLabelS\">$::phr{'ListGroupMembers'}</span></font></td>
    </tr>";
	
	$::calinfo{'_clist_'} = 1;
	my ($textfield,$selectfield) = select_multicals("mpts","", 60);
	delete $::calinfo{'_clist_'};
	print "<tr><td align=right valign=top>
<a href=\"javascript:openpopup(\'$::o{'cginame'}?c=listcal&w=$who\',\'calendars\',500,400)\"><span class=\"fmLabel\">$::phr{'Participants'}:</span></a>$amore</td><td colspan=2>$textfield</td></tr>";
	if ($::o{'listAllCals'}) {
	    print "<tr><td><br></td><td colspan=2>",
	    "<table border=0 cellspacing=0 cellpadding=0><tr><td valign=top>",
	    $selectfield, "&nbsp;&nbsp;</td><td>",
	    "<blockquote class=\"fmMsg\">", $::phr{'MkGroupInstruction'}, "</blockquote>",	
	    "</td></tr></table>",
	    "</td></tr>\n";
	}
	print "</table>";
    }
    
    if($opcode == 123) {  # $adnames{'123_GmeetingGP'}  = $::phr{'Create_Global_Meeting_Group'};
	my $opname = $::phr{'Create_Global_Meeting_Group'};
        print <<END;
<Form action="$::o{'cginame'}" name=gmgpeditor method=POST>$::vmp
$common_fields
<input type=hidden name=ac value="acgmtgrp">
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>

<table cellpadding=2 cellspacing=2 width="85%" class="admin"><tr>
END
;
	{
	    my (@gkeys, @fgkeys, $n);	    
	    @gkeys = get_global_mgroups();
	    if(scalar @gkeys) {
		@fgkeys=(); for $n (@gkeys) { $n=~ s/\(\)//g; push @fgkeys, $n;}
		print "<td align=right><span class=\"fmLabel\">$::phr{'Existing_Groups'}: </span></td><td>",
		select_option("null",undef,@fgkeys);
	    } else {
		print "<td></td><td>";
	    }
	}
	print "</td></tr>";
	print "
   <tr><td align=right><input type=Button class=\"fmBtn\" onclick=\"openpopup('$::o{'cginame'}?c=showgmgps&w=$who','Mps',500,200)\" value=\"$::phr{'Group_Name'}\">:</td>
   <td align=left><input type=text size=20 maxlength=20 name=gmgpname value=\"\" class=\"fmEntry\"></td>
    <tr><td></td><td colspan=3><font size=-1 color=#cc00cc><span class=\"fmLabel\">$::phr{'ListGroupMembers'}</span></font></td>
    </tr>";
	my ($textfield,$selectfield) = select_multicals("gmpts","",60);
    print "<tr><td align=right><a href=\"javascript:openpopup(\'$::o{'cginame'}?c=listcal&w=$who\',\'calendars\',500,400)\">$::phr{'Participants'}:</a></td><td align=left colspan=2>$textfield</td>
    </tr>";
	if ($::o{'listAllCals'}) {  print "<tr><td></td><td align=left colspan=2>",$selectfield,   "</td></tr>\n"; }
	print "</table>";
    }

    if($opcode == 126) { # '126_download' => $::phr{'downloadCalendar'},
	my @alldata = listalldata($who);
	my $allcals = select_option("database", "data", @alldata);
	my $opname = $::phr{'downloadCalendar'};
        print <<END;
<Form action="$::o{'cginame'}" name=download method=POST>$::vmp
$common_fields
<input type=hidden name=ac value="download">
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>
<br>
<br>

<table cellpadding=2 cellspacing=2 width="85%" class="admin">
END
;
	print "<tr><td align=right><span class=\"fmLabel\">$::phr{'CalendarFormat'}: </span></td><td>",
	input_radio("cft","vcal",("ht","Hash Table","vcal","vCalendar")),
	"</td></tr>
<tr><td align=right><span class=\"fmLabel\">$::phr{'CalendarFile'}:</span></td><td>&nbsp;$allcals</td></tr>
</table>";
    }

    if($opcode == 128) { # '128_danger'  =>  $::phr{'DangerousOperations'},
	my $epoch = to_native_date("12/31/1990");
	my $opname = $::phr{'DangerousOperations'};
	my $other = "";
        print <<END;
<Form action="$::o{'cginame'}" name=dangerop method=POST onSubmit="return confirm('Are you sure?')">
$::vmp
$common_fields
<input type=hidden name=ac value="acdanger">
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>

<table cellpadding=2 cellspacing=2 width="85%" class="admin" align=center>
END
;
	print <<END;
<tr><td align=right><input type=checkbox name=clearCache value="clearCache" class="fmRadio"></td>
 <td><span class="fmLabel">$::phr{'ClearCache'}</span></td>
</tr>
<tr><td align=right><input type=checkbox name=deleteEventsBefore value="DeleteEventsBefore" class="fmRadio"></td>
<td colspan=2><span class="fmLabel">$::phr{'deleteEventsBefore'}</span>
 <input type=text size=12 name="DeleteEventsBeforeDate" value="$epoch" class="fmEntry"></td></tr>
    <tr><td align=right><input type=checkbox name=eraseCalendar value="EraseCalendar" class="fmRadio"></td>
<td><span class="fmLabel">$::phr{'EraseCalendar'}</span></td></tr>
    <tr><td align=right><input type=checkbox class="fmRadio" name=deleteCalendar value="DeleteCalendar"></td>
<td><span class="fmLabel">$::phr{'DeleteCalendar'}</span></td> </tr>
</table>
END
;
    }

    if($opcode == 124) { # $adnames{'124_mergeCal'} = $::phr{'Merge_Calendars'};
	my $opname = $::phr{'Merge_Calendars'};
        print <<END;
<Form action="$::o{'cginame'}" name=mergecal method=POST onSubmit="return confirm('Are you sure?')">
$::vmp
$common_fields
<input type=hidden name=ac value="acmerge">
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>
<br>
<br>
<table cellpadding=0 cellspacing=0 width="85%" class="admin">
END
;
	print <<END;
  <tr><td></td><td colspan=2><font size=-1><span class="fmLabelS">$::phr{'EnterCalNames'}.</span></font></td></tr>
  <tr><td align=right><span class="fmLabel">$::phr{'CalendarNames'}: </span></td>
  <td><input type=text size=40 maxlength=256 name=mergecal value="" class="fmEntry"></td></tr>
  </table>	
END
;
    }

    if($opcode == 129) { # $adnames{'129_delete'}  =  $::phr{'DeleteCalendars'};
	my $opname = $::phr{'DeleteCalendars'};
        print <<END;
<Form action="$::o{'cginame'}" name=adeletecal method=POST onSubmit="return confirm('Are you sure?')">
$::vmp
$common_fields
<input type=hidden name=ac value="acmerge">
<input type=hidden name=ac value="acdanger">
<input type=hidden name="admindelete" value="AdminDelete">
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>

<table cellpadding=0 cellspacing=0 width="85%" class="admin">
END
;
	print <<END;
   <tr>
   <tr><td align=center><a href="javascript:openpopup('$::o{'cginame'}?c=delcal',\'calendars\',500,400)"><img src="$::o{'imgdirurl'}/yopen.gif" width=25 height=16 border=0 align=bottom></a>
<b><span class="fmLabel">Delete Calendar: </span></b><input type=text name=calendar2bedeleted size=30 maxlength=256 value="" class="fmEntry"></td></tr>
</table>
END
;

    }

    if($opcode == 121) { # $adnames{'121_deleteCache'}  =  $::phr{'DeleteCache'};
	my $opname = $::phr{'DeleteCache'};
        print <<END;
<Form action="$::o{'cginame'}" name=adeletecache method=POST>
$::vmp
$common_fields
<input type=hidden name="adminClearCache" value="AdminClearCache">
<input type=hidden name=ac value="acdanger">
<input type=hidden name="admindelete" value="AdminDelete">
<table name=opdivider border=0 cellspacing=0 cellpadding=0>
<tr><td class="optitle" align=right width=600>$opname</td></tr>
<tr><td><img src="$::o{'imgdirurl'}/hline.gif" width=600 height=1 border=0 alt=""></td></tr></table><br>

<table cellpadding=0 cellspacing=0 width="85%" class="admin">
END
;
	print <<END;
<tr><td><blockquote>
<br>
<blockquote>
This operation delete all temp cache files on your calendar server. Temp cache files are normally
self maintained for active calendars. Occationally when your server clock is off too much into the future, 
the cached files may cause problems. The symptom is that new events added to the calendar fails to
show up on your calendar. The reason is that a cached file was created in the future (due to the
skewed clock on the server) is used.
</blockquote>
</blockquote>
</td></tr>
</table>
END
;

    }

    print <<END;
<br>
<table border=0 width="85%" class="option"><tr><td align=center class="option">
 <tr><td align=center ><br>
 <input type=submit name=action class="fmBtnSt" value="$::phr{'Submit'}">&nbsp;&nbsp;
 <input type=submit name=action class="fmBtnSt" value="$::phr{'Cancel'}"></td></tr>
</table>
</center></Form>

END
}

sub listalldata {
    my $who = (@_)[0];
    my @cals = ();
    my $name;
    my $DIR5= gensym;
    if (opendir($DIR5, "$::o{'spooldir'}/$who" )) {
        while ($name = readdir($DIR5)) {
            if($name =~ m/^data/) { push(@cals,$name);}
        }
        closedir($DIR5);
    }
    $ = time;
    my $mtime = -M "$::o{'spooldir'}/$who/data";
    my $DIR6= gensym;
    if (opendir($DIR6, "$::o{'spooldir'}/$who/cache" )) {
        while ($name = readdir($DIR6)) {
            if($name =~ m/^[m|d|w]/) {
		my $tt = -M "$::o{'spooldir'}/$who/cache/$name";
		if($tt <= $mtime) {
		    push(@cals,"cache/$name");
		}
	    }
        }
        closedir($DIR6);
    }
    return sort @cals;
}
#==================================================================================================
sub showMGroups {
  my ($who);
  $who = $::calinfo{'w'};
  &headers(undef,"");
  print "<center><h1>$::phr{'Existing_Groups'}</h1><br>\n";
  print "<table border=0 cellpadding=2 cellspacing=2>\n<tr>";
  my ( $i, @gkeys, $tkey, $value);
  @gkeys = get_mgroups($who);
  if(scalar @gkeys) {
    for $tkey (@gkeys) {
      if ($tkey =~ m/\($::phr{'global'}\)/) {
        my $aa=$tkey;  
        $aa =~ s/\($::phr{'global'}\)//g;        
        $value = $::GlobalMeetingGroups{"mgp_".$aa};
      } else {
          $value = $::meetingGroups{"mgp_".$tkey};
      }
      $tkey =~ s/\(\)//i;
      print "<td><a href=\"JavaScript:setgp('$tkey','$value')\"><b><span class=\"fmLabel\">$tkey</span></b></a>&nbsp;&nbsp;&nbsp;</td>";
      $i++; if($i == 8) { $i = 0; print "</tr>\n<tr>";}
    }
  }
  print "</tr><tr><td><br></td></tr></table>";
  print "<table><tr><td><form><input type=button  class=\"fmBtn\" onClick=\"window.opener.awin=''; window.close();\" value=\"$::phr{'Close'}\"></form></td></tr></table>\n";
  print "</center>";
  &trailer(0,0);
}
#===================================================================================================
sub showGMGroups {
  my ($who);
  $who = $::calinfo{'w'};
  &headers(undef,"");
  print "<center><h1>$::phr{'Existing_Groups'}</h1><br>\n";
  print "<table border=0 cellpadding=2 cellspacing=2>\n<tr>";
  my ( $i, @gkeys, $tkey, $value);
  @gkeys = get_global_mgroups();
  if(scalar @gkeys) {
    for $tkey (@gkeys) {
      $value = $::GlobalMeetingGroups{"mgp_".$tkey};
      $tkey =~ s/\(\)//g;
      print "<td><a href=\"JavaScript:setggp('$tkey','$value')\"><b><span class=\"fmLabel\">$tkey</span></b></a>&nbsp;&nbsp;&nbsp;</td>";
      $i++; if($i == 8) { $i = 0; print "</tr>\n<tr>";}
    }
  }
  print "</tr><tr><td><br></td></tr></table>";
  print "<table><tr><td><form><input type=button  class=\"fmBtn\" onClick=\"window.opener.awin=''; window.close();\" value=\"$::phr{'Close'}\"></form></td></tr></table>\n";
  print "</center>";
  &trailer(0,0);
}
#===================================================================================================
sub deltree { # remove a directory recursively. Does not handle special files.
    my ($dir) = (@_);
    my $ans=0;
    if( -d "$dir") {
	my $DIR7= gensym;
	if(opendir($DIR7, "$dir")) {
	    my @allfiles = readdir($DIR7); closedir($DIR7);
	    my ($f, $g);
	    foreach $f (@allfiles) {
		next if $f eq "." or $f eq "..";
		$g = "$dir/$f";
		if( -l "$g" ) { $ans += unlink "$g";}
		elsif( -f "$g" ) { $ans += unlink "$g";}
		elsif( -d "$g") {  $ans += deltree($g); }
	    }
	    rmdir $dir;
	}
    }
    return $ans;
} 
#===================================================================================================
sub doadmin {
    my ( $who, $err, $msg, $i, $view, $day, $month, $year, $acmd, $ls);
    if(defined $::calinfo{'action'} and $::calinfo{'action'} eq "$::phr{'Cancel'}") { &readData; &calendar; myexit(0);}
    $who=$::calinfo{'w'};
    if($::d{'authResult'} ne 4) { calerror(" $::phr{'errorPerm'}");  }
    $acmd=(@_)[0];
    $msg="";
    $err="";
    my $isadm = isadmin($::d{'remote_user'}); my $isvgadm= $isadm || isvgadmin($::d{'remote_user'},$who);

    if($acmd eq 'acdanger') {	# erase or delete
      my @doesnotexist=(); my $gvmsg="";
      my @reallydeleted=();
      my @cals_2_be_deleted =();
      my $deleteCalendar = 0;
      if(defined $::calinfo{'adminClearCache'}  and $::calinfo{'adminClearCache'} eq 'AdminClearCache') {
          my $cnt = &delete_all_cache_files();
          &headers($::phr{'Acknowledgement'},undef,undef,1);
          print "<center><br><br>";
          print "A total of $cnt cache files have been deleted.";
          print "<br><br><a href=\"javascript:history.go(-1)\"><b>$::phr{'GoBack'}</b></a>";
          print "</center>";
          &trailer(0,0);
          myexit(0);          
      }
      if(defined $::calinfo{'admindelete'}  and $::calinfo{'admindelete'} eq 'AdminDelete') {
          if($isadm or $isvgadm) {
              my $tmp = $::calinfo{'calendar2bedeleted'};
              $tmp =~ s/^\s+|\s+$//g; $tmp =~ s/\s*[;,:]\s*/,/g; 
	      my @tmps=split(/,/, $tmp); @cals_2_be_deleted=();
	      if(!$isadm) {
		  for $tmp (@tmps) {
		      if(isvgadmin($::d{'remote_user'}, $tmp)) {push @cals_2_be_deleted, $tmp;}
		      else {$ gvmsg .= "$tmp, ";}
		  }
	      } else { @cals_2_be_deleted = @tmps;}
              $deleteCalendar = 10;
          } else { 
              $msg = "Only calendar administrator is allowed to do this operation ($::phr{'errorPerm'}).<br>\n";
              calerror( $msg);
              myexit(0);
          }
      } elsif(defined $::calinfo{'deleteCalendar'}  and $::calinfo{'deleteCalendar'} eq 'DeleteCalendar') {
          my $file= "$::o{'spooldir'}/$who/do_not_delete_me";
          if( ! -f "$file") {  @cals_2_be_deleted = ($who); } else { @cals_2_be_deleted=('o_o:-protected-:o_o');}
          $deleteCalendar = 1;
      }
      if($deleteCalendar) {
          my ($count, $cal, $names); $count=0; $names = "";
          foreach  $cal (@cals_2_be_deleted) {
              my (@args, $calname, @table, $pfile, $nam, $pwdd, $tmp, $err0, $vgps);
              $err0 = ""; $vgps="";
              $cal = untaintname($cal);
              $calname = "$::o{'spooldir'}/$cal";
              if( -d $calname ) {
                  push @reallydeleted, $cal; $vgps=getcalvgroup($cal);
                  if( $ =~ m/MSWin|NT/i ) {	  deltree($calname);  }
                  else {
                      @args = ('/bin/rm', '-r', $calname);
                      system(@args) == 0  or $err0 = "$::phr{'OpenFailed'} ($calname)<br>";
                  }
              } else { push @doesnotexist, $cal;}
              if($err0) { $err .= $err0; }
              else {
		  my ($astatus, $amessage) = &webcalAuth::DeletePasswordEntry($cal);
		  &update_name_list($cal, "", "", 'd');
		  if($vgps) {removefromvgroups($cal,$vgps);}
		  if(! $astatus) { calerror("$amessage",1); myexit(0); }
              }
          }
          &headers($::phr{'Acknowledgement'},undef,undef,1);
          print "<center><br><br>";
          if($deleteCalendar > 1) {
              if( 0+@reallydeleted > 0) {
                  print "<font size=+1><b>The following calendar has been deleted</b></br></br></font>";
                  print "<font color=red><b>", join(", ", @reallydeleted), "</b></font><br><br>";
              }
              if( 0+@doesnotexist > 0) {
                  print "<font size=+1><b>Cannot find the following calendars</b></br></br></font>";
                  print "<font color=red><b>", join(", ", @doesnotexist), "</b></font><br><br>";
              }
	      print "<br><a href=\"javascript:history.go(-1)\"><b>$::phr{'GoBack'}</b></a>";
          } else {
              if( 0+@doesnotexist > 0) { 
                  print "<font color=red><b>", join(", ", @doesnotexist), "</b></font><br><br>";
                  print "<br><a href=\"javascript:history.go(-1)\"><b>$::phr{'GoBack'}</b></a>";
                  print "</center>";
              } else {
                  print "<font size=+1><b>$::phr{'calDeleted'}!<br>$::phr{'ThankYou4Using'} $webcalConfig::r{'cgiInfo'} !</b></font>";
              }
          }
	  if($gvmsg) { print "<br><br>You don't have permission to delete calendar <b>$gvmsg</b>";}
          print "</center>";
          &trailer(0,0);
          myexit(0);
      }
      if(defined $::calinfo{'clearCache'} and $::calinfo{'clearCache'} eq 'clearCache') {
          my $cnt = &delete_cache_1($who); 
          $msg = "$cnt cache files has been deleted<br>";
      }
      if(defined $::calinfo{'eraseCalendar'} and $::calinfo{'eraseCalendar'} eq 'EraseCalendar') {
	my ( $calname);
	$calname = "$::o{'spooldir'}/$who";
        my $fileK= "$::o{'spooldir'}/$who/do_not_erase_me";
        if( -f $fileK) { calerror("$::phr{'eraseFailed'}");}
	if(write_file("$calname/data", "\@::caldata = (\n\n);\n1;\n")) {
	    $msg .= "$::phr{'calErased'}! <br>\n";
        } else { calerror("$::phr{'eraseFailed'}!",1);}
     } elsif( defined $::calinfo{'deleteEventsBefore'} and $::calinfo{'deleteEventsBefore'} eq 'DeleteEventsBefore') {
          my $pdate=$::calinfo{'DeleteEventsBeforeDate'};
          my ($month, $day, $year, $rest)= split(/\//, $pdate); 
          my $calname = "$::o{'spooldir'}/$who";
          my $changed = 0;
          my ($href, $enddate, $emonth, $eday, $eyear);
          if( ! $month or !$day or !$year) { calerror("Bad date <b><font color=#0000ff>$pdate</font><b>",1); }
          $month--; my ($zmonth, $zday, $zyear ) = canDate( $month, $day , $year ); # month: 0-11
          $month++; $zmonth++;
          if( $zmonth != $month or $zday != $day or $zyear != $year) {
              calerror("$::phr{'invalid_date'} $zmonth/$zday/$zyear != $month/$day/$year",1);
          }
          my $fileK= "$::o{'spooldir'}/$who/do_not_erase_me";
          if( -f $fileK) { calerror("$::phr{'eraseFailed'}");}
          
          if ( -d "$calname" and  -r "$calname/data") {
              my $eventCounter= doReadFile("$calname/data");
              for $href (@::caldata) {  
                  $enddate="";
                  if(defined $href->{'end'} ) { $enddate =  $href->{'end'};}
                  else { $enddate = findEndDateHref($href); if($enddate) { $href->{'end'} = $enddate;}}
                  if($enddate){
                      ($emonth, $eday, $eyear, $rest) = split(/\//,$enddate);
                      if(mdyAafterB($month, $day, $year, $emonth, $eday, $eyear)) {
                          $href->{'deleted'} = 1;
                          $changed ++;
                      }
                  }
              }
              if($changed > 0) {
                  my ($role, $tmp, $ee);
		  my $fhod = gensym;
                  if (sysopen($fhod, "$calname/data", O_WRONLY | O_CREAT, 0644) ) {
                      &webcalLock::doflock( \*$fhod, LOCK_EX, "$calname/data") or calerror("Cannot lock file '$calname/data': $!\n",1);
                      truncate($fhod, 0);
                      print $fhod "\@::caldata = (\n";
                      for $href (@::caldata) {
                          next if $href->{'deleted'};
			  $tmp = print1Entry($href);
                          print $fhod $tmp;
                      }
                      print $fhod ");\n$eventCounter;\n";
                      &webcalLock::doflock( \*$fhod, LOCK_UN, "$calname/data") or calerror("Cannot unlock file '$calname/data': $!\n",1);
                      close $fhod;
                      # save a copy of deleted events and also send it it to the user
                      my $tstr = "$::now{'month'}_$::now{'day'}_$::now{'year'}_$::now{'hour'}_$::now{'min'}_$::now{'sec'}";
		      $tstr = untaintname($tstr,$::phr{'invalid_date'});
		      my $fhodd = gensym;		      
                      if (sysopen($fhodd, "$calname/data_deleted-$tstr", O_WRONLY | O_CREAT, 0644) ) {
                          &webcalLock::doflock( \*$fhodd, LOCK_EX, "$calname/data_deleted-$tstr") or calerror("Cannot lock file '$calname/data_deleted': $!\n",1);
                          truncate($fhodd, 0);
                          print $fhodd "\@::caldata = (\n";
                          for $href (@::caldata) {
                              next if ! defined($href->{'deleted'});
			      $tmp = print1Entry($href);
			      print $fhodd $tmp;
                          }
                          print $fhodd ");\n$eventCounter;\n";
                          &webcalLock::doflock( \*$fhodd, LOCK_UN,"$calname/data_deleted-$tstr") or calerror("Cannot unlock file '$calname/data_deleted': $!\n",1);
                          close $fhodd;
                      }
                  } else { calerror("$::phr{'eraseFailed'}!"); }
              }
              $msg .= "Done! <br>";
          } else { calerror("$::phr{'eraseFailed'}!");}
      }
  } elsif($acmd eq 'acpasswd') {	# change password
      my ($oldp, $npa, $npb, $npaswd, $opaswd, $pfile, $nam, $pwdd, @table, $tmp, $i, $salt);
      $npa = $::calinfo{'npasswda'};
      $npb = $::calinfo{'npasswdb'};
      $oldp = $::calinfo{'opasswd'};
      if(! $oldp) { calerror( "$::phr{'cpasswordWrong'}");}
      if( ! $npa or ($npa ne $npb)) { calerror("$::phr{'PasswordMismatch'}");}
      if( -f "$::o{'spooldir'}/$who/do_not_change_password") { calerror("This password is protected"); myexit(0);}
      my ($status, $message) = &webcalAuth::ChangeUserPassword($who, $oldp, $npa);
      if(!$status) {  calerror($message);  myexit(0); }
      $msg = "$::phr{'password_changed'}<br>\n";
  } elsif($acmd eq 'rspasswd') {	# reset password
      if($isadm or $isvgadm) {
	  my ($oldp, $npa, $npb, $npaswd, $opaswd, $pfile, $nam, $pwdd, @table, $tmp, $i, $salt, $uname, $found);
          $npa = $::calinfo{'npasswda'};
          $npb = $::calinfo{'npasswdb'};
          $uname = $::calinfo{'pcname'};
          if( ! $npa or ($npa ne $npb)) { calerror("$::phr{'PasswordMismatch'}",1);}
          if(! $uname) { calerror( "$::phr{'PleaseEnterCalendarName'}",1);}
	  if($isadm or isvgadmin($::d{'remote_user'}, $uname)) {
              $::d{'remote_user_crypted_password'} = readCookie('wcalpassword');
	      my ($status, $message) = &webcalAuth::ReplaceUserPassword($uname, $npa);
	      if(!$status) { calerror($message); myexit(0);}
              $msg = "$::phr{'password_changed'}<br>\n";
	  } else { calerror( "You're not a calendar administror.",1);}
      } else {
          $msg = "Only calendar administrator can reset user password ($::phr{'errorPerm'}).<br>\n";
      }
    } elsif ($acmd eq 'acmtgrp') {
       my $cmsg="";
       if($::calinfo{'mgpname'}) {
	   my $tmp = $::calinfo{'mgpname'}; $tmp =~ s/[\(|\)]/_/g;
          if(!validname($tmp)) { 
              calerror("Bad group name <font color=#0000ff><b>\"$::calinfo{'mgpname'}\"</b></font>. Group name must be alpha numerical",1);
          } 
	  my($gpname, $mgpname, $mpts, @mptsl, $mbr, $prevmbr, $username, $calname, $key, $value);
          my($gmgrpfile);
	  $gpname = $::calinfo{'mgpname'};
	  $gpname =~ s/ +$//g;
	  $gpname =~ s/^ +//g;
	  $gpname =~ s/ +/_/g;
          $gpname =~ s/\($::phr{'global'}\)//g;
	  $mgpname = "mgp_" . $gpname;
          my $mgnam = $mgpname . "()";
	  $gmgrpfile="$::o{'spooldir'}/GlobalMeetingGroups";
          if( -f $gmgrpfile) {
              %::GlobalMeetingGroups=();
              doReadFile( $gmgrpfile);
              if(defined $::GlobalMeetingGroups{$mgpname} or defined $::GlobalMeetingGroups{$mgnam}) {
                  calerror("$gpname:  $::phr{'groupnametaken'}",1);
                  myexit(0);
              }
          }
	  $username=$::calinfo{'w'};
	  $calname="$::o{'spooldir'}/$username";
	  %::meetingGroups = ();
          my $pdefed=0;
	  if( -f "$calname/mgroup") {
              doReadFile("$calname/mgroup");
              $pdefed=1 if $::meetingGroups{$mgpname};
	   }

	  $mpts = $::calinfo{'mpts'};
	  $mpts =~ s/^:+//;
	  @mptsl = sort split /[,:; ]+/, $mpts;
	  $mpts = "";  $prevmbr = "_";
	  foreach $mbr (@mptsl) {
	    next if $mbr eq "";
	    if ($mbr ne $prevmbr) {
		if(! ismember($mbr, $::o{'corporate_calendar'})) {
		    $mpts .= ":".$mbr ;
		    $prevmbr = $mbr;
		} else {$cmsg .= "$mbr, ";}
	    }
	  }
	  $mpts =~ s/^[:]+//;
          $tmp= $mpts; $tmp=~ s/://g; if($tmp ne "" and !validmname($tmp)) { 
              calerror("Member names must be alpha numerical. <b><font color=#0000ff>$mpts</font></b>",1);
              myexit(1);
          }
          #== 11/12/03 append a () at the end of all meeting group names
          #== This is an invalid uid, hence eliminate name clashes with uids.
          if(not $pdefed) {
               if($mgpname !~ /\(\)$/ ) { $mgpname .= "()";}
          }
          # == 11/12/03

          $::meetingGroups{$mgpname} = $mpts;
	  my $fhr = gensym;
	  if(sysopen($fhr, "$calname/mgroup", O_WRONLY | O_CREAT, 0644)) {
            &webcalLock::doflock( \*$fhr, LOCK_EX,"$calname/mgroup") or calerror("Cannot lock file '$calname/mgroup': $!\n",1);
            truncate($fhr, 0);
	    print $fhr  '%::meetingGroups =(',"\n";
	    for $key (keys %::meetingGroups) {
	    $value = $::meetingGroups{$key};
		if($value) { print $fhr "\'$key\' => \'$value\',\n"; }
	    }
	    print $fhr ");\n";
            &webcalLock::doflock( \*$fhr, LOCK_UN,"$calname/mgroup") or calerror("Cannot unlock file '$calname/mgroup': $!\n",1);
	    close $fhr;
	  } else { calerror("$::phr{'cannot_open'} $calname/mgroup.",1); }
	  $msg =  "$::phr{'Meeting_group'} $gpname $::phr{'updated'}.";
	   if($cmsg) {
	       $cmsg =~ s/,\s*$//g;
	       $msg .="<br> <font color=blue>Corporate Calendar <b>$cmsg</b> cannot be in any work groups. It is removed from the list.</font>";
	   }
       } else {
	   calerror("Please enter a group name",1);
       }
    } elsif ($acmd eq 'acgmtgrp') {
       my $cmsg ="";
       if($::calinfo{'gmgpname'}) {
	 my $tmp = $::calinfo{'gmgpname'}; $tmp =~ s/[\(|\)]/_/g;
         if(!validname($tmp)) { 
              calerror("Bad group name <font color=#0000ff><b>\"$::calinfo{'gmgpname'}\"</b></font>. Group name must be alpha numerical",1);
          } 
	  my($gpname, $mgpname, $mpts, @mptsl, $mbr, $prevmbr, $username, $calname, $key, $value, $used);
          my($gmgrpfile);
	  $gpname = $::calinfo{'gmgpname'};
	  $gpname =~ s/ +$//g;
	  $gpname =~ s/^ +//g;
	  $gpname =~ s/ +/_/g;
	  $mgpname = "mgp_" . $gpname;
          # verify that the name is not being used
          $used = meetingGroupNameUsed($mgpname);
          if($used) {
              calerror("$gpname:  $::phr{'groupnametaken'}",1);
              myexit(0);
          }
	  $gmgrpfile="$::o{'spooldir'}/GlobalMeetingGroups";
	  %::GlobalMeetingGroups = ();
          my $pdefed = 0;
	  if( -f "$gmgrpfile") {
              doReadFile( "$gmgrpfile");
              $pdefed = 1 if $::GlobalMeetingGroups{$mgpname};
	   }
	  $mpts = $::calinfo{'gmpts'};
	  $mpts =~ s/^:+//;
	  @mptsl = sort split /[,:; ]+/, $mpts;
	  $mpts = "";  $prevmbr = "_";
	  foreach $mbr (@mptsl) {
	    next if $mbr eq "";
	    if ($mbr ne $prevmbr) {
		if(! ismember($mbr, $::o{'corporate_calendar'})) {
		    $mpts .= ":".$mbr ;
		    $prevmbr = $mbr;
		} else { $cmsg .= "$mbr, ";}
	    }
	  }
	  $mpts =~ s/^[:]+//;
          $tmp= $mpts; $tmp=~ s/://g; if($tmp ne "" and !validmname($tmp)) { 
              calerror("Member names must be alpha numerical. <b><font color=#0000ff>$mpts</font></b>",1);
              myexit(1);
	  }
          #== 11/12/03 append a () at the end of all meeting group names
          #== This is an invalid uid, hence eliminate name clashes with uids.
          if(not $pdefed) {
               if($mgpname !~ /\(\)$/ ) { $mgpname .= "()";}
          }
          # == 11/12/03
	  $::GlobalMeetingGroups{$mgpname} = $mpts;

	  my $fhrg = gensym;
          if(sysopen($fhrg, "$gmgrpfile", O_WRONLY | O_CREAT, 0644)) {
            &webcalLock::doflock( \*$fhrg, LOCK_EX,"$gmgrpfile") or calerror("Cannot lock file '$gmgrpfile': $!\n",1);
            truncate($fhrg, 0);
	    print $fhrg  '%::GlobalMeetingGroups =(',"\n";
	    for $key (keys %::GlobalMeetingGroups) {
	    $value = $::GlobalMeetingGroups{$key};
		if($value) { print $fhrg "\'$key\' => \'$value\',\n"; }
	    }
	    print $fhrg ");\n";
            &webcalLock::doflock( \*$fhrg, LOCK_UN,"$gmgrpfile") or calerror("Cannot unlock file '$gmgrpfile': $!\n",1);
	    close $fhrg;
	  } else { calerror("$::phr{'cannot_open'} $gmgrpfile.",1); }
	  $msg =  "$::phr{'Meeting_group'} $gpname $::phr{'updated'}.";
	 if($cmsg) {
	       $cmsg =~ s/,\s*$//g;
	       $msg .="<br> <font color=blue>Corporate Calendar <b>$cmsg</b> cannot be in any work groups. It is removed from the list.</font>";
	   }
     } else {
	 calerror("Please enter a group name",1);
     }
    } elsif($acmd eq 'acmerge') {
        my($mcal, @mcals, $cname, @save, $counter, @keys, $modified, $total, $tmp, $calname);
        my($isadmin,$cprivacy, $eprivacy, $doit, $tmsg, $pcount);
        $tmsg=""; $pcount=0; $counter=0;
        $_ = $::calinfo{'mergecal'};
        s/[ ,;]+/:/g;
        (@mcals) = split(/:/,$_);
        $who = untaintname($who,$::phr{'Invalidusername'});
        $isadmin= &isadmin($who);
        if(!$isadmin){ 
            for $mcal (@mcals) {if($mcal =~ m/^\//g){calerror("Only calendar administrators are allowed to read a local calendar file");}}
        }

        # first read in the current calendar data
        $calname="$::o{'spooldir'}/$who";
	my $fht = gensym;
        if( -f "$calname/data" and sysopen($fht, "$calname/data", O_WRONLY | O_CREAT, 0644) ) {
            &webcalLock::doflock( \*$fht, LOCK_EX,"$calname/data") or calerror("Cannot lock file '$calname/data': $!\n",1);
            $counter = do "$calname/data";

            # keys holds the vital fields for a calendar entry. Ignore entries
            # if all vital fields match an existing entry.
            (@keys) = ('kind', 'date', 'start', 'duration', 'occurs',  'repeat', 'what', 'detail');
            $modified = $counter;
            $total = 0;

            for $mcal (@mcals) {
                my($href, $key, $role, $flag, $matched, $ee, $isfile, $isreader);
                next if $mcal eq $who;
                $isfile=0;
                if($mcal =~ m/^\//g) {
                    $cname = $mcal;
                    $isfile = 2;
                } else {
                    $mcal = untaintname($mcal,$::phr{'Invalidcalendarname'});
                    $cname="$::o{'spooldir'}/$mcal/data";
                }
                $cprivacy= $isfile; my $isvgadmin= isvgadmin($::d{'remote_user'}, $mcal); 
                if(!$isadmin and ! $isvgadmin and ! $isfile) { # $who is not an admin. 
                    $cprivacy = &getinfo($mcal, 'privacy');
		    if($cprivacy) { $cprivacy = $::privacyTable{$cprivacy};} else { $cprivacy=4;}
                }
                # readers and writers can always merge  
                $isreader = isre($who, $mcal, 'any');
                if( -f $cname) {
                    if( $isadmin or $isvgadmin or $cprivacy>2 or $isreader) {
                        (@save) = (@::caldata);
                        @::caldata=();
                        # check file is a valid calendar file
                        my ($line, $tmsg) = ("", "");
			my $fhmf = gensym;
                        if(open($fhmf, "<$cname")) {
                            &webcalLock::doflock( \*$fhmf, LOCK_SH,"$cname") or calerror("Cannot lock file '$cname': $!\n",1);
                            my $line = <$fhmf>;
                            if($line !~ /\@::caldata = \(/ ) { $tmsg = "File <b><font color=#0000ff>$cname</font><b> is not a valid webCalendar data file";}# \)
                                &webcalLock::doflock( \*$fhmf, LOCK_UN,"$cname") or calerror("Cannot lock file '$cname': $!\n",1);
                            close $fhmf;
                        } else { $tmsg = "Cannot open <b>$cname</b>. $!";}
                        if($tmsg) {
                            &webcalLock::doflock( \*$fht, LOCK_UN, "$calname/data") or calerror("Cannot unlock file '$calname/data': $!\n",1);
                            close $fht;
                            calerror($tmsg); myexit(0);
                        }
                        doReadFile($cname);
                        foreach $href (@::caldata) {
                            if(!$isadmin and !$isvgadmin and ! $isfile and ! $isreader) {
                                if(defined $href->{'privacy'}) {$doit = $::privacyTable{$href->{'privacy'}};} 
                                else {$doit = $cprivacy;}
                            } else {$doit = 4;}
                            
                            if($doit > 3) {
                                $matched = 0;
                                foreach $ee (@save) {
                                    $flag = 1;
                                    foreach $key (@keys) {
                                        if($href->{$key}) { if(!$ee->{$key} or $href->{$key} ne $ee->{$key}){ $flag = 0; last;}}
                                        else { if($ee->{$key}) {$flag=0; last;}}
                                    }
                                    if($flag) { $matched = 1; last; }	#we have a matched entry;
                                }
                                if($matched == 0) {	#mark this entry for later merge
                                    $href->{'i'} = 1;
                                    $counter++;
                                    $href->{'key'} =$counter;
                                    if(! $href->{'end'}) {
                                        my $enddate = findEndDateHref($href); 
                                        if($enddate) { $href->{'end'} = $enddate;}
                                    }
                                }
                            } else {$pcount++;}
                        }
                        foreach $href (@::caldata) {   if($href->{'i'} and  $href->{'i'} == 1) {  delete $href->{'i'}; push(@save, $href); }}
                        (@::caldata) = (@save);
                    } else { $tmsg .=  "$mcal -- $::phr{'errorPerm'};<br>"; }
                }
                if($modified != $counter) {
                    my $j=0;
                    # if(sysopen(FILET, "$calname/data", O_WRONLY | O_CREAT, 0644) ) {
                    #    &webcalLock::doflock( \*FILET, LOCK_EX,"$calname/data") or calerror("Cannot lock file '$calname/data': $!\n",1);
                    truncate($fht, 0);
                    print $fht "\@::caldata = (\n";
                    for $href (@::caldata) {
                        $tmp = print1Entry($href);
                        print $fht $tmp;
                    }
                    print $fht ");\n$counter;\n";
                    #   }
                    $total += $counter - $modified;
                    $modified = $counter;
                }
            }
            $msg = "$total $::phr{'new_entries'} <br> $tmsg";
            if($pcount > 0 ) { $msg .= "$pcount entries not merged due to permission problem"};
         
            &webcalLock::doflock( \*$fht, LOCK_UN, "$calname/data") or calerror("Cannot unlock file '$calname/data': $!\n",1);
            close $fht;
        } else { calerror($::phr{'openFailed'});}
    } else { calerror("$::phr{'Unknown_command'}"); }
    if($msg) {
        $view=$::calinfo{'v'};
        $ls = $::calinfo{'ls'};
	$month= $::calinfo{'month'};
	$day  = $::calinfo{'day'};
	$year = $::calinfo{'year'};
	my $cmd;
	if($::calinfo{'ret_p'}) {  $cmd = $::calinfo{'ret_p'};} else {$cmd='get';}
	if($::calinfo{'opcode'}) { $cmd .= "&opcode=$::calinfo{'opcode'}";}


        &headers($::phr{'Acknowledgement'},undef,"5; URL=$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=$view&d=$month/$day/$year$::vmg",1);
	print "<center><br>";
	print "<br><font color=#ff0000>$msg</font><br><br>";
	print "<br><a href=\"javascript:history.go(-1)\"><b>$::phr{'GoBack'}</b></a>";
	&trailer(0,0);
    } else {
        &readData;
	&calendar;
    }
    myexit(0);
}
#====================================================================================
sub delete_cache_1 {
    my ($who) = (@_); $who=untaintname($who);
    my $cnt=0;
    if($who) {
        my $DIR1= gensym;
        if( -f "$::o{'spooldir'}/$who/mcache") {
	    unlink "$::o{'spooldir'}/$who/mcache";
	}
        my $dir="$::o{'spooldir'}/$who/cache";
        if (opendir($DIR1, $dir)) {
            my @entries = readdir($DIR1); closedir($DIR1);          
            my $file;
            foreach $file (@entries) {
                next if $file eq "." or $file eq ".."; 
		$file=untaintname($file); my $f = "$dir/$file";
                if(-f $f) {unlink $f; $cnt++;}
            }
        }
	my $cssfile ="$::o{'imgdir'}/$::o{'stylesheetdir'}/${who}.css";
	if( -f $cssfile) { unlink $cssfile;}
    }
    return $cnt;
}
#====================================================================================
sub delete_all_cache_files {
    my $DIR00= gensym;
    my $dir="$::o{'spooldir'}";
    my $total = 0;
    if (opendir($DIR00, $dir)) {
        my @entries = readdir($DIR00); closedir($DIR00);              
        my ($cal);
        foreach $cal (@entries) {
            next if $cal eq "." or $cal eq "..";
            if( -d "$dir/$cal") { $total += delete_cache_1($cal);} 
        }
    }
    $dir="$::o{'imgdir'}/$::o{'stylesheetdir'}";
    if (opendir($DIR00, $dir)) {
        my @entries = readdir($DIR00); closedir($DIR00);              
        my ($ff);
        foreach $ff (@entries) {
            next if $ff eq "." or $ff eq "..";
	    if( $ff =~ /\.css$/ and  -f "$dir/$ff") {
		$ff = untaintname($ff); unlink "$dir/$ff";
		$total ++;
	    }
	}
    }
    if( -f "$::o{'spooldir'}/.namelist") { unlink "$::o{'spooldir'}/.namelist"; $total++;}

    return $total;
}
#====================================================================================
sub meetingGroupNameUsed {
    my ($mgpname) = (@_);
    my(@cals, $cal, $name, $dir);
    my $pgpname = untaintname($mgpname,"");
    my $mgnam=$mgpname."()";
    @cals = &listcals;
    foreach $cal (@cals) {
        $cal = untaintname($cal,"");
	$dir = "$::o{'spooldir'}/$pgpname";
	if(-d "$dir") { return 1;}
        $name = "$::o{'spooldir'}/$cal/mgroup";
        if( -f $name) {
            $::meetingGroups = ();
            doReadFile("$name");
            if( defined $::meetingGroups{$mgpname} or defined $::meetingGroups{$mgnam}) { return 1;}
        }
    }
    return 0;
}
#====================================================================================
sub search {
    my ($who, $view, $start, $start0, $end, $date, $udate0, $udate1, $udate2, $mg, $cnames, $ls, $day, $month, $year);
    $who=$::calinfo{'w'};
    $view=$::calinfo{'v'};
    $ls = $::calinfo{'ls'};
    $day = $::calinfo{'day'};
    $month = $::calinfo{'month'};
    $year = $::calinfo{'year'};
    $start0 = printDate($month,$day,$year-1);
    $start = printDate($month,$day,$year);
    $date = printDate0($month,$day,$year);
    $end = printDate($month,$day,1+$year);
    $udate0 = to_native_date($start0);
    $udate1 = to_native_date($start);
    $udate2 = to_native_date($end);

    my $isadm = isadmin($::d{'remote_user'});  my $isvgadm= $isadm || isvgadmin($::d{'remote_user'},$who);
    my $rlevel = $isadm;
    if(! $isadm and ! $isvgadm) {
        if( $::d{'ispublic'} == 0) {
            if( isre($::d{'remote_user'}, $who, 'editors') ) { $rlevel = 10;}
            elsif( isre($::d{'remote_user'}, $who, 'readers') ) { $rlevel = 1;}
        } else { $rlevel = 10;}
    }

    if(defined $::calinfo{'mg'} and $::calinfo{'mg'} ne "")
      {$mg="<input type=hidden name=mg value=\"$::calinfo{'mg'}\">"; $cnames= $::calinfo{'mg'};}
    else {$mg=""; $cnames = $who;}
    my ($body, $script) = &getClockScript();

    #&make_style_sheet();   

    &headers($::phr{'Search_Calendar'},$script,undef,1,0,$body);

    my $headerForm=&newHeader('search', 1);
    print $headerForm;


    print "<center>
<table bgcolor=$webcalConfig::r{'dkbackground'} border=3 cellpadding=4 cellspacing=0 width=\"70%\" class=\"search\">
<tr><th width=\"100%\"><font size=+1 color=#ff0000><span class=\"miscTitle\">$::phr{'Search_Calendar'} <font color=#009900>($cnames)</font></span></font></th></tr>
<tr><td width=\"100%\">
<Form name=calendar action=\"$::o{'cginame'}\" method=GET>$::vmp
<input type=hidden name=c value=dosearch>
<input type=hidden name=w value=\"$who\">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value=\"$date\">
$mg
<table width=\"100%\" border=0 cellpadding=0 cellspacing=0 class=\"search\">
<tr><td align=center><b><span class=\"fmLabel\">$::phr{'Keyword'}:&nbsp;</span></b>
  <input type=text size=40 maxlength=128 name=stopic value=\"\" class=\"fmEntry\">
</td></tr>
<tr><td>&nbsp;&nbsp;<input type=radio name=searchRange value=\"all\" class=\"fmRadio\"><span class=\"fmLabel\">&nbsp;&nbsp;$::phr{'SearchAll'}</span></td></tr>
<tr><td nowrap>&nbsp;&nbsp;<input type=radio checked name=searchRange value=\"period\" class=\"fmRadio\"><span class=\"fmLabel\">&nbsp;&nbsp;$::phr{'Search_From'}:&nbsp;</span>
<input type=text size=10 maxlength=16 name=searchFrom value=\"$udate1\" class=\"fmEntry\">",
     linkSmallCal("calendar.searchFrom",$who,$month,$year),
"<span class=\"fmLabel\">&nbsp;&nbsp;$::phr{'To'}:&nbsp;</span><input type=text  class=\"fmEntry\" size=10 maxlength=16 name=searchTo value=\"$udate2\">",
     linkSmallCal("calendar.searchTo",$who,$month,$year+1),"</td>
</tr>
<tr><td colspan=2 align=center><hr></tr>
<tr>
<td colspan=2 align=center>
 <input type=submit name=action class=\"fmBtnSt\" value=\"$::phr{'Submit'}\">
 <input type=submit name=action class=\"fmBtnSt\" value=\"$::phr{'Cancel'}\">
</table></Form></td></tr></table><br>";

if($rlevel) {
    if(! defined $::calinfo{'mg'} or $::calinfo{'mg'} eq "") {
      print "
<table bgcolor=$webcalConfig::r{'dkbackground'} border=3 cellpadding=4 cellspacing=0 width=\"70%\" class=\"search\">
<tr><th width=\"100%\"><font size=+1 color=#ff0000><span class=\"miscTitle\">$::phr{'SearchDiary'} <font color=#009900>($who)</font></span></font></th></tr>
<tr><td width=\"100%\">
<Form name=diary action=\"$::o{'cginame'}\" method=GET>$::vmp
<input type=hidden name=c value=\"sdiary\">
<input type=hidden name=w value=\"$who\">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value=\"$date\">
<table width=\"100%\" border=0 cellpadding=0 cellspacing=0 class=\"search\">
<tr><td align=center><b><span class=\"fmLabel\">$::phr{'Keyword'}:&nbsp;</span></b>
 <input type=text size=40 maxlength=128 name=stopic value=\"\" class=\"fmEntry\">
</td></tr>
<tr><td>&nbsp;&nbsp;<input type=radio name=searchRange value=\"all\" class=\"fmRadio\"><span class=\"fmLabel\">&nbsp;&nbsp;$::phr{'SearchAll'}</span></td></tr>
<tr><td nowrap>&nbsp;&nbsp;<input type=radio checked name=searchRange value=\"period\" class=\"fmRadio\"><span class=\"fmLabel\">&nbsp;&nbsp;$::phr{'Search_From'}:&nbsp;</span>
<input type=text size=10 maxlength=16 name=searchFrom value=\"$udate0\" class=\"fmEntry\">",
    linkSmallCal("diary.searchFrom",$who,$month,$year-1),
"<span class=\"fmLabel\">&nbsp;&nbsp;$::phr{'To'}:&nbsp;</span><input type=text class=\"fmEntry\" size=10 maxlength=16 name=searchTo value=\"$udate1\">",
    linkSmallCal("diary.searchTo",$who,$month,$year),"</td>
</tr>
<tr><td colspan=2 align=center><hr></tr>
<tr>
<td colspan=2 align=center>
 <input type=submit class=\"fmBtnSt\" name=action value=\"$::phr{'Submit'}\">
 <input type=submit class=\"fmBtnSt\" name=action value=\"$::phr{'Cancel'}\">
</table></Form></td></tr></table><br>";
    }
    print <<END;
<table bgcolor=$webcalConfig::r{'dkbackground'} border=3 cellpadding=4 cellspacing=0 width="70%" class="search">
<tr><th width="100%"><font size=+1 color=#ff0000><span class="miscTitle">$::phr{'SearchNotes'} <font color=#009900>($cnames)</font></span></font></th></tr>
<tr><td width="100%">
<Form action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value="notes">
<input type=hidden name=ntc value="s">
<input type=hidden name=w value="$who">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$date">
<table width="100%" border=0 cellpadding=0 cellspacing=0 class="search">
<tr><td align=right><b><span class="fmLabel">$::phr{'Keyword'}:&nbsp;</span></b></td><td>
<input type=text name=stopic size=20 maxlength=128 class="fmEntry"></td>
</td></tr>
<tr><td colspan=2 align=center><hr></tr>
<tr>
<td colspan=2 align=center>
 <input type=submit class="fmBtnSt" name=action value="$::phr{'Submit'}">
 <input type=submit class="fmBtnSt" name=action value="$::phr{'Cancel'}">
</table></Form></td></tr></table><br>
END
    ;

    print <<END;
<table bgcolor=$webcalConfig::r{'dkbackground'} border=3 cellpadding=4 cellspacing=0 width="70%" class="search">
<tr><th width="100%"><font size=+1 color=#ff0000><span class="miscTitle">$::phr{'SearchAddress'} <font color=#009900>($cnames)</font></span></font></th></tr>
<tr><td width="100%">
<Form action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value="sad">
<input type=hidden name=w value="$who">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$date">
<table width="100%" border=0 cellpadding=0 cellspacing=0 class="search">
<tr><td align=right><b><span class="fmLabel">$::phr{'Keyword'}:&nbsp;</span></b></td><td>
<input type=text name=kword size=20 maxlength=128 class="fmEntry"></td>
</td></tr>
<tr><td colspan=2 align=center><hr></tr>
<tr>
<td colspan=2 align=center>
 <input type=submit class="fmBtnSt" name=action value="$::phr{'Submit'}">
 <input type=submit class="fmBtnSt" name=action value="$::phr{'Cancel'}">
</table></Form></td></tr></table><br>
END
    ;
}
    &trailer(0,0);
}

#====================================================================================
sub dateInRange {	# check if e is in [a, b], return 0 if yes, -1 if e is before a, 1 if e is after b
    my ($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb) = (@_);
    if($sye < $sya) {
	return -1;
    } elsif($sye > $syb) {
	return 1;
    } elsif ($sye == $sya) {
	if($sme < $sma or ($sme == $sma and $sde < $sda)) { return -1;}
	else {
	    if ($sye < $syb) {
		return 0;
	    } else {	#must be $sye == $syb == $sya
		if( $sme < $smb or  ($sme == $smb and $sde <= $sdb)) { return 0;}
		return 1;
	    }
	}
    } elsif ($sye == $syb) {
	if($sme > $smb or ($sme == $smb and $sde > $sdb)) { return 1;}
	else {
	    return 0;
	}
    } else {	#must be:  $sya < $sye < $syb
	return 0;
    }
}

#======================================================================================================
sub buildMExpr {
    my ($in) = (@_); $in = " $in ";
    $in =~ s/(\s+[\(|\)|\-|\+|\!|\||\&])/ $1 /g; $in =~ s/([\(|\)|\-|\+|\!|\||\&])\s+/ $1 /g;
    $in =~ s/\s+\|\s+\|\s*/ \|\| /g; $in =~ s/\s*\|\s+\|\s+/ \|\| /g; 
    $in =~ s/\s+\&\s+\&\s*/ \&\& /g; $in =~ s/\s*\&\s+\&\s+/ \&\& /g;     

    my (@out, @words, $op, $start, $tmp, $inq, $ins);
    if( $in =~ m/\"[^\"]+\"/) { #"
	$inq=$ins=0;
	$in =~ s{(.)}{
	    if($1 eq "\"") { if($inq) { $inq=0; $ins=0;} else {$inq=1;}; "";}
	    elsif($inq) {
		if($1 eq ' ' or $1 eq "\t") { if($ins == 0) { $ins=1; '(\s*)';} else { "";}}
		else {$ins=0; $1;} 
	    }
	    else { $1;}
	}gsex;
    }
   
    @words = split(/[ \t]+/, $in);
    @out =();  $op = 0; $start = 1;
    foreach $tmp (@words) {
	if( $tmp ne "") {
	    if($tmp eq "+" or $tmp eq 'and' or $tmp eq 'AND' or $tmp eq '&' or $tmp eq '&&') {
		push(@out, 'and'); $op = 1;
	    } elsif($tmp eq "-" or $tmp eq '!' or $tmp eq 'not' or $tmp eq 'NOT') {
		if(! $start and ! $op) { push(@out, 'and');}
		push(@out, 'not'); $op =1;
	    } elsif( $tmp eq 'or' or $tmp eq 'OR' or $tmp eq '|' or $tmp eq '||') {
		push(@out, 'or'); $op =1;
	    } elsif ($tmp eq '(') {
		if(!$start and !$op) { push(@out, 'or');}
		push(@out, '('); $op =1 ;
	    } elsif ($tmp eq ')') {
		push(@out, ')'); $op =0 ;
	    } else {
		if(!$start and ! $op) { push(@out, 'or');}
		$op =0;
		push(@out, html_escape($tmp,1));
	    }
	    $start = 0;
	}
    }
    return (@out);
}
sub matchMExpr {
    my ($keyref, $str) = (@_);
    my (@in, $expr, $word, $lenw, $matched);
    @in = @$keyref;
    $expr = "";
    return 0 if not $str;
    foreach $word (@in) {
	if($word =~ /^(not|or|and|\(|\))$/i) { $expr .= " $word "; }
	else {
	    $matched=0;
	    if($str =~ /$word\b|\b$word/i) { $matched = 1;};
	    $expr .= " $matched ";
	}
    }
    return 1 if eval($expr);
    return 0;
}

sub matchSrchExpr {
    my ($str) = (@_);
    my ($expr, $word, $lenw, $matched);
    $expr = "";
    return 0 if not $str;
    foreach $word (@::srchwords) {
	if($word =~ /^(not|or|and|\(|\))$/i) { $expr .= " $word "; }
	else {
	    $matched=0;
	    if($str =~ /$word\b|\b$word/i) { $matched = 1;};
	    $expr .= " $matched ";
	}
    }
    my $ans =  eval($expr);
#    $::debugInfo{$str} = $ans;
    return $ans;

}

#======================================================================================================
sub annotate {
    my ($keyref, $str) = (@_);
    my (@in, $i, $cnt, $word, $matched);
    @in = @$keyref;
    return "" if not $str;
    $cnt=0;
    my @bgs = ('#ffff00', '#ff99ff', '#ff9900',  '#ff9c6f', '#cc3399', '#0099ff', '#c9fcc2');
    foreach $word (@in) {
	next if $word =~ /^(not|or|and|\(|\))$/i;
        $str =~ s/(\b$word|$word\b)/_<_${cnt}_>_$1_<_>_/ig;
        $cnt++;
    }
  for($i=0; $i<$cnt; $i++) {
      my $bg = $bgs[$i];
      $str =~ s/_<_${i}_>_/<b style="background-color:$bg">/g;
  }
  $str =~ s/_<_>_/<\/b>/g;
  return $str;
}
#======================================================================================================


sub dosearch {
    use integer;
    my ($i,$j,$k, $adv, $who, $stopic, $view, $edate, $date, $srange, $sfrom, $sto, $out, $username, $href,
	$calname, $des, %table, $etime, $sma, $sda, $sya, $smb, $sdb, $syb , $sme, $sde, $sye, $x, $syr,$srefs,
	$occurs, $repeat, $wday, $exception, $elength, $check, $tmp, $kind, $cdate, $kk, $code, $detail, $junk,
	@keys, $key, $tmn, $mn, $dy, $yr, $hr, $nn, $tim, $gprivacy, $eprivacy, %dtable, $mg,$owner, $ls, %mtable);
    my($fm, $fd, $tm, $td, $fy, $ty, %roomtable, %cattable, %spkrtable, $tiptag);
    $stopic = $::calinfo{'stopic'};
    if(! $stopic) { calerror("$::phr{'SearchSubjectEmpty'}",1);}
    my @searchwords = &buildMExpr($stopic);
    if(defined $::calinfo{'mg'} and $::calinfo{'mg'} ne "") {$mg="&mg=$::calinfo{'mg'}";} else {$mg="";}
    %table=();
    %dtable=();
    %mtable=();
    %roomtable=(); %cattable=(); %spkrtable=();
    $who = $::calinfo{'w'};
    $view = $::calinfo{'v'};
    $ls = $::calinfo{'ls'};
    $cdate=$date = $::calinfo{'d'};
    $srange = $::calinfo{'searchRange'};
    $username=$::calinfo{'w'};
    $calname="$::o{'spooldir'}/$username/data";
    $sfrom = $::calinfo{'searchFrom'};
    $sto = $::calinfo{'searchTo'};
    $srefs = ($::vm & 0x200);
    %::oneDayEventRefs= ();
    $tiptag = 0;

    ($gprivacy, $junk) = getPrivacy(0);

    if( -f $calname ) {
	if(not $srange or $srange eq 'all') {
	    $sfrom = $::calinfo{'searchFrom'} = '1/1/1997';
	    $sto = $::calinfo{'searchTo'} = '12/31/2030';
	};
	if($::calinfo{'sfday'}) {
	    my $year = $::calinfo{'year'};
	    $fm = $::calinfo{'sfmonth'};
	    $fd = $::calinfo{'sfday'};
	    $tm = $::calinfo{'stmonth'};
	    $td = $::calinfo{'stday'};
	    $fy = $ty = $year;
	    if($tm < $fm) { if($tm <= 5) {$fy -= 1;} else { $ty += 1;}}
	    elsif($tm == $fm and $td < $fd) { my $tmp = $td; $td = $fd, $fd = $tmp;} 
	    $sfrom = "$fm/$fd/$fy";
	    $sto = "$tm/$td/$ty";
	}
	($sma, $sda, $sya) = split(/\//,$sfrom);	# month is from 1-12 here
	($smb, $sdb, $syb) = split(/\//,$sto);
        if(! $sma or ! $sda or ! $sya or ! $smb or ! $sdb or ! $syb) {
            calerror("$::phr{'invalid_date'}: [$sfrom]   [$sto]",1);
        }
	$sma--; $smb--;
        ($sma, $sda, $sya) = canDate($sma, $sda, $sya);
        ($smb, $sdb, $syb) = canDate($smb, $sdb, $syb);

	if( $syb < $sya or ($syb == $sya and $smb < $sma) or ($syb == $sya and $smb == $sma and $sdb < $sda)) {
	    ($sme, $sde, $sye) = ($sma, $sda, $sya);
	    ($sma, $sda, $sya) = ($smb, $sdb, $syb);
	    ($smb, $sdb, $syb) = ($sme, $sde, $sye);
	}

        if($mg) { $::calinfo{'mattendants'} = "$::calinfo{'mg'}"; &getMegaCalendarData; $gprivacy = 2; $tiptag=1;}

	
	for $href (@::caldata) {
            if($gprivacy > 3) { $eprivacy = 3;}
            else {
                if(defined $href->{'e'} or (defined $href->{'w'} and $href->{'w'} eq $::d{'remote_user'})) { $eprivacy = 3;} # for megaCalendar
                elsif(defined $href->{'privacy'}) { $eprivacy = $::privacyTable{$href->{'privacy'}} -1; }
		else {$eprivacy = $gprivacy;}
	    }
	    next if $eprivacy < 2;
  	    $des =  $href->{'what'} || "";
	    if($eprivacy >= 3) {$detail = $href->{'detail'};} else {$detail = "";}
	    if( matchMExpr(\@searchwords, $des) or 
		($eprivacy > 2 and ( ($detail and matchMExpr(\@searchwords, $detail)) or
				     ($href->{'kwd'} and matchMExpr(\@searchwords, $href->{'kwd'})) or 
				     ($href->{'room'} and matchMExpr(\@searchwords, $href->{'room'})) or 
				     ($href->{'cat'} and matchMExpr(\@searchwords, $href->{'cat'})) or 
				     ($href->{'spkr'} and matchMExpr(\@searchwords, $href->{'spkr'})) or 
				     ($href->{'ctp'} and matchMExpr(\@searchwords, $href->{'ctp'})) or 
				     ($href->{'ctm'} and matchMExpr(\@searchwords, $href->{'ctm'})) ) ))
	    {
		if($href->{'cs'}){ $des="<span class=\"$href->{'cs'}\">" . $des . "</span>"; }
		$edate = $href->{'date'};
		$etime = $href->{'start'};
		$kind = $href->{'kind'};
		$occurs = $href->{'occurs'};
		$exception = $href->{'exception'};
		if($exception) { $elength = $#$exception;} else {$elength = -1;}
		$key = $href->{'key'};
		$repeat = $href->{'repeat'};
		if(defined $href->{'detail'}) {$detail =  $href->{'detail'};} else {$detail="";}

                my ($misc, $troom, $tspkr, $tcat, $trest)  = getMiscInfo($href);
                if($ls < 0) { if($trest) { if($detail) { $detail .= " <br>";}	 $detail .= $trest;}}
		elsif($misc) {  if($detail) { $detail .= " <br>";}  $detail .= $misc; }
                
		if(!$repeat or $repeat eq "0" or !$occurs or $occurs eq 'OneTime') {
		    ($sme, $sde, $sye) = split(/\//,$edate); $sme--;
		    $check= dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
		    if($check == 0) {
                      if(defined $href->{'w'}) { $owner= $href->{'w'}; $kk= "$sme/$sde/$sye/$etime/$kind/$key/$owner";}
                      else { $kk= "$sme/$sde/$sye/$etime/$kind/$key";}
                      $table{$kk} = $des;
                      $dtable{$kk} = $detail;
		      if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr;}
		      if($srefs){$::oneDayEventRefs{$kk} = $href;}
                  }
		} else {
		    my ($endM,$endD,$endY)=("","","");
		    if($href->{'end'}) { ($endM,$endD,$endY)=split(/\//,$href->{'end'}); $endM--;}
		    if ($occurs eq "Daily") {
			($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {
				if( abs($exception->[$j]) == $i) { $k = 1; last;}
			    }
			    if($k == 0) {
				$check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				if($check ==0) {
				    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
				    $table{$kk} = $des;
				    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr;}
				    if($srefs){$::oneDayEventRefs{$kk} = $href;}
				} elsif($check == 1) { last; }
			    }
			    ($sme, $sde, $sye) = canDate($sme, $sde + 1, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "Weekly") {
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			$wday = wday($sme, $sde, $sye);	# weekday of event
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {
				if( abs($exception->[$j]) == $i) { $k = 1; last;}
			    }
			    if($k == 0) {
				$check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				if($check ==0) {
				    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
				    $table{$kk} = $des;
				    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
				    if($srefs){$::oneDayEventRefs{$kk} = $href;}
				} elsif($check == 1) { last; }
			    }
			    ($sme, $sde, $sye) = canDate($sme, $sde + 7, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "Every2Weeks") {
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			$wday = wday($sme, $sde, $sye);	# weekday of event
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {
				if( abs($exception->[$j]) == $i) { $k = 1; last;}
			    }
			    if($k == 0) {
				$check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				if($check ==0) {
				    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
				    $table{$kk} = $des;
				    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
				    if($srefs){$::oneDayEventRefs{$kk} = $href;}
				} elsif($check == 1) { last; }
			    }
			    ($sme, $sde, $sye) = canDate($sme, $sde + 14, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "MonthlyByDate") {
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {
			      if( abs($exception->[$j]) == $i) { $k = 1; last;}
			    }
			    if($k == 0) {
				$check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				if($check ==0) {
				    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
				    $table{$kk} = $des;
				    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
				    if($srefs){$::oneDayEventRefs{$kk} = $href;}
				} elsif($check == 1) { last; }
			    }
			    ($sme, $sde, $sye) = canDate($sme+1, $sde, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "MonthlyByWeekday") {
			my ($nth, $nnm);
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			$wday = wday($sme, $sde, $sye);	# weekday of event
			$code =  $sde - ($sde/7) * 7; if($code==0) { $code += 7;}	# the first wday
			$nth =  ($sde-$code)/7;	# the nth week
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {
			      if( abs($exception->[$j]) == $i) { $k = 1; last;}
			      }
			    if($k == 0) {
				$x= wday($sme, $sde, $sye);	# weekday of event
				$sde += $wday -$x;	#to the correct weekday
				if($sde <= 0) { $sde += 7;}
				$code =  $sde - ($sde / 7) *7; if($code<=0) { $code = 7;}	# the first wday
				$sde = $nth * 7 + $code;	# the nth wday
				$check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				if($check ==0) {
				  my ($mxdays, $ok);
				  $ok=1;
				  if($sde > 28) {

				    if($sme != 1) { $mxdays = $::mdays[$sme];}
				    else { if(isleap($sye)) { $mxdays = 29;} else {$mxdays = 28;}}
				    if($sde > $mxdays) { $ok=1;}
				  }
				  if($ok) {
				    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
				    $table{$kk} = $des;
				    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
				    if($srefs){$::oneDayEventRefs{$kk} = $href;}
				  } elsif($check == 1) { last; }
				}
			      }
			    ($nnm, $sde, $sye) = canDate($sme+1, $sde, $sye);
			    if($nnm != $sme+1 and $nnm != $sme-11) { $i++;}
			    $sme = $nnm;
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "Yearly") {
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {
			      if( abs($exception->[$j]) == $i) { $k = 1; last;}
			    }
			    if($k == 0) {
				$check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				if($check ==0) {
				    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
				    $table{$kk} = $des;
				    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
				    if($srefs){$::oneDayEventRefs{$kk} = $href;}
				} elsif($check == 1) { last; }
			    }
			    ($sme, $sde, $sye) = canDate($sme, $sde, $sye+1);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		     } elsif ($occurs eq "YearlyByMonthWeekday") {
			my ($nth, $nnm);
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			$wday = wday($sme, $sde, $sye);	# weekday of event
			$code =  $sde - ($sde/7) * 7; if($code==0) { $code += 7;}	# the first wday
			$nth =  ($sde-$code)/7;	# the nth week
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {
			      if( abs($exception->[$j]) == $i) { $k = 1; last;}
			    }
			    if($k == 0) {
				$check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				if($check ==0) {
				  $x = wday($sme, $sde, $sye);	# weekday of event
				  $sde += $wday -$x;	#to the correct weekday
				  if($sde <= 0) { $sde += 7;}
				  $code =  $sde - ($sde / 7) *7; if($code<=0) { $code = 7;}	# the first wday
				  $sde = $nth * 7 + $code;	# the nth wday
				  $check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				  if($check ==0) {
				    my ($mxdays, $ok);
				    $ok=1;
				    if($sde > 28) {
				      if($sme != 1) { $mxdays = $::mdays[$sme];}
				      else { if(isleap($sye)) { $mxdays = 29;} else {$mxdays = 28;}}
				      if($sde > $mxdays) { $sde=$mxdays-2; $ok=0;}
				    }
				    if($ok) {
				      $kk= "$sme/$sde/$sye/$etime/$kind/$key";
				      $table{$kk} = $des;
				      $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
				      if($srefs){$::oneDayEventRefs{$kk} = $href;}
				    }
				  } elsif($check == 1) { last; }
				}
			      }
			    ($nnm, $sde, $sye) = canDate($sme, $sde, $sye+1);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			  }
		    } elsif ($occurs eq "MTWThF") {
			my ($x, $y, $done, $err);
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			$wday = wday($sme, $sde, $sye);	# weekday of event
			$done = 0;
			for($i = 0; $i < $repeat; $i += 5, $wday=0) {
			    for($x=$wday; $x <7; $x++) {
				$err=wday($sme, $sde, $sye);
				$y= $i+$err;
				if($err and $err != 6 and $y <= $repeat) {
				    $k = 0;
				    for $j (0 .. $elength) {
				      if( abs($exception->[$j]) == $y) { $k = 1; last;}
				    }
				    if($k == 0) {
					$check=dateInRange($sme, $sde, $sye,
							   $sma, $sda, $sya, $smb, $sdb, $syb);
					if($check ==0) {
					    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
					    $table{$kk} = $des;
					    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
					    if($srefs){$::oneDayEventRefs{$kk} = $href;}
					} elsif($check == 1) { $done = 1; last; }
				    }
				}
				($sme, $sde, $sye)=canDate($sme, $sde+1, $sye);
				if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY)){$done=1;last;}
			    }
			    if($done) { last;}

			}
		    } elsif ($occurs eq "MWF") {
			my ($x, $y, $done, $err);
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			$wday = wday($sme, $sde, $sye);	# weekday of event
			$done = 0;
			for($i = 0; $i < $repeat; $i += 3, $wday=0) {
			    for($x=$wday; $x <7; $x++) {
				$err=wday($sme, $sde, $sye);
				$y = $i+(($err+1)>>1);
				if(($err & 1) and $y <= $repeat) {
				    $k = 0;
				    for $j (0 .. $elength) {
				      if( abs($exception->[$j]) == $y) { $k = 1; last;}
				    }
				    if($k == 0) {
					$check=dateInRange($sme, $sde, $sye,
							   $sma, $sda, $sya, $smb, $sdb, $syb);
					if($check ==0) {
					    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
					    $table{$kk} = $des;
					    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
					    if($srefs){$::oneDayEventRefs{$kk} = $href;}
					} elsif($check == 1) { $done = 1; last; }
				    }
				}
				($sme, $sde, $sye)=canDate($sme, $sde+1, $sye);
				if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY)){$done=1; last;}
			    }
			    if($done) { last;}
			}
		    } elsif ($occurs eq "TTh") {
			my ($x, $y, $done, $err);
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			$wday = wday($sme, $sde, $sye);	# weekday of event
			$done = 0;
			for($i = 1; $i <= $repeat; $i += 2) {
			    for($x=0; $x <7; $x++) {
				$err=wday($sme, $sde, $sye);
				$y = $i+($err>>1);
				if(($err == 2 or $err == 4) and $y <= $repeat) {
				    $k = 0;
				    for $j (0 .. $elength) {
				      if( abs($exception->[$j]) == $y) { $k = 1; last;}
				    }
				    if($k == 0) {
					$check=dateInRange($sme, $sde, $sye,
							   $sma, $sda, $sya, $smb, $sdb, $syb);
					if($check ==0) {
					    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
					    $table{$kk} = $des;
					    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
					    if($srefs){$::oneDayEventRefs{$kk} = $href;}
					} elsif($check == 1) { $done = 1; last; }
				    }
				}
				($sme, $sde, $sye)=canDate($sme, $sde+1, $sye);
				if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY)){$done=1;last;}
			    }
			    if($done) { last;}
			}
		      } elsif ($occurs eq "EveryOtherDay") {
			($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {
				if( abs($exception->[$j]) == $i) { $k = 1; last;}
			    }
			    if($k == 0) {
				$check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				if($check ==0) {
				    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
				    $table{$kk} = $des;
				    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
				    if($srefs){$::oneDayEventRefs{$kk} = $href;}
				} elsif($check == 1) { last; }
			    }
			    ($sme, $sde, $sye) = canDate($sme, $sde + 2, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			  }
		      } elsif ($occurs eq "Every3rdDay") {
			($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {
				if( abs($exception->[$j]) == $i) { $k = 1; last;}
			    }
			    if($k == 0) {
				$check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				if($check ==0) {
				    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
				    $table{$kk} = $des;
				    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
				    if($srefs){$::oneDayEventRefs{$kk} = $href;}
				} elsif($check == 1) { last; }
			    }
			    ($sme, $sde, $sye) = canDate($sme, $sde + 3, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			  }
		      } elsif ($occurs eq "Every4thDay") {
			($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {
				if( abs($exception->[$j]) == $i) { $k = 1; last;}
			    }
			    if($k == 0) {
				$check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				if($check ==0) {
				    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
				    $table{$kk} = $des;
				    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
				    if($srefs){$::oneDayEventRefs{$kk} = $href;}
				} elsif($check == 1) { last; }
			    }
			    ($sme, $sde, $sye) = canDate($sme, $sde + 4, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			  }
		      } elsif ($occurs eq "Every5thDay") {
			($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {
				if( abs($exception->[$j]) == $i) { $k = 1; last;}
			    }
			    if($k == 0) {
				$check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				if($check ==0) {
				    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
				    $table{$kk} = $des;
				    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
				    if($srefs){$::oneDayEventRefs{$kk} = $href;}
				} elsif($check == 1) { last; }
			    }
			    ($sme, $sde, $sye) = canDate($sme, $sde + 5, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			  }
		      } elsif ($occurs eq "Every6thDay") {
			($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {
				if( abs($exception->[$j]) == $i) { $k = 1; last;}
			    }
			    if($k == 0) {
				$check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				if($check ==0) {
				    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
				    $table{$kk} = $des;
				    $dtable{$kk} = $detail;
                                    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
				    if($srefs){$::oneDayEventRefs{$kk} = $href;}
				} elsif($check == 1) { last; }
			    }
			    ($sme, $sde, $sye) = canDate($sme, $sde + 6, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			  }
		    } elsif(substr($occurs,0,1) eq 'Z' and  $occurs =~ /^Z(.+),(\d+),(\d*)/) {
			my ($r, $c1, $c2) = ($1, $2, $3);
			if($r eq 'D') {
			    ($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			    for($i = 1; $i <= $repeat; $i++) {
				$k = 0;
				for $j (0 .. $elength) {
				    if( abs($exception->[$j]) == $i) { $k = 1; last;}
				}
				if($k == 0) {
				    $check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				    if($check ==0) {
					$kk= "$sme/$sde/$sye/$etime/$kind/$key";
					$table{$kk} = $des;
					$dtable{$kk} = $detail;
					if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
					if($srefs){$::oneDayEventRefs{$kk} = $href;}
				    } elsif($check == 1) { last; }
				}
				($sme, $sde, $sye) = canDate($sme, $sde + $c1, $sye);
				last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			    }
			} elsif($r eq 'MD') {
			    ($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			    for($i = 1; $i <= $repeat; $i++) {
				$k = 0;
				for $j (0 .. $elength) {
				    if( abs($exception->[$j]) == $i) { $k = 1; last;}
				}
				if($k == 0) {
				    $check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				    if($check ==0) {
					$kk= "$sme/$sde/$sye/$etime/$kind/$key";
					$table{$kk} = $des;
					$dtable{$kk} = $detail;
					if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
					if($srefs){$::oneDayEventRefs{$kk} = $href;}
				    } elsif($check == 1) { last; }
				}
				($sme, $sde, $sye) = canDate($sme+$c1, $sde, $sye);
				last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			    }
			} elsif($r eq 'MWD') {
			    my ($nth, $nnm);
			    ($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			    $wday = wday($sme, $sde, $sye);	# weekday of event
			    $code =  $sde % 7; if($code==0) { $code += 7;}	# the first wday
			    $nth =  ($sde-$code)/7;	# the nth week
			    for($i = 1; $i <= $repeat; $i++) {
				$k = 0;
				for $j (0 .. $elength) {
				    if( abs($exception->[$j]) == $i) { $k = 1; last;}
				}
				if($k == 0) {
				    $x= wday($sme, $sde, $sye);	# weekday of event
				    $sde += $wday -$x;	#to the correct weekday
				    if($sde <= 0) { $sde += 7;}
				    $code =  $sde % 7; if($code<=0) { $code = 7;}	# the first wday
				    $sde = $nth * 7 + $code;	# the nth wday
				    $check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				    if($check ==0) {
					my ($mxdays, $ok);
					$ok=1;
					if($sde > 28) {
					    if($sme != 1) { $mxdays = $::mdays[$sme];}
					    else { if(isleap($sye)) { $mxdays = 29;} else {$mxdays = 28;}}
					    if($sde > $mxdays) { $ok=0;}
					}
					if($ok) {
					    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
					    $table{$kk} = $des;
					    $dtable{$kk} = $detail;
					    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
					    if($srefs){$::oneDayEventRefs{$kk} = $href;}
					} elsif($check == 1) { last; }
				    }
				}
				my $nye;
				($nnm, $sde, $nye) = canDate($sme+$c1, $sde, $sye);
				if( ($nye-$sye)*12 + ($nnm - $sme) != $c1) { $i++;}
				$sme = $nnm; $sye = $nye;
				last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			    }
			} elsif($r eq 'MND') {                 # ==== 01/31/2003
			    ($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			    my ($mxdays, $ndb); $mxdays= ndays_in_month($sme, $sye);
			    $ndb = $mxdays - $sde;
			    for($i = 1; $i <= $repeat; $i++) {
				$k = 0;
				for $j (0 .. $elength) {
				    if( abs($exception->[$j]) == $i) { $k = 1; last;}
				}
				if($k == 0) {
				    $check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
				    if($check ==0) {
					$kk= "$sme/$sde/$sye/$etime/$kind/$key";
					$table{$kk} = $des;
					$dtable{$kk} = $detail;
					if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
					if($srefs){$::oneDayEventRefs{$kk} = $href;}
				    } elsif($check == 1) { last; }
				}
				($sme, $sde, $sye) = canDate($sme+$c1, 10, $sye);
				$sde = ndays_in_month($sme, $sye) - $ndb;
				last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			    }
			} elsif($r eq 'MNW') {  # ==== 01/31/2003
			    my ($nth, $nnm, $nwb, $mxdays, $offset, $fit);
			    ($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			    $wday = wday($sme, $sde, $sye);	# weekday of event
			    $mxdays = ndays_in_month($sme, $sye);
			    $nth =  1 + ($mxdays-$sde)/7;	# the nth weekday, counting backwards
			    for($i = 1; $i <= $repeat; $i++) {
				$k = 0;
				for $j (0 .. $elength) {
				    if( abs($exception->[$j]) == $i) { $k = 1; last;}
				}
				if($k == 0) {
				    $mxdays = ndays_in_month($sme, $sye);
				    $x= wday($sme, $mxdays, $sye);	
				    if($x > $wday) { $offset = ($wday - $x) + ($nth -1 )* 7;}
				    else { $offset = 7 + $x - $wday + ($nth -1) * 7;}
				    $sde = $mxdays - $offset; #to the correct weekday
				    if($sde <= 0) { $fit = 0;} else {$fit = 1;}
				    if($fit) {
					$check = dateInRange($sme, $sde, $sye, $sma, $sda, $sya, $smb, $sdb, $syb);
					if($check == 0) {
					    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
					    $table{$kk} = $des;
					    $dtable{$kk} = $detail;
					    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
					    if($srefs){$::oneDayEventRefs{$kk} = $href;}
					} elsif($check == 1) { last; }
				    }
				}
				my $nye;
				($nnm, $sde, $nye) = canDate($sme+$c1, 10, $sye);
				$sme = $nnm; $sye = $nye;
				last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			    }
			} elsif($r eq 'W') { # later
			    #print "Content-type: text/html\n\n";
			    my ($x, $y, $done, $err, $nbits, $adv, $jj);
			    $nbits = unpack "%8b*", pack("C", $c2);
			    $adv = ($c1 -1) * 7; 
			    ($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			    $wday = wday($sme, $sde, $sye);	# weekday of event
			    $done = 0;
			    for($i = 0; $i < $repeat; $i += $nbits, $wday=0) {
				$err=wday($sme, $sde, $sye);
				$jj=0;
				for($x=$wday; $x <7; $x++) {
				    if( ((1<<$err) & $c2) ) {
					$y= $i+$jj; $jj++;
					if($y < $repeat) {
					    $k = 0;
					    for $j (0 .. $elength) {
						if( abs($exception->[$j]) == $y) { $k = 1; last;}
					    }
					    if($k == 0) {
						$check=dateInRange($sme, $sde, $sye,
								   $sma, $sda, $sya, $smb, $sdb, $syb);
						if($check ==0) {
						    $kk= "$sme/$sde/$sye/$etime/$kind/$key";
						    $table{$kk} = $des;
						    $dtable{$kk} = $detail;
						    if($ls < 0 and $misc) { $mtable{$kk} = $misc; $roomtable{$kk} = $troom if $troom; $cattable{$kk} = $tcat if $tcat; $spkrtable{$kk} = $tspkr if $tspkr; }
						    if($srefs){$::oneDayEventRefs{$kk} = $href;}
						} elsif($check == 1) { $done = 1; last; }
					    }
					}
				    }
				    $err++;
				    ($sme, $sde, $sye)=canDate($sme, $sde+1, $sye);
				    if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY)) {$done=1;last;}
				}
				if($done) { last;}
				($sme, $sde, $sye)=canDate($sme, $sde+$adv, $sye);
				last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			    }
			}
		    }
		}
	    }
	}
    } else { calerror($::phr{'openFailed'},1);}

    #&make_style_sheet();   
    &headers($::phr{'Search_Results'},undef,undef,1,1);
if($ls >= 0) {
    my $header = "";
    if($::vm & 0x4) { # use the customized header 
        if($::calinfo{'hdr'}) { $header = customize_header(substImages($::calinfo{'hdr'}));}
    }
    print $header;

    print "<br><center><h1><font color=#666666>$::phr{'Search_Results'}</font></h1>\n";
    print "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$cdate$mg$::vmg\">
	   <font color=blue size=1>$::phr{'BackToCalendar'}</font></a></center>";
    print "<br><center><table border=0 cellpadding=2>";

    # search results is in table
    {
	my($clr, $counter, $tag, $tip, $tdetail, $owner);

	$counter = 1;
	@keys = sort sortDateTime (keys %table);
	for $key (@keys) {
	    ($mn,$dy, $yr, $tim, $kind, $tag, $owner)=split(/\//, $key);
            if(!defined $owner or ! $owner) { $owner =$who;}
	    ($hr, $nn) = split(/:/, $tim);
            $dy= "0$dy" if $dy < 10;  $mn= "0$mn" if $mn < 10;
	    $tim= "<code>".mdy_swstring($mn,$dy,$yr)." ".hm_string($hr,$nn)."</code>";
	    $des=$table{$key};
	    $tdetail=$dtable{$key};
	    if($tdetail) {
	      #$tdetail =~ s/\'/\\\'/g;
	      #$tdetail =~ s/\"/\\\'/g;
	      $tdetail = &substImages($tdetail);
	      #$tdetail =~ s/\n/&lt;br&gt;/g;
	      $tdetail =~ s/\n/<br>/g if ($tdetail =~ tr/\n/\n/) <20;
              my $tpid; 
	      if($tiptag) {
		  my $zz = $owner; $zz =~ s/[^A-Za-z0-9]//g;
		  $tpid = add4tip("$tag$zz", $tdetail);
	      } else { $tpid = add4tip($tag, $tdetail);}
	      $tip = " onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"";
	    } else {$tip="";}
	    $clr= $webcalConfig::r{'rowColors'}->[$counter]; $counter = ($counter==1? 2 : 1);
	    if($kind == 1) {
		print "<tr><td noWrap bgcolor=$clr><font color=$::o{'tclra'}><b>$tim</b>&nbsp;&nbsp;</font></td><td bgcolor=$clr>";
	    } elsif ($kind == 2) {
		print "<tr><td noWrap bgcolor=$clr><font color=$::o{'tclrt'}><b>$tim</b>&nbsp;&nbsp;</font></td><td bgcolor=$clr>";
	    } elsif ($kind == 3) {
		print "<tr><td noWrap bgcolor=$clr><font color=$::o{'tclrm'}><b>$tim</b>&nbsp;&nbsp;</font></td><td bgcolor=$clr>";
	    } else {	# special event, no time
	      my $nt =  "<code>".mdy_swstring($mn,$dy,$yr)."</code>";
	      print "<tr><td noWrap bgcolor=$clr><font color=$::o{'tclrs'}><b>$nt</b>&nbsp;&nbsp;</font></td><td bgcolor=$clr>";
	   }
	    print "<a href=\"$::o{'cginame'}?c=ed&w=$owner&t=$tag&k=$kind&d=$mn/$dy/$yr/$hr/$nn$mg\"$tip>$des</a></td></tr>\n";
	}
    }
    print "<tr><td colspan=2 align=center><br><a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$cdate$mg$::vmg\">
	   <font color=blue size=1>$::phr{'BackToCalendar'}</font></a></td></tr>";
    print "</center></table>";
} else { # special list view
    my ($header, $footer, $nav, $month, $day, $year, $savedname, $dstr, $tcolor, $odstr,$hcr);
    my ($counter, $m, $tag, $tdetail, $tim, $misc, $tip, $tiptag);
    my ($troom, $tspkr, $tcat);
    $tiptag=0; 	$savedname="";
    if($::d{'megaCal'} ne "") {
	my ($memb, @mlist, $sdate);	
	$month = $::calinfo{'month'};$day = $::calinfo{'day'}; $year = $::calinfo{'year'};
	$sdate="=$month/$day/$year";
	@mlist = split(',',$::d{'megaCal'});

	for $memb (@mlist) {
	    $memb =~ s/[ ]+//g;
	    $savedname .= "<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$memb&v=$view&d=$sdate$::vmg\">$memb</a>&nbsp; ";
	}
	$savedname =~ s/, $//g;
	$tiptag=1;
    } else {
	my $name = $::calinfo{'name'} || "";
	my $homepage = $::calinfo{'homepage'} || "";
	if($homepage) { $savedname = "<a href=\"$homepage\">$name</a>";}
	else {$savedname = "$name"; }
    }
    ($header, $footer, $hcr) = getHdrFtr($savedname);
    $nav = &navigationTable(0, $fm, $fd, $tm, $td);   
    if($::vm & 0x4) {
	print "<table $hcr border=0 cellpadding=0 cellspacing=2 width=\"$::o{'tw'}%\"><tr><td width=4%><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=20 height=30></td><td nowrap>$header</td></tr></table><br>";
    }
    print "<table border=0 cellpadding=0 cellspacing=2 width=\"$::o{'tw'}%\">";
    print "<tr><td width=4% rowspan=5000><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=20 height=8 border=0></td>
<td width=10%><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=40 height=1 border=0></td>
<td width=30%><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=140 height=1 border=0></td>
<td width=20%><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=80 height=1 border=0></td>
<td width=16%><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=70 height=1 border=0></td>
<td width=20% rowspan=1000 valign=top>$nav</td></tr>";

    print "<tr><td colspan=4><font color=#999999 size=6><i><b>$::phr{'Search_Results'}</b></i></font></td></tr>";	  
    $counter = 0;

    if($srefs) {
        print "<tr><td colspan=4 height=2><img src=\"$::o{'imgdirurl'}/blue.gif\" width=\"100%\" height=2 border=0></td></tr>";
	@keys = sort sortDateTime (keys %::oneDayEventRefs);
	for $key (@keys) {
	    ($mn,$dy, $yr, $tim, $kind, $tag, $owner)=split(/\//, $key);
	    my $eref = $::oneDayEventRefs{$key};
	    my $tmp = printEvent($eref, 2, 2, 1, "$mn/$dy/$yr");
	    print "<tr><td colspan=4 height=1><img src=\"$::o{'imgdirurl'}/blu.gif\" width=\"100%\" height=1 border=0></td></tr>";
	    print "<tr><td colspan=4 align=center>$tmp</td></tr>";
	    print "<tr><td colspan=4 align=center><br></td></tr>";
	    $counter += 5;
	}
    } else {
	$odstr="";
	@keys = sort sortDateTime (keys %table);
	for $key (@keys) {
	    ($mn,$dy, $yr, $tim, $kind, $tag, $owner)=split(/\//, $key);
	    if(!defined $owner or ! $owner) { $owner =$who;}
	    ($hr, $nn) = split(/:/, $tim);
	    $dstr= mdy_wstring($mn,$dy,$yr);
	    $tim = hm_string($hr,$nn);
	    $des=$table{$key};
	    $tdetail = $dtable{$key};
	    ($troom, $tspkr, $tcat)=("<br>","<br>","<br>");
	    if($roomtable{$key}) { $troom = $roomtable{$key};}
	    if($cattable{$key}) { $tcat = $cattable{$key};}
	    if($spkrtable{$key}) { $tspkr .= $spkrtable{$key};}
	    if($tdetail) {
		#$tdetail =~ s/\'/\\\'/g; 
		#$tdetail =~ s/\"/\\\'/g;
		$tdetail = &substImages($tdetail);
		#$tdetail =~ s/\n/&lt;br&gt;/g;
		$tdetail =~ s/\n/<br>/g if ($tdetail =~ tr/\n/\n/) <20;
		my $tpid;
		if($tiptag) {
		    my $zz = $owner; $zz =~ s/[^A-Za-z0-9]//g;
		    $tpid = add4tip("$tag$zz", $tdetail);
		} else { $tpid = add4tip($tag, $tdetail);}
		$tip = " onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"";
	    } else {$tip="";}
	    if($kind == 1) {
		$tcolor="$::o{'tclra'}";
	    } elsif ($kind == 2) {
		$tcolor="$::o{'tclrt'}";
	    } elsif ($kind == 3) {
		$tcolor="$::o{'tclrm'}";
	    } elsif ($kind == 4) {
		$tcolor="$::o{'tclrs'}";
		$tim = "$::phr{'AllDay'}";
	    }
	    if($odstr ne $dstr) {
		$odstr = $dstr;
		print "<tr><td colspan=4 height=2><img src=\"$::o{'imgdirurl'}/blue.gif\" width=\"100%\" height=2 border=0></td></tr>";
		print "<tr><td colspan=4 bgcolor=#eeeeff><font color=#666699><b>$dstr</b></font></td></tr>";
		print "<tr><td colspan=4 height=2><img src=\"$::o{'imgdirurl'}/blu.gif\" width=\"100%\" height=2 border=0></td></tr>";
		print "<tr><td><font color=#96969f size=1>$::phr{'Time'}</font></td><td><font color=#96969f size=1>$::phr{'Event'}</font></td><td><font color=#96969f size=1>$::phr{'Location'}</font></td><td><font color=#96969f size=1>$::phr{'Category'}</font></td></tr>";
	    }
	    print "<tr><td colspan=4 height=1><img src=\"$::o{'imgdirurl'}/blu.gif\" width=\"100%\" height=1 border=0></td></tr>";
	    my $tmp = "<a href=\"$::o{'cginame'}?c=ec&w=$owner&t=$tag&k=$kind&d=$mn/$dy/$yr/$hr/$nn$mg$::vmg\"$tip>$des</a>";
	    my $smp = "<a href=\"$::o{'cginame'}?c=m2&w=$owner&t=$tag&k=$kind&d=$mn/$dy/$yr/$hr/$nn$mg$::vmg\"><font color=$tcolor size=-1>$tim</font></a>";
	    print "<tr><td valign=top>$smp</td>
<td valign=top><font size=-1><b>$tmp</b></font><font size=-2>$tspkr</font></td>
<td valign=top><font size=-1>$troom</font></td>
<td valign=top><font size=-1>$tcat</font></td>
</tr>";
	    $counter++;
	}
    }
    print "<tr><td colspan=4 height=1><img src=\"$::o{'imgdirurl'}/blu.gif\" width=\"100%\" height=1 border=0></td></tr>";
    if($counter == 0) {
	print "<tr><td colspan=4><h1>$::phr{'NoEvents'}</h1></td></tr>";
	print "<tr><td colspan=4 height=1><img src=\"$::o{'imgdirurl'}/blue.gif\" width=\"100%\" height=1 border=0></td></tr>";
    }
    if($counter < 20) {   print "<tr><td><br></td></tr>" x (20 - $counter);}    
    print "</table>";
    print "<br>";
    print "<table border=0 cellspacing=0 width=\"$::o{'tw'}%\"><tr><td width=5%><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=20 height=30></td><td nowrap align=center>$footer</td></tr></table>";
}
    &trailer(1,0);
}
#==============================================================================================================


sub sortDateTime {
    my ($ay, $am, $ad, $ah, $an, $by, $bm, $bd, $bh, $bn, $atmp, $btmp, $tmp);
    ($am, $ad, $ay, $atmp ) = split(/\//,$a);
    ($bm, $bd, $by, $btmp ) = split(/\//,$b);
    if($ay > $by) { return 1;}
    elsif ($ay < $by) { return -1;}
    else {	#ay = by
	if( $am > $bm) { return 1;}
	elsif( $am < $bm) { return -1;}
	else {	#ay = by and am = bm
	    if( $ad > $bd) { return 1;}
	    elsif( $ad < $bd) { return -1;}
	    else {	#ay = by and am = bm and ad = bd
		($ah, $an ) = split(/:/,$atmp);
		($bh, $bn ) = split(/:/,$btmp);
                if(defined $ah and defined $bh) {
                    if($ah > $bh) { return 1;}
                    elsif ($ah < $bh) { return -1;}
                    else {
                        if(defined $an and defined $bn) {
                            if ($an > $bn) { return 1;}
                            elsif ($an < $bn) { return -1;}
                            else { return 0;}
                        } else { return 0;}
                    }
                } else { return 0;}
	    }
	}
    }
}
#=====================================================================================================
sub dowarn {
    my ($who, $warnname, @keys, $key, $des, $tim, $mn, $dy, $yr, $shr,$smn, $ehr, $emn,$kind,
	$counter, $clr, $tmp, $timeout);
    $who = $::calinfo{'w'};
    $warnname = "$::o{'spooldir'}/$who/warn";
    doReadFile($warnname);

    my $olm=$webcalConfig::r{'leftmargin'}; $webcalConfig::r{'leftmargin'}=0;
    my $omw=$webcalConfig::r{'marginwidth'};$webcalConfig::r{'marginwidth'}=0;
    &headers($::phr{'CalendarReminder'}," ",$webcalConfig::r{'refreshInterval'},0,undef,
	     "onload=\"javascript:setSnoozeTimer();normalwin()\"");
    $webcalConfig::r{'marginwidth'}=$omw; $webcalConfig::r{'leftmargin'}=$olm;
    print "<br><center><h3><b>$::phr{'CalendarReminder'}</b></h3></center><hr>";
    print "<center><table height=90 border=0 width=\"100%\"><tr><td align=center>";
    print "<table cellpadding=2 cellspacing=0>";
    $counter =0;
    $tmp = 30;
    @keys = sort sortDateTime (keys %::warnEvents);
    for $key (@keys) {
	($mn, $dy, $yr, $tim)=split(/\//, $key); $mn--;
	($shr, $smn, $ehr, $emn, $kind) = split(/:/, $tim);if($kind==4){$shr=~ s/^\(\d+\)//;}
	$tmp = (($ehr - $shr)*60 + ($emn - $smn))>>1;
	if($tmp <= 4 ){ $tmp = 5;}
	$tim= "<code>".mdy_swstring($mn,$dy,$yr)." ".hm_string($shr,$smn)."</code>";
	$des=$::warnEvents{$key};
	$clr= $webcalConfig::r{'rowColors'}->[$counter]; $counter = ($counter? 0 : 1);

	if($kind == 1) {
	    print "<tr><td noWrap bgcolor=$clr><font color=$::o{'tclra'}><b><span class=\"reminderT\">$tim</span></b>&nbsp;&nbsp;</font></td>
<td bgcolor=$clr><span class=\"reminderD\">$des</span></td></tr>";
	} elsif($kind == 2) {
	    print "<tr><td noWrap bgcolor=$clr><font color=$::o{'tclrt'}><b><span class=\"reminderT\">$tim</span></b>&nbsp;&nbsp;</font></td>
<td bgcolor=$clr><span class=\"reminderD\">$des</span></td></tr>";
	} elsif($kind == 3) {
	    print "<tr><td noWrap bgcolor=$clr><font color=$::o{'tclrm'}><b><span class=\"reminderT\">$tim</span></b>&nbsp;&nbsp;</font></td>
<td bgcolor=$clr><span class=\"reminderD\">$des</span></td></tr>";
	} else {
	    print "<tr><td noWrap bgcolor=$clr><font color=$::o{'tclrs'}><b><span class=\"reminderT\">$tim</span></b>&nbsp;&nbsp;</font></td>
<td bgcolor=$clr><span class=\"reminderD\">$des</span></td></tr>";
	  }
    }
    print "</table></td></tr></table><hr>\n";
    $timeout= $tmp *60000;	#ms

    my $snooze = int($tmp/2);
    print <<END;
<FORM name="timer"><table border=0 height=50 width="100%" cellpadding=0 cellspacing=0>
<tr bgcolor="#ccccff"><b>
<td colspan=2 align=center><b><input type=button class="fmBtn" onclick="javascript:self.close();"value=" $::phr{'Close'} ">
</b></td></tr>
<tr bgcolor="#ccffcc"><td align=left><font size=1 color="#cc00cc"><span class=\"fmLabelS\">auto close in
<input name=ti size=3 type=text class="fmEntry" value="$tmp" onFocus="Javascript:self.document.timer.ti.blur();"> minutes</span></font>
</td>
<td align=right>
<font color="#cc00cc" size=1><input type=button class="fmBtn" onclick="javascript:setsnooze();"value=" Snooze ">&nbsp; for &nbsp;
<input type=text name="snooze" size=3 value="$snooze" class="fmEntryS"><span class=\"fmLabelS\"> minutes </span></font>
</td></tr>
</table>
</FORM>
END
    ;
    print "</center>";
    &trailer(0,0);
}

#=====================================================================================================
sub greeting {
  my ($msg, $who, $name, $homepage);
  $msg= (@_)[0];

  &headers("WebCalendar",undef,undef,1);
  print "<center><font size=+1><span class=\"miscTitle\">$::phr{'WelcomeToWebCalendar'}</span></font><br>";
  if($msg !~ /anonymous/) {
    print "<font color=#ff0000><span class=\"warnMsg\">$msg<b></span><br>\n";
  }

  my ($count, @cals);
  $count = 0;
  if($::o{'listAllCals'}) {
    @cals = &listcals;
    $count = @cals;
  }
  print <<END;
<table border=0 width="70%" cellspacing=2 cellpadding=2>
<tr><td width="100%" align=left colspan=2 bgcolor="#eeeeff"><span class="greetingInstruction">$::phr{'olduserInstruction'}</span></td></tr></table><br>
END
  print "<table border=0 cellpadding=0 cellspacing=0 width=\"70%\">";
  print "<tr><td align=center nowrap>";
  print "<Form action=\"$::o{'cginame'}\" method=POST>$::vmp";
  print "<input type=hidden name=c value=\"plogin\"><font color=#666600><input type=submit class=\"fmBtnS\" value=\"$::phr{'login'}\"></span></font></form>";
  print "<Form name=webcal action=\"$::o{'cginame'}\" method=GET><input type=hidden name=c value=\"get\">";

  if($count > 0) {
      print "<span class=\"greetingInstruction\">$::phr{'ViewOnly'}:&nbsp; </span>";
      print  select_option("w","",@cals); 
  } else {      
      print "<a href=\"javascript:openpopup('$::o{'cginame'}?c=getcal',\'calendars\',500,400)\"><span class=\"greetingInstruction\">$::phr{'ViewOnly'}:</span></a>";
      print "<input type=text size=10 maxlength=64 name=w value=\"\" class=\"fmEntry\">";
  }
  print "&nbsp;<input type=submit class=\"fmBtnSt\" name=action value=\"Go\"></form>";
  print "</td></tr></table>";

  my $scgi="$::o{'signupurl'}?c=signup";
  print <<END;
<table border=0 width="70%" cellspacing=2 cellpadding=2>
<tr><td width="100%" align=left colspan=2 bgcolor="#eeeeff"><span class="greetingInstruction">$::phr{'newuserInstruction'}</span></td></tr>
<tr><td align=center><a href="$scgi"><span class="greetingInstruction"><b>$::phr{'signup'}</b></span></a></td></tr>
</table>
</center>
END
  &trailer(0,0);
}
#=====================================================================================================
#
sub doauth {
  my($who, $tmp, $editor, @editors, $nchunks, $i, $j, $salt, $wlen, $encrypted, $smp, $ee);
  $who = $::calinfo{'w'};
  $::d{'ceditor'} = "";
  if(isadmin($::d{'remote_user'})) {return 4;} elsif(isvgadmin($::d{'remote_user'}, $who)) { return 4;}
  elsif ($::d{'remote_user'}) {
    if ($who eq $::d{'remote_user'}) { $::d{'ceditor'}=$who; return 4; }
    elsif(defined $::calinfo{'editors'}) {
      $tmp = $::calinfo{'editors'};
      $tmp =~ s/[,; ]+/:/g;
      (@editors)=split(/:/, $tmp);
      for $editor (@editors) {
        if($::d{'remote_user'} eq $editor) { $::d{'ceditor'} = $editor; return 4;}
      }
    }
  }
  return 0;
}
#=====================================================================================================
sub download {
    my ($who, $calname,$fname, $data, $vcal);
    if($::d{'authResult'} != 4 and $::d{'ispublic'} == 0) {calerror("$::phr{'notAllowedToDownload'} $::d{'authResult'}");}
    $who = $::calinfo{'w'};
    if($::calinfo{'cft'} eq 'vcal') { $vcal = 1;} else { $vcal = 0;}
    $calname = "$::o{'spooldir'}/$who";
    if(defined $::calinfo{'database'}) { $data = $::calinfo{'database'};} else { $data = "data";}
    if($data =~/cache\/(.+)/) {
	$data = "cache/" . untaintname($1,$::phr{'Invalidcalendarname'});
    } else {
	$data = untaintname($data,$::phr{'Invalidcalendarname'});
    }
    if($vcal == 0) {
        print "Content-Type: application/octet-stream\n\n";
	$fname="$calname/$data";
	my $fhu = gensym; 
	if (open($fhu, "<$fname") ) {
	    &webcalLock::doflock( \*$fhu, LOCK_SH,"$fname") or calerror("Cannot lock file '$fname': $!\n",1);
	    while (<$fhu>) { print;}
	    &webcalLock::doflock( \*$fhu, LOCK_UN,"$fname") or calerror("Cannot unlock file '$fname': $!\n",1);
	    close $fhu;
	} else {
	    print "No data available ...";
	}
    } else {
        print "Content-Type: text/x-vCalendar\n\n";
	@::caldata=(); @::mdata=(); @::wdata=(); @::ddata=();
	$fname="$calname/$data";
	doReadFile("$fname");
	print "BEGIN:VCALENDAR\015\012PRODID:-//WebCalendar $webCalVersion-$patchlevel//EN\015\012VERSION:1.0\015\012";
	my $href;
	for $href (@::caldata) { my $t = toVcal($href, $who, 3); print $t, "\015\012";}
	for $href (@::mdata) { my $t = toVcal($href, $who, 3); print $t, "\015\012";}
	for $href (@::wdata) { my $t = toVcal($href, $who, 3); print $t, "\015\012";}
	for $href (@::ddata) { my $t = toVcal($href, $who, 3); print $t, "\015\012";}
	print "END:VCALENDAR\015\012";	
    }
    myexit(0);
}
#=====================================================================================================
sub dologout {
  my ($tmp, @names);

  &headers("WebCalendar $::phr{'Logout'}",undef,undef,1);
  print "<br><center><h1><span class=\"miscTitle\">WebCalendar $::phr{'Logout'}</span></h1></center><br>";

  if($webcalConfig::r{'limitGet'} == 0) {
    print "<center><span class=\"authWarn\">$::phr{'AuthNotRequired'}</span><br></center>";
  }
  $::vm=0; $::vmp=$::vmg=$::vmc="";
  if($::d{'remote_user'} ne 'nobody' and $::d{'remote_user'} ne 'anonymous')  {
    print "
 <Form action=\"$::o{'cginame'}\" method=POST>
 <center><table border=0 cellpadding=0 cellspacing=0 width=\"80%\"><tr><td width=\"$::o{'tw'}%\" align=center>
<font color=#ff0000><span class=\"warnMsg\">
$::phr{'logoutInstruction'}<br></span>
    <input type=hidden name=c value=\"signoff\">
    <input type=submit name=action value=\"$::phr{'Logout'}\" class=\"fmBtnSt\">
</font>
</td></tr></table></center></Form>";
  } else {
    print "
<Form action=\"$::o{'cginame'}\" method=POST>
<center><table border=0 cellpadding=0 cellspacing=0 width=\"80%\"><tr><td width=\"$::o{'tw'}%\" align=center>
<h2>$::phr{'You_ve_logout'}.</h2>
<span class=\"greetingInstruction\">$::phr{'loginInstruction'}</span>
<input type=hidden name=c value=\"plogin\">$::vmp
<font color=#ff0000><input type=submit name=action value=\"$::phr{'login'}\" class=\"fmBtn\"></font>
</td></tr></table></center></Form>";
  }
  &trailer(0,0);
  myexit(0);
}

sub signoff {
    print "Status: 401 auth req\n";
    print "WWW-authenticate: Basic realm=\"Calendar\"\n";
    print "Content-type: text/plain\n\n";
    print "$::phr{'access_denied'}";
    myexit(0);
}

sub compare {
  my ($who, $view, @lcals, $count, $sdate, $m,$d, $y, $rest, $udate, $ls);
  my ($i, $shr, $ehr);
  $view=$::calinfo{'v'};
  $ls = $::calinfo{'ls'};
  $who=$::calinfo{'w'};
  $sdate=$::calinfo{'d'};
  ($m,$d, $y, $rest) = split(/\//, $sdate);
  $m++;
  $sdate="$m/$d/$y";
  $m--;
  $udate = to_native_date($sdate);

  &headers($::phr{'CompareCalendars'}," ",undef,1);
  print "<Form name=webcal action=\"$::o{'cginame'}\" method=GET>$::vmp
<input type=hidden name=c value=docompare>
<input type=hidden name=w value=\"$who\">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=cmp value=1>
<center>
<br><font size=+1><b><span class=\"miscTitle\">$::phr{'CompareCalendars'}</span></b></font><br>";
  $shr = $::calinfo{'hourB'};
  $ehr = $::calinfo{'hourE'};

  print "<table border=3 cellpadding=2 cellspacing=2 width=\"70%\">
<tr><td align=right><b><span class=\"fmLabel\">$::phr{'Date'}:</span></b></td>
<td align=left><input type=text size=16 maxlength=16 name=sdate value=\"$udate\" class=\"fmEntry\">",
  linkSmallCal("webcal.sdate",$who,$m,$y),"</td></tr>\n";

  print "<tr><td align=right><b><span class=\"fmLabel\">$::phr{'Time'}:</span></b></td>
  <td noWrap align=left><span class=\"fmLabel\">$::phr{'Start'}:&nbsp;</span>",select_time("s",$shr,-1);
  print "<span class=\"fmLabel\">&nbsp;&nbsp;&nbsp;$::phr{'End'}:&nbsp;</span>",select_time("e",$ehr,-1);
  print "</td></tr>\n";

  $::calinfo{'_clist_'} = 1;
  my ($textfield,$selectfield) = select_multicals("mattendants",$who);
  delete $::calinfo{'_clist_'};  
  my @slist = get_mgroups($who);
  my $hasmeetgroup = scalar @slist;
  print "<tr><td align=right><b><span class=\"fmLabel\">$::phr{'Enter_calendar_names'}:</span></b>";
  print "<br><font size=-1 color=#cc00cc><span class=\"fmLabelS\">&nbsp;$::phr{'or_meeting_group'}:</span></font>" if ($hasmeetgroup);
  print "</td><td align=left>$textfield";

  if ($hasmeetgroup) {
      unshift @slist,"$::phr{'none'}";
      print "<br>",select_option("smtgp",undef,@slist);
  }
  print "</td></tr>\n";
  if($::o{'listAllCals'}) {
      print "<tr><td><br></td><td>",
      "<table border=0 cellspacing=0 cellpadding=0><tr><td valign=top>", $selectfield, "&nbsp;&nbsp;</td><td>",
      "<blockquote class=\"fmMsg\">", $::phr{'SelectAttendee'}, "</blockquote>",
      "</td></tr></table>",
      "</td></tr>";
  }
  print "<tr><td bgcolor=$webcalConfig::r{'dkbackground'} colspan=2 noWrap align=center><span class=\"fmLabel\"> $::phr{'View'}:&nbsp;</span>";
  print "<input type=radio class=\"fmRadio\" name=cfd value=0 checked><span class=\"fmLabel\">&nbsp;$::phr{'Freebusytable'}&nbsp;&nbsp;</span>";
  print "<input type=radio class=\"fmRadio\" name=cfd value=1><span class=\"fmLabel\">&nbsp;$::phr{'CombinedView'}&nbsp;&nbsp;</span>";
  print "<input type=radio class=\"fmRadio\" name=cfd value=2><span class=\"fmLabel\">&nbsp;$::phr{'DetailedView'} &nbsp;&nbsp;</span>";
  print "<font color=#ff0000><input type=submit class=\"fmBtnSt\" name=action value=\"$::phr{'FindConflict'}\"></font></td></tr>";
  print "<tr><td bgcolor=$webcalConfig::r{'dkbackground'} colspan=2 noWrap align=center>
<span class=\"fmLabel\">$::phr{'View'}:&nbsp;</span>",select_value("v",$view,@::viewList),
select_value("ls",$ls,@::lsList)," <span class=\"fmLabel\">$::phr{'Events'}:&nbsp;</span>",
select_value("ke",0,@::eventList),
"<br><font color=#ff0000><input type=submit  class=\"fmBtnSt\" name=action value=\"$::phr{'ShowCombinedCalendar'}\"><input type=submit name=action class=\"fmBtnSt\" value=\"$::phr{'Cancel'}\"></font>
</td></tr>
</table></center>
</form>";
  &trailer(0,0);
}
#=====================================================================================================
sub getMegaCalendarData {
  my $ls =$::calinfo{'ls'};
  my $getall = (($::d{'getall'}) or 
		(($::calinfo{'v'} == 1) and (! $ls) and 
		 ( ($::vm & 0x10000) or (!($::vm & 0x70000) and (($::calinfo{'dayview'} || 0) &0x10000)))));
  my ($iwho, $admin, $etmp, $tmp, $others, $view, $iname, $cname, $counter, %marks, @members, $mem, $ievent, $privacy);
  my ($whoami, $editor, $reader, %emarks);
  $whoami = $::d{'remote_user'};
  $iwho = $::calinfo{'w'};
  if(defined $::calinfo{'smtgp'}) {$etmp = $::calinfo{'smtgp'};} else {$etmp="";}
  if(defined $::calinfo{'mattendants'}) { $tmp = $::calinfo{'mattendants'};} else {$tmp="";}
  if($etmp && $etmp ne "$::phr{'none'}") {
    $_=$tmp;
    if( ! /\b$etmp\b/) {
      $tmp .= ":$etmp";
    }
  }
  $tmp =~ s/[,; ]+/:/g;
  $tmp =~ s/:$//g;
  $others = expandMeetingGroups($iwho,$tmp,1);
  if(!$others) { $others = $iwho;}
  (@members) = split(/:/, $others);

  %marks = (); %emarks=();
  $counter = 1;
  @::caldata=();
  if(defined $::calinfo{'ke'}) {$ievent = $::calinfo{'ke'};} else {$ievent = 0;}
  $admin = isadmin($whoami);
  for $mem (sort @members) {
    $mem = untaintname($mem,$::phr{'Invalidusername'});
    $cname="$::o{'spooldir'}/$mem/data";
    if( $mem and !exists $marks{$mem} and -f $cname) {
      my($href, $key, $role, $flag, $matched, $ee, @save);
      my $ispublic;  { my $tmp=getinfo($mem, 'ctype'); if($tmp and $tmp =~ 'public'){$ispublic=1;}};
      $::d{'megaCal'} = $::d{'megaCal'} . "$mem,";
      $marks{$mem} = $counter;
      $editor = $admin || isvgadmin($whoami,$mem);
      if(!$editor) {
	if($whoami eq $mem) {$editor = 1;}
	else { $editor = isre($whoami, $mem, 'editors');}
      }
      $reader=$editor? $editor : isre($whoami, $mem, 'readers');

      (@save) = (@::caldata);
      @::caldata=();
      doReadFile($cname);
      foreach $href (@::caldata) {
	next if $href->{'pnd'}; 
        if($editor or $reader or !exists($href->{'privacy'})) {$privacy = 3;}
	elsif($ispublic) { $privacy = 3; delete $href->{'privacy'} if $href->{'privacy'};}
	else { $privacy = $::privacyTable{$href->{'privacy'}} - 1;}

	if($privacy and ($ievent == 0 || $href->{'kind'} == $ievent)) {
          $href->{'w'} = $mem;
          if($reader) {$href->{'e'} = 1;}; if(! $href->{'what'}) { $href->{'what'} = "";}
	  my $ok=1; my $clr="#0000Ff"; my $ncor=1; my $people="";
	  if($getall) { push(@save, $href);}
	  else {
              if($href->{'mkey'}) { 
                  my $mk=$href->{'mkey'};
                  if(not $emarks{$mk}) { 
                      $emarks{$mk} = $href;
		      if($href->{'attendants'}) { 
			  $href->{'p'} = "$mem"; #$clr="#990000"; 
			  $people="<img src=\"$::o{'imgdirurl'}/pp.gif\" width=10 height=9 border=0>";
		      }
                      push(@save, $href);
                  } else {
                      my $ref = $emarks{$mk}; if($ref->{'attendants'}) {$ref->{'p'} .= ", $mem";}
		      $ok=0;
                  }
              } elsif($href->{'seq'} =~ /C/) {
                  my $seq=$href->{'seq'};
                  if(not $emarks{$seq}) { $emarks{$seq} = $href; push(@save, $href); $ncor=0;}
              } else { push(@save, $href);}
	  } 
	  if($ok) {
	      if($privacy > 1) {$href->{'what'} = "<FoNt CoLoR=$clr>$mem:</FoNt>$people " . $href->{'what'} if $ncor;}
	      else {$href->{'what'} = "<FoNt CoLoR=#0000Ff>$mem:</FoNt> $::phr{'Protected'}"; } # this is needed or search will find them
	      if($privacy < 3) {$href->{'detail'}=""; }
	      if(! $href->{'bg'}){ $href->{'bg'}  = $webcalConfig::r{'usrColors'}->[$counter];}
	  }
        }
      }
      $counter++; if($counter > 15) { $counter = 1;}
      (@::caldata) = (@save);
      }
    }
    $::d{'megaCal'} =~ s/,$//;
}
#=====================================================================================================
sub docompare {
  my ($action, $cmd); 
  if(defined $::calinfo{'action'}) {$action = $::calinfo{'action'};} else {$action="";}
  if($action eq "$::phr{'FindConflict'}" or $action eq 'cft') { $::d{'getall'} = 1; &findConflict('ctd'); }
  elsif ($action ne "$::phr{'Cancel'}") {	# find and display a combined mega calendar
      $cmd = (@_)[0];
      &getMegaCalendarData;
      my ($date, $month, $day, $year, $rest);
      if(defined $::calinfo{'sdate'}) {
	  $date = $::calinfo{'sdate'};
	  ($month, $day, $year, $rest) = split(/\//, $date); 
	  if(! $month or ! $day or ! $year) { calerror( "$::phr{'invalid_date'}: $date",1);}
	  $month -=1;  ($month, $day, $year)= canDate($month, $day, $year);
	  $::calinfo{'sdate'}="$month/$day/$year";
	  $::calinfo{'d'}="$month/$day/$year/7/0";
	  ($::calinfo{'month'}, $::calinfo{'day'}, $::calinfo{'year'}) =($month, $day, $year); 
      }
      if($cmd eq 'e') { my ($extra, $invitee) = getEditorState(); $::d{'editorState'} = $extra . $invitee; }
      &calendar;
  } else { &readData; &calendar; }
  myexit(0);
}
#===============================================================================================
sub whichWeekday { # return the nth weekday
    use integer;
    my ($mn, $dy, $yr) = (@_);
    my $wday = wday($mn, $dy, $yr);	# weekday of event
    my $fwday = wday($mn, 1, $yr);
    my $nth = ($dy + $fwday -$wday -1)/7;
    $nth++ if $fwday <= $wday;
    return($wday, $nth);
}
sub findnthWeekday { # return
    my ($wday, $nth, $mn, $yr) = (@_);
    my $fwday = wday($mn, 1, $yr); # weekday of the first day of the month
    #if($fwday == 0) { $fwday = 7;}
    if($fwday <= $wday) {$nth--;}
    my $d = ($wday - $fwday) + 1 + 7 * $nth;
    if($d > 28) {
        if($mn == 1) {if( $d > 29 or !isleap($yr)) {$d =0;}} 
	elsif($d > 31) { $d=0;}
        elsif($d == 31 and ($mn == 3 or $mn == 5 or $mn == 8 or $mn == 10)) {$d = 0;}
    }
    return($d);
}
#===============================================================================================
sub getAllDates {
    my ($mn, $dy, $yr, $occurs, $repeat) =(@_);
    my @ans=();
    my ($tmp, $i, $m, $d, $y, $j);

    if($repeat == 0 or !$occurs or $occurs eq 'OneTime') { $mn++; $tmp="$mn/$dy/$yr"; push(@ans, $tmp);}
    else {
        if($repeat == 0) { $repeat = 1;}

        if($occurs eq "Daily") {
            for($i=0; $i < $repeat; $i++) {
                ($m, $d, $y)=canDate($mn, $dy+$i, $yr);
                $m++;
                $tmp="$m/$d/$y";
                push(@ans, $tmp);
            }
        } elsif($occurs eq "Weekly") {
            $j = 0;
            for($i=0; $i < $repeat; $i++, $j += 7) {
                ($m, $d, $y)=canDate($mn, $dy+$j, $yr);
                $m++;
                $tmp="$m/$d/$y";
                push(@ans, $tmp);
            }
        } elsif ($occurs eq "Every2Weeks") {
            $j = 0;
            for($i=0; $i < $repeat; $i++, $j += 14) {
                ($m, $d, $y)=canDate($mn, $dy+$j, $yr);
                $m++;
                $tmp="$m/$d/$y";
                push(@ans, $tmp);
            }
        } elsif ($occurs eq "MonthlyByDate") {
            for($i=0; $i < $repeat; $i++) {
                ($m, $d, $y)=canDate($mn+$i, $dy, $yr);
                if($m == ($mn+$i)%12) {
                    my $ok = 1;
                    if($dy > 28) {
                        if($m == 1) {if( $dy > 29 or !isleap($yr)) {$ok =0;}} 
                        elsif($dy == 31 and ($m == 3 or $m == 5 or $m == 8 or $m == 10)) {$ok = 0;}
                    }
                    if($ok) {
                        $m++;
                        $tmp="$m/$d/$y";
                        push(@ans, $tmp);
                    } else {
                        push(@ans, "0/0/0");			
		    }
                } else { push(@ans, "0/0/0");}
            }
        } elsif( $occurs eq "MonthlyByWeekday") {
            my ($twd, $nth) = whichWeekday($mn, $dy, $yr);
            for($i=0; $i < $repeat; $i++) {
                ($m, $d, $y)=canDate($mn+$i, $dy, $yr);
		my $ok=0;
                if($m == ($mn + $i)%12) {
                    my $nd = findnthWeekday($twd, $nth, $m, $y);
                    if($nd > 0) {
                        $m++;
                        $tmp="$m/$nd/$y";
                        push(@ans, $tmp);
			$ok=1;
                    }            
                }
		if($ok == 0) { push(@ans, "0/0/0");}
            }
        } elsif ($occurs eq "MTWThF") {
	    my($x, $z, $wday, $kk);
	    ($m, $d, $y) = ($mn, $dy, $yr);
	    $wday= wday($m, $d, $y);
	    my $aref = $::occurenceHash{$occurs};
	    my $eoffset = $aref->[3+$wday];
	    for($i=1; $i< $eoffset; $i++) { push @ans, "0/0/0";}
	    for($i = 0; $i < $repeat; $i += 5, $wday=0) {
		for($x=$wday; $x <7; $x++) {
		    my $wd=wday($m, $d, $y);
		    $kk=0;
		    if( $wd >= 1 and $wd <= 5) {
			$z = $i + $kk; $kk++;
			if($z < $repeat) {
			    my $tmm = $m + 1;
			    $tmp="$tmm/$d/$y";
			    push(@ans, $tmp);
			}
		    }
		    ($m, $d, $y)=canDate($m, $d+1, $y);
		}
	    }
        } elsif ($occurs eq "MWF") {
	    my($x, $z, $wday, $kk);
	    ($m, $d, $y) = ($mn, $dy, $yr);
	    $wday= wday($m, $d, $y);
	    my $aref = $::occurenceHash{$occurs};
	    my $eoffset = $aref->[3+$wday];
	    for($i=1; $i< $eoffset; $i++) { push @ans, "0/0/0";}
            for($i=0; $i < $repeat; $i += 3, $wday=0) {
		$kk=0;
		for($x=$wday; $x <7; $x++) {
		    my $wd=wday($m, $d, $y);
		    if( $wd & 1) {
			$z = $i + $kk; $kk++;
			if($z < $repeat) {
			    my $tmm = $m + 1;
			    $tmp="$tmm/$d/$y";
			    push(@ans, $tmp);
			}
		    }
		    ($m, $d, $y)=canDate($m, $d+1, $y);
                }
            }
        } elsif ($occurs eq "TTh") {
	    my($x, $z, $wday, $kk);
	    ($m, $d, $y) = ($mn, $dy, $yr);
	    $wday= wday($m, $d, $y);
	    my $aref = $::occurenceHash{$occurs};
	    my $eoffset = $aref->[3+$wday];
	    for($i=1; $i< $eoffset; $i++) { push @ans, "0/0/0";}
            for($i=0; $i < $repeat; $i += 2, $wday=0) {
		$kk=0;
		for($x=$wday; $x <7; $x++) {
		    my $wd=wday($m, $d, $y);
		    if( $wd == 2 or $wd == 4) {
			$z = $i + $kk; $kk++;
			if($z < $repeat) {
			    my $tmm = $m + 1;
			    $tmp="$tmm/$d/$y";
			    push(@ans, $tmp);
			}
		    }
		    ($m, $d, $y)=canDate($m, $d+1, $y);
                }
            }
        } elsif ($occurs eq "Yearly") {
            for($i=0; $i < $repeat; $i++) {
                ($m, $d, $y)=canDate($mn, $dy, $yr+$i);
		my $done = 0;
                if($m == $mn) {
                    my $ok = 1;
                    if($m == 1 and ($d > 29 or ($d == 29 and !isleap($y)))) {$ok = 0;}
                    if($ok) {
                        $m++;
                        $tmp="$m/$d/$y";
                        push(@ans, $tmp);
			$done = 1;
                    }
                }
		if($done == 0) { push @ans, "0/0/0";}
            }            
        } elsif( $occurs eq "YearlyByMonthWeekday" ) {
            my ($twd, $nth) = whichWeekday($mn, $dy, $yr);
            $m = $mn+1;
            for($i=0; $i < $repeat; $i++) { 
                $y= $yr+$i;
                my $nd = findnthWeekday($twd, $nth,$mn,$y);
                if($nd > 0) {
                    $tmp="$m/$nd/$y";
                    push(@ans, $tmp);  
                } else { push @ans, "0/0/0";}                 
            }
        } elsif($occurs eq "EveryOtherDay") {
            $j=0;
            for($i=0; $i < $repeat; $i++, $j+=2) {
                ($m, $d, $y)=canDate($mn, $dy+$j, $yr);
                $m++;
                $tmp="$m/$d/$y";
                push(@ans, $tmp);
            }            
        } elsif($occurs eq "Every3rdDay") {
            $j=0;
            for($i=0; $i < $repeat; $i++, $j+=3) {
                ($m, $d, $y)=canDate($mn, $dy+$j, $yr);
                $m++;
                $tmp="$m/$d/$y";
                push(@ans, $tmp);
            }            
        } elsif($occurs eq "Every4thDay") {
            $j=0;
            for($i=0; $i < $repeat; $i++, $j+=4) {
                ($m, $d, $y)=canDate($mn, $dy+$j, $yr);
                $m++;
                $tmp="$m/$d/$y";
                push(@ans, $tmp);
            }            
        } elsif($occurs eq "Every5thDay") {
            $j=0;
            for($i=0; $i < $repeat; $i++, $j+=5) {
                ($m, $d, $y)=canDate($mn, $dy+$j, $yr);
                $m++;
                $tmp="$m/$d/$y";
                push(@ans, $tmp);
            }            
        } elsif($occurs eq "Every6thDay") {
            $j=0;
            for($i=0; $i < $repeat; $i++, $j+=6) {
                ($m, $d, $y)=canDate($mn, $dy+$j, $yr);
                $m++;
                $tmp="$m/$d/$y";
                push(@ans, $tmp);
            }            
	} elsif(substr($occurs,0,1) eq 'Z' and $occurs =~ /^Z(.+),(\d+),(\d*)/) {
	    my ($word, $c1, $c2) = ($1, $2, $3);
	    if($word eq 'D') { 
		$j=0;
		for($i=0; $i < $repeat; $i++, $j+= $c1) {
		    ($m, $d, $y)=canDate($mn, $dy+$j, $yr);
		    $m++;
		    $tmp="$m/$d/$y";
		    push(@ans, $tmp);
		}
	    } elsif($word eq 'MD') {
		for($i=0; $i < $repeat; $i++) {
		    ($m, $d, $y)=canDate($mn+$i * $c1, $dy, $yr);
		    my $done = 0;
		    if($m == ($mn+$i * $c1)%12) {
			my $ok = 1;
			if($dy > 28) {
			    if($m == 1) {if( $dy > 29 or !isleap($yr)) {$ok =0;}} 
			    elsif($dy == 31 and ($m == 3 or $m == 5 or $m == 8 or $m == 10)) {$ok = 0;}
			}
			if($ok) {
			    $m++;
			    $tmp="$m/$d/$y";
			    push(@ans, $tmp);
			    $done = 1;
			}
		    }
		    if($done == 0) { push @ans, "0/0/0";}
		}
	    } elsif($word eq 'MWD') {
		my ($twd, $nth) = whichWeekday($mn, $dy, $yr);
		for($i=0; $i < $repeat; $i++) {
		    ($m, $d, $y)=canDate($mn+$i * $c1, $dy, $yr);
		    my $done = 0;
		    if($m == ($mn + $i*$c1)%12) {
			my $nd = findnthWeekday($twd, $nth, $m, $y);
			if($nd > 0) {
			    $m++;
			    $tmp="$m/$nd/$y";
			    push(@ans, $tmp);
			    $done = 1;
			}            
		    }
		    if($done == 0) { push @ans, "0/0/0";}
		}
	    } elsif($word eq 'MND') { # ====== 01/31/2003
		my ($mxdays, $ndb); $mxdays = ndays_in_month($mn, $yr);
		$ndb = $mxdays - $dy;
		for($i=0; $i < $repeat; $i++) {
		    ($m, $d, $y)=canDate($mn+$i * $c1, 10, $yr);
		    $d = ndays_in_month($m, $y) - $ndb;
		    if($d > 0) {
			$m++;
			$tmp="$m/$d/$y";
			push(@ans, $tmp);
		    } else { push @ans, "0/0/0";}
		}
	    } elsif($word eq 'MNW') {  # ====== 01/31/2003
		my ($twd, $nth, $mxdays, $x, $offset);
		$twd = wday($mn, $dy, $yr);	# weekday of event
		$mxdays = ndays_in_month($mn, $yr);
		$nth =  1 + ($mxdays-$dy)/7;	# the nth weekday, counting backwards
		for($i=0; $i < $repeat; $i++) {
		    ($m, $d, $y)=canDate($mn+$i * $c1, 10, $yr);
		    $mxdays = ndays_in_month($m, $y);
		    $x= wday($m, $mxdays, $y);	
		    if($x > $twd) { $offset = ($twd - $x) + ($nth -1 )* 7;}
		    else { $offset = 7 + $x - $twd + ($nth -1) * 7;}		    
		    $d = $mxdays - $offset; #to the correct weekday		    
		    if($d > 0) {
			$m++;
			$tmp="$m/$d/$y";
			push(@ans, $tmp);
		    } else {push @ans, "0/0/0";}
		}
	    } elsif($word eq 'W') {
		my ($nbits, $adv, $wday, $x, $z, $err, $kk, @maskary);
		@maskary = wdayoffsets($c2); $nbits = $maskary[9];
		$adv = ($c1 -1) * 7;
		$wday =wday($mn, $dy, $yr);
		my $eoffset = $maskary[3+$wday];
		for($i=1; $i<$eoffset; $i++) { push @ans, "0/0/0";}
		($m, $d, $y) = ($mn, $dy, $yr);
		for($i=0; $i < $repeat; $i += $nbits, $wday=0) {
		    $err=wday($m, $d, $y);
		    $kk = 0;
		    for($x=$wday; $x <7; $x++) {
			if( (1<<$err) & $c2 ) {
			    $z = $i+$kk; $kk++;
			    if($z < $repeat) {
				my $mm = $m+1;
				$tmp="$mm/$d/$y";
				push(@ans, $tmp);
			    }
			}
			$err += 1;
			($m, $d, $y)=canDate($m, $d+1, $y);
		    }
		    ($m, $d, $y)=canDate($m, $d+$adv, $y);		    
                }
	    } elsif($word eq 'X') {
		($m, $d, $y)=($mn,$dy,$yr);		
		my $nwks = int($c1/5);  my $mod = $c1%5;
		my $ndays = $nwks * 7 + $mod;
		for($i=0; $i < $repeat; $i++) {
		    $m++; $tmp = "$m/$d/$y"; push(@ans, $tmp); $m--;
		    my $start =wday($m, $d, $y); 
		    $start += $mod;
		    if($start > 5) { $tmp = 2; $start -= 5;} else { $tmp = 0;}
		    ($m, $d, $y)=canDate($m,$d+$ndays+$tmp,$y);				    
		}
	    }
	} else { $mn++; $tmp="$mn/$dy/$yr"; push(@ans, $tmp);}
    }
    return(@ans);    
}
#===============================================================================================
sub checkOverlap {
  use integer;
  my ($mem, $date,@tmem, %hh, @members, $month, $imonth, $day,$year,$hour,$min, $who, $cname, $iname, $interval, $atten, $ls, $mk);
  my (@save, $rest, $count, $out, $i, $j, $k, $cal, @keys, $key, $tmp, $hr, $mn, $ehr, $emn, $tim, $kind, $tag, $view, $mkey,
      $repeat, $occurs);
  my ($tstart, $tend,  $aol, %pcals, $dock, $title, $txtmsg);
  ($date, $atten, $mk, $dock, $title) = (@_);
  @members=();   %hh = ();
  $who = $::calinfo{'w'};
  $count = 1; $aol=0; %pcals = ();

  if($atten) {
      $atten =~ s/[,; ]+/:/g;
      $atten =~ s/:$//g;
      $atten = expandMeetingGroups($mk,$atten);
      (@tmem) = split(/:/, $atten);
      for $mem (@tmem) {
	  next if $mem eq $who;
	  if( !exists $hh{$mem}) {
	      push @members, $mem;
	      $hh{$mem} = 1;
	      $count++;
	  }
      }
  }
  %hh = ();
  if(!$dock) { foreach $mem (@members) {  $tmp = getinfo($mem, 'ol'); if($tmp and $tmp > 1) { $dock = -1; last;}} }
  if(!$dock) { return "";}

  push @members, $who;  
  
  $view = $::calinfo{'v'};
  $ls = $::calinfo{'ls'};

  ($month, $day, $year,$rest, $occurs, $repeat) = split(/\//, $date);
  $imonth= $month - 1;
  my (@alldates) = getAllDates($imonth, $day, $year, $occurs, $repeat);
  ($hour, $min, $interval) =  split(/:/, $rest);
  $tstart = $hour * 100 + $min;
  $tmp = ($min+$interval);  $j = $hour + int($tmp/60);  $k = $tmp % 60;
  $tend = $j * 100 + $k;

  if(defined $::calinfo{'mkey'}) { $mkey= $::calinfo{'mkey'}; } # Must From Modify an existing Meeting Event
  else { $mkey="";}

  $out=""; $txtmsg="";
  if($count > 1) {(@save) = (@::caldata);  @::caldata=();}
  foreach $mem (@members) {
      $::calinfo{'privacy'}='ostxti';
      $mem = untaintname($mem,$::phr{'Invalidusername'});
      $iname="$::o{'spooldir'}/$mem/info";
      $cname="$::o{'spooldir'}/$mem/data";
      my $ckme;  $ckme = 1 if $dock > 0;
      if( -f $cname and -f $iname) {
	  $rest="";
	  if($count > 1) {
	      delete $::calinfo{'ol'};
	      if($mem eq $who) { do "$iname";} # $cname is locked already. Dead lock occurs otherwise
	      else { doReadFile($iname);}
	      if($::calinfo{'ol'} and $::calinfo{'ol'} > 1) { $ckme = 8 ;}

	      if($ckme) {
		  $rest = "<td width=\"20%\" align=left><a href=\"$::o{'cginame'}?w=$mem&c=get&ls=$ls&v=$view$::vmg\"><span class=\"cftCname\">$mem</span></a></td>";
		  if($mem eq $who) { do "$cname";} # $cname is locked already. Dead lock occurs otherwise
		  else {  doReadFile($cname);}
		  if($mkey) { # mark so that we don't use the entry being modified
		      my $href; for $href (@::caldata) {
			  if(exists $href->{'mkey'} and $href->{'mkey'} eq $mkey){ $href->{'deleted'}=1; last;}
		      }
		  }
	      }
	  }
	  if($::calinfo{'ol'}) {
	      if($::calinfo{'ol'} > $aol) { $aol= $::calinfo{'ol'};}
	      if($::calinfo{'ol'} > 1) { $ckme = 8;}
	  }
	  $cal="";
	  if($ckme) {
	      my ($tmn, $tdy, $tyr, $tdate, $tstr, $ii, $bclr, $ckwh);
	      $ii=0;
	      &getWorkingHourTable($mem);
	      $ckwh = $::WorkingHours[16];
	      
	      foreach $tstr (@alldates) {
		  next if $tstr eq "0/0/0";
		  ($tmn, $tdy, $tyr) = split(/\//, $tstr);
		  $tmn--;
		  if($ckwh) {
		      my ($wday, $istart, $iend);
		      $wday = wday($tmn, $tdy, $tyr);
		      $istart = $::WorkingHours[$wday];
		      $iend = $::WorkingHours[$wday+8];
		      if( $tstart < $istart or $tend > $iend) { # overlap with off duty hours
			  $bclr = $webcalConfig::r{'oColors'}->[6];
			  $tdate = mdy_string($tmn, $tdy, $tyr);
			  $tim = hm_string($hour,$min);
			  $tmp = $::phr{'OffDutyHours'};
			  $cal .= "<tr bgcolor=$bclr><td width=\"40%\"><font size=-1><b><span class=\"ztt4\"><font color=#0066cc>$tdate &nbsp; $tim &nbsp;</span></font></b></font></td><td width=\"60%\"><font size=-1><span class=\"zet4\">$tmp</span></font></td></tr>"; 
			  if($ckme > 1){ $pcals{$mem}=1;}
			  if($::calinfo{'no_html_code'}) { $txtmsg .="$mem: $tdate $tim $tmp\n";}
		      }
		  }
		  getEventGivenTime($tmn, $tdy, $tyr, $hour, $min, $interval);
		  @keys = sort sorttime (keys %::oneDayEvents);
		  for $key (@keys) {
		      ($hr,$mn, $ehr, $emn, $kind, $tag)=split(/:/, $key);if($kind==4){$hr=~ s/^\(\d+\)//;}
		      $tim = hm_hm_string($hr,$mn,$ehr,$emn);
		      $tdate = mdy_string($tmn, $tdy, $tyr);
		      $tmp = $::oneDayEvents{$key};
		      $bclr = $webcalConfig::r{'rowColors'}->[$ii];
		      if($::calinfo{'ol'} and $::calinfo{'ol'}>1){ $pcals{$mem}=1;}
		      if($::calinfo{'no_html_code'}) {
			  my $smp = $tmp; $smp=~ s/<img[^>]+>//ig;
			  $smp=~ s/<a[^>]+>//ig;  $smp=~ s/<\/a>//ig;
			  $txtmsg .="$mem: $tdate $tim $smp\n";
		      }
		      if($kind == 1) {
			  $cal .= "<tr bgcolor=$bclr><td width=\"40%\"><font size=-1><b><font color=$::o{'tclra'}><span class=\"ztt1\">$tdate &nbsp; $tim &nbsp;</span></font></b></font></td><td width=\"60%\">" .
			      "<font size=-1><span class=\"zet1\">$tmp</span></font></td></tr>\n";
			  $ii= (1+$ii) & 1;
		      } elsif ($kind == 3) {
			  $cal .= "<tr bgcolor=$bclr><td width=\"40%\"><font size=-1><b><font color=$::o{'tclrm'}><span class=\"ztt3\">$tdate &nbsp; $tim &nbsp;</span></font></b></font></td><td width=\"60%\">" .
			      "<font size=-1><span class=\"zet3\">$tmp</span></font></td></tr>\n";
			  $ii = (1+$ii) & 1;
		      }
		  }
	      }
	  }
	  if($cal) {
	      $cal = "<table border=0 cellpadding=0 cellspacing=0 width=\"100%\" class=\"cftETable\">\n" . $cal . "</table>\n";
	      $out .= "<tr>$rest<td align=left>$cal</td></tr>";
	  }
      }
  }
  if($count > 1) { (@::caldata) = (@save);}
  if($out ne "") { # conflict exists
      # &headers($::phr{'CompareCalendars'},undef,undef,1,1);
      $tmp = ($min+$interval);
      $hr = $hour + int($tmp/60);
      $mn = $tmp % 60; if($mn < 10) { $mn = "0$mn";}
      my $rmsg;
      if(! $::calinfo{'donotacknowledge'}) {
	  $rmsg = <<_END_;
<center>
<br>
<table bgcolor=$webcalConfig::r{'dkbackground'} border=1 cellpadding=8 cellspacing=0 width="90%"><tr><td align=center>
<font size=+1 color="#ff0000"><b><span class="miscTitleSmall">$::phr{'Warning'}</span></b></font></td></tr><tr><td>
<table border=0 cellpadding=8 cellspacing=0 width="100%">
<tr><td bgcolor=$webcalConfig::r{'dkbackground'} width="100%"><span class="fmLabel">$::phr{'OverlapInstr'}<br><br>$::phr{'OverlapInstr2'}</span></td></tr>
_END_
    ;
      } else {
	  $rmsg = <<_END_;
<center>
<br>
<table bgcolor=$webcalConfig::r{'dkbackground'} border=1 cellpadding=8 cellspacing=0 width="90%"><tr><td>
<table border=0 cellpadding=8 cellspacing=0 width="100%">
<tr><td bgcolor=$webcalConfig::r{'dkbackground'} width="100%"><span class="fmLabel">$::phr{'OverlapDnD'}</span></td></tr>
_END_
    ;
      }
  
      if($aol > 1) {
	  my $tmp = join(', ', (keys  %pcals));
	  $rmsg .= "<tr><td bgcolor=$webcalConfig::r{'dkbackground'} width=\"100%\">
<font color=#ff0000><b><span class=\"fmLabel\">$::phr{'OverlapNotAllowed'}</span></b></font><br><br><font color=009999><b>$tmp</b></font><br></td></tr>";
      }
      $title = substImages($title);
      my $aa = "<font size=+1><b><span class=\"miscTitleSmall\">" . mdy_nstring($month,$day,$year) . " <font color=#ff0000>&nbsp;" . hm_hm_string($hour,$min,$hr,$mn). "</font></span></b></font>";

      if($count > 1) { $rest = "<td width=\"20%\"><font size=+1><b><span class=\"cftEtHead\"><font color=#0077ff>$::phr{'Name'}</span></font></b></font></td>"; } else {$rest ="";}    

      if(! $::calinfo{'donotacknowledge'}){
	  $rmsg .= <<_END_;
<tr><td align=center><FORM><b><input class="fmBtn" type=button onClick="javascript:history.go(-1)" value=" $::phr{'GoBack'} "></b></FORM></td></tr>
_END_
;
      }

      $rmsg .= <<_END_;
</table></td></tr></table>
<br>
<table bgcolor=$webcalConfig::r{'dkbackground'} border=1 cellpadding=2 cellspacing=0 width="90%"><tr bgcolor="#99ff99"><td align=center>
<table border=0 cellpadding=2 cellspacing=0 width="100%"><tr><td>
$aa
</td><td><font size=+1><span class="miscTitleSmall"><font color=006699>$title</font></span></font></td></tr></table>
</td></tr><tr><td>
<table border=0 cellpadding=1 cellspacing=1 width="100%" bgcolor="#ccccff">
<tr>$rest<td align=center><font color="#0077ff"><b><span class="cftEtHead">$::phr{'ConflictingE'}</span></b></font></td></tr>
$out
</table></td></tr></table>
</center>
_END_
    ;
      if($::calinfo{'no_html_code'}) { return "Event is rejected due to schedule conflict\n\n$txtmsg";}
      return $rmsg;
  }
  return "";
}
#===============================================================================================
sub outputPage00 {
    my ($content) = (@_);
    &headers($::phr{'Calendar'},undef,undef);    
    print $content;
    &trailer(0,0);
    myexit(0);
}
#===============================================================================================

sub showCEvents {
  my ($mem, $date,@tmem, %hh, @members, $month, $day,$year,$hour,$min, $who, $cname, $iname, $interval, $atten, $satten, $imgp);
  my ($i, $j, $k, $cal, @keys, $key, $tmp, $hr, $mn, $ehr, $emn, $tim, $kind, $imonth, $tag, $view, $imrem, $mg, $iroom, $ls, $eme);
  $who = $::calinfo{'w'};
  $view = $::calinfo{'v'};
  $ls = $::calinfo{'ls'};
  $interval= $::calinfo{'interval'};
  $date = $::calinfo{'d'};

  ($month, $day, $year, $hour, $min) = split(/\//, $date);
  $imonth=$month+1;
  if(defined $::calinfo{'imrem'}){$imrem = $::calinfo{'imrem'};} else {$imrem="";}
  if(defined $::calinfo{'iroom'}){$iroom = $::calinfo{'iroom'};} else {$iroom="";}
  if(defined $::calinfo{'imatt'}) {$satten = $atten = $::calinfo{'imatt'};}
  elsif (defined $::calinfo{'mg'}) {$satten = $atten = $::calinfo{'mg'};}
  else {$satten = $atten = $who;}
  if(defined $::calinfo{'imgp'}) {$imgp = $::calinfo{'imgp'};} else {$imgp="";}
  $eme=$who; if($::calinfo{'eme'}) { $eme=$::calinfo{'eme'};}
  if($imgp ne "$::phr{'none'}") {   $_=$atten;   if( ! /\b$imgp\b/) {   $atten .= " $imgp";}}
  $atten =~ s/[,; ]+/:/g;
  $atten = expandMeetingGroups($eme,$atten);
  $atten =~ s/^:|:$//g;
  $atten =~ s/:/,/g;
  if(defined $::calinfo{'mg'}) {
    $mg="<input type=hidden name=mg value=\"$atten\">";
  } else { $mg="";}

  %hh = ();
  @members=();
  (@tmem) = split(/,/, $atten);
  for $mem (@tmem) {
    if( !exists $hh{$mem}) {
      push @members, $mem;
      $hh{$mem} = 1;
    }
  }
  &headers($::phr{'CompareCalendars'},undef,undef,1,1);
  print "<center>";
  print "<br><h2>$::phr{'EventsTable'}: ",mdy_nstring($imonth,$day,$year),"<font color=#ff0000>&nbsp;",hm_string($hour,$min),"</font></h2>";
  print "<table border=1 cellpadding=4 cellspacing=0 width=\"80%\">\n";
  print "<tr><td width=\"20%\"><font color=#0077ff size=+1><b><span class=\"cftEtHead\">$::phr{'Name'}</span></b></font></td><td align=center><font color=#0077ff size=+1><b><span class=\"cftEtHead\">$::phr{'Events'}</span></b></font</td></tr>\n";
  foreach $mem (@members) {
    $::calinfo{'privacy'}='ostt';
    $mem = untaintname($mem,$::phr{'Invalidusername'});
    $iname="$::o{'spooldir'}/$mem/info";
    $cname="$::o{'spooldir'}/$mem/data";
    if( -f $cname and -f $iname) {
      doReadFile($iname);
      doReadFile($cname);
      print "<tr><td><a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$mem&v=2&d=$month/$day/$year$::vmg\"><b><span class=\"cftCname\">$mem</span></b></a></td><td>";
      getEventGivenTime($month, $day, $year, $hour, $min, $interval);
      @keys = sort sorttime (keys %::oneDayEvents);
      $cal="";
      for $key (@keys) {
	($hr,$mn, $ehr, $emn, $kind, $tag)=split(/:/, $key);if($kind==4){$hr=~ s/^\(\d+\)//;}
	$tim = hm_hm_string($hr,$mn,$ehr,$emn);
	$tmp = $::oneDayEvents{$key};
	if($kind == 1) {
	  $cal .= "<tr><td><font color=$::o{'tclra'} size=-1><b><span class=\"ztt1\">$tim &nbsp;</span></b></font></td><td>" .
	    "<font size=-1><span class=\"zet1\">$tmp</span></font></td></tr>\n";
	} elsif ($kind == 2) {
	  $cal .= "<tr><td><font color=$::o{'tclrt'} size=-1><b><span class=\"ztt2\">$tim &nbsp;</span></b></font></td><td>" .
	    "<font size=-1><span class=\"zet1\">$tmp</span></font></td></tr>\n";
	} elsif ($kind == 3) {
	  $cal .= "<tr><td><font color=$::o{'tclrm'} size=-1><b><span class=\"ztt3\">$tim &nbsp;</span></b></font></td><td>" .
	    "<font size=-1><span class=\"zet1\">$tmp</span></font></td></tr>\n";
	} else {
	  $cal .= "<tr><td><font color=$::o{'tclrs'} size=-1><b><span class=\"ztt4\">$tim &nbsp;</span></b></font></td><td>" .
	    "<font size=-1><span class=\"zet1\">$tmp</span></font></td></tr>\n";
	}
      }
      if($cal) {
	$cal = "<table border=0 cellpadding=0 cellspacing=0 class=\"cftETable\">\n" . $cal . "</table>\n";
      } else { $cal = "&nbsp;";}
      print "$cal</td></tr>";
    }
  }
  print "</table>";
  print "<br><font color=#999900><b><span class=\"authWarn\">$::phr{'AuthRequired'}!</span></b></font><br>";
  print "<table border=1 cellpadding=8 cellspacing=0 width=\"80%\">
<Form name=fmctd action=\"$::o{'cginame'}\" method=POST>$::vmp
<input type=hidden name=c value=\"ne\">
<input type=hidden name=eme value=\"$eme\">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value=\"$date\">
<input type=hidden name=imgp value=\"$imgp\">
<input type=hidden name=imatt value=\"$satten\">
<input type=hidden name=iroom value=\"$iroom\">
<input type=hidden name=imrem value=\"$imrem\">
$mg
<tr><td align=center><b><font size=+1><span class=\"fmLabel\">";
print mdy_nstring($imonth,$day,$year),"<font color=#ff0000>&nbsp;",hm_string($hour,$min),"</font></span></font></b><br>";
print "<b><span class=\"fmLabel\">$::phr{'Schedule'}</span></b>
<input type=radio class=\"fmRadio\" name=k value=1><font color=#ff0000>&nbsp;<b><span class=\"fmLabel\">$::phr{'Appointment'}</span></b></font>
<input type=radio class=\"fmRadio\" name=k checked value=3><font color=#cc00cc>&nbsp;<b><span class=\"fmLabel\">$::phr{'Meeting'}</span></b></font>
&nbsp;<b><span class=\"fmLabel\">$::phr{'onCalendar'}</span></b>&nbsp;",select_option("w",$who,@members);
  print "</td><tr>\n";
  print "
<tr><td align=center><input type=submit name=action class=\"fmBtnSt\" value=\"$::phr{'Submit'}\">
<input type=submit name=action class=\"fmBtnSt\" value=\"$::phr{'Cancel'}\"></td>
</form></table>";
  print "</center>";
  &trailer(0,0);
}

sub getEventGivenTime {
  use integer;
  my ($date, $occurs, $repeat, $exception, $today, $i, $month, $day, $year, $kind, $tmp, $smp, $tim, $start,$ls,
      $whoami, $dmonth, $duration, $ehr, $emn, $utmp, $hr, $mn, $key, $who, $view,$edate, $junk, $href,
      $gprivacy, $eprivacy, $endM, $endD, $endY, $interval, $ihr, $imn, $fhr, $fmn, @editors, $editor, $hpnd);
  ($month, $day, $year, $ihr, $imn, $interval) = (@_);
  $dmonth = $month + 1;
  $today= "$dmonth/$day/$year";
  $utmp=$imn+$interval;
  $fhr=$ihr + int($utmp/60);
  $fmn = $utmp % 60;

  $whoami=$::d{'remote_user'};
  $who = $::calinfo{'w'};
  $view = $::calinfo{'v'};
  $ls = $::calinfo{'ls'};

  $gprivacy = 0;
  if($whoami eq $who) { $gprivacy = 4;}
  elsif($::d{'megaCal'} ne "") { $gprivacy=2;} # MegaCal uses event based privacy.
  else {
    if(defined $::calinfo{'editors'}) {$tmp = $::calinfo{'editors'};} else {$tmp="";}
    $tmp =~ s/[,; ]+/:/g;
    (@editors)=split(/:/, $tmp);
    for $editor (@editors) { if($::d{'remote_user'} eq $editor) {$gprivacy = 4; last;} }
    if($gprivacy != 4) {
      if($::calinfo{'privacy'}) {$tmp=$::calinfo{'privacy'}; $gprivacy = $::privacyTable{$tmp} -1;}
      else { $gprivacy = 3;}
    }
  }

  if($gprivacy < 4) { $hpnd=1;} else { $hpnd=0;}
  %::oneDayEvents=();
  for $href (@::caldata) {
    next if $href->{'deleted'};
    if($gprivacy > 3) { $eprivacy = 3;}
    else {
      if(defined $href->{'w'} and $href->{'w'} eq $whoami) { $eprivacy = 3;} #for megaCalendar
      elsif(defined $href->{'privacy'}) { $eprivacy = $::privacyTable{$href->{'privacy'}} -1; } 
      else {$eprivacy = $gprivacy;}
    }
    if($href->{'end'}) {
      ($endM, $endD, $endY) = split(/\//, $href->{'end'}); $endM--;
      next if $year > $endY;
      if ($year == $endY) {
	next if $month > $endM;
	next if $month == $endM and $day > $endD;
      }
    }
    $start = $href->{'start'};
    if($href->{'duration'}) {$duration = $href->{'duration'};} else {$duration =0;}
    ($hr,$mn)=split(/:/,$start);
    $utmp=$mn+$duration;
    $hr = 0 if ($hr eq "");
    $ehr=$hr + int($utmp/60);
    $emn = $utmp % 60;
    if(intersectTimeinterval($hr,$mn, $ehr, $emn, $ihr, $imn, $fhr, $fmn) == 0) { next;}
    if($emn < 10) { $emn="0$emn";}

    $tmp="";
    $date = $href->{'date'};
    $occurs = $href->{'occurs'};
    $repeat = $href->{'repeat'};
    $exception = $href->{'exception'};
    $kind =  $href->{'kind'};
    if($kind == 2 and defined $href->{'done'}) {	# todo event,
      my $done = $href->{'done'};
      if($done eq 'y' and !$::calinfo{'dctoc'}) { next;}		# do not display completed tasks
    }
    my $mkind; if($::calinfo{'dctoc'}) { $mkind = $kind;} else {$mkind = 0;}	  
    if(calmatch($today, $date, $occurs, $repeat, $exception, $mkind)) {
      my( $tip, $detail);
      $tip="";
      $key = $href->{'key'};
      if($eprivacy >= 2) {
       if($href->{'pnd'} and $hpnd) {
	   $smp = "$::phr{'Pending'}";
       } else {  
	$smp = $href->{'what'}; $smp = "no subject" unless $smp;
	$detail = "";
	if($eprivacy >= 3) {
	    $detail = $href->{'detail'}; 
	    my ($misc, $troom, $tspkr, $tcat, $trest)  = getMiscInfo($href);
	    if($misc) {
		if($detail) { $detail .= " <br>";}	    
		$detail .= $misc;
	    }
	}
    }
	my ($owner, $tiptag);
	if(defined $href->{'w'}) {$owner = $href->{'w'}; $tiptag = 1;} else {$owner = $who; $tiptag = 0;}
        if($detail) {
	  #$detail =~ s/\'/\\\'/g; 
          #$detail =~ s/\"/\\\'/g;
	  $detail = &substImages($detail);
          #$detail =~ s/\n/&lt;br&gt;/g;
	  $detail =~ s/\n/<br>/g if ($detail =~ tr/\n/\n/) <20;
          my $tpid;
	  if($tiptag) {
	      my $zz = $who; $zz =~ s/[^A-Za-z0-9]//g;
	      $tpid = add4tip("$key$zz",$detail);
	  } else {
	      $tpid = add4tip($key,$detail);
	  }
          $tip = " onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"";
        }
      } else {
	  if(defined $href->{'w'}) {
	      $smp = "<FoNt CoLoR=#0000Ff>" . $href->{'w'} . ":</FoNt> " . ": $::phr{'Protected'}"; 
	  } else {$smp = "$::phr{'Protected'}"; }
      }
      $tim = $junk = $start;
      $junk =~ s/:/\//g;
      $edate = "$month/$day/$year/$junk";
       $tim .= ":$ehr:$emn:$kind:$key";
      $::oneDayEvents{$tim} = "<a href=\"$::o{'cginame'}?w=$who&c=ed&v=$view&ls=$ls&t=$key&k=$kind&d=$edate$::vmg\"$tip>$smp</a>";
   }
  }
}
#=====================================================================================================
sub getMiscInfo {
    my($href) = (@_);

    my ($detail, $troom, $tspkr, $tcat, $trest)  = ("", "", "", "", "");
    if(defined $href->{'p'} and $href->{'p'}) {
        my $tmp = "<foNt color=#cc0000><font size=1>On Calendar:</font>  $href->{'p'}</font>";	
        $trest .= $tmp;
	$detail .= $tmp;
    }

    if(defined $href->{'room'} and $href->{'room'} ne "") { 
	if($detail) { $detail .= " <br>";}
        $troom = $href->{'room'};
	$detail .= "<b>$::phr{'Location'}:</b> $troom";
    }
    if(defined $href->{'spkr'} and $href->{'spkr'} ne "") {
	if($detail) { $detail .= " <br>";}
        $tspkr = $href->{'spkr'};
	$detail .= "<b>$::phr{'Speaker'}:</b> $tspkr";
    }	
    if($href->{'ctp'}) {
	if($detail) {$detail .=" <br>";} 
        my $tmp =  "<b>$::phr{'ContactP'}:</b> $href->{'ctp'}";
	$detail .= $tmp;
	if($trest) {$trest .=" <br>";} 
        $trest .= $tmp;
    }
    if($href->{'ctm'}) {
	if($detail) {$detail .=" <br>";} 
        my $tmp = "<b>$::phr{'ContactE'}:</b> $href->{'ctm'}";
	$detail .= $tmp;
	if($trest) {$trest .=" <br>";} 
        $trest .= $tmp;
    }
    if(defined $href->{'pri'} and $href->{'pri'} ne "") {
	if($detail) { $detail .= " <br>";}
        my $tmp = "<b>$::phr{'Priority'}:</b> $href->{'pri'}";
        $trest .= $tmp;
	$detail .= $tmp;
    }
    if(defined $href->{'cat'} and $href->{'cat'} ne "") {
	if($detail) { $detail .= " <br>";}
        $tcat = $href->{'cat'};
	$detail .= "<b>$::phr{'Category'}:</b> $tcat";
    }
    return ($detail, $troom, $tspkr, $tcat, $trest);
}
#=====================================================================================================
sub loadLangfile {
  if ($::o{'language'} and $::o{'language'} =~ /^([^\/]*)$/) { $::o{'language'} = $1;  } 
  else { $::o{'language'} = 'English';  }
  my $langFile = $::o{'language'} . ".perl";
  $langFile = "English.perl" if (! -f "$::o{'cgidir'}/$langFile");

  if (defined $::LoadedLangFile && $langFile eq $::LoadedLangFile) {  &setViewMode;  return; }

  $::LoadedLangFile = $langFile;
  %::phr=();
  @::wdays = ();
  @::swd = ();
  @::wkdNames=();
  @::mname=();
  @::mNames=();

  my $cgidir="$::o{'cgidir'}"; if($cgidir =~ /^(.+)$/) {$cgidir=$1;}
  $langFile = untaintname($langFile);  do "$cgidir/$langFile";
  
  @::wdays = ("$::phr{'Sunday'}","$::phr{'Monday'}","$::phr{'Tuesday'}","$::phr{'Wednesday'}",
	    "$::phr{'Thursday'}","$::phr{'Friday'}","$::phr{'Saturday'}","$::phr{'Sunday'}");
  @::swd = ("$::phr{'Su'}","$::phr{'Mo'}","$::phr{'Tu'}","$::phr{'We'}","$::phr{'Th'}","$::phr{'Fr'}","$::phr{'Sa'}","$::phr{'Su'}");
  @::wkdNames=("$::phr{'Sun'}","$::phr{'Mon'}","$::phr{'Tue'}","$::phr{'Wed'}","$::phr{'Thu'}","$::phr{'Fri'}","$::phr{'Sat'}","$::phr{'Sun'}");

  @::mname=("$::phr{'January'}","$::phr{'February'}","$::phr{'March'}","$::phr{'April'}","$::phr{'May_'}","$::phr{'June'}",
	    "$::phr{'July'}","$::phr{'August'}","$::phr{'September'}","$::phr{'October'}","$::phr{'November'}","$::phr{'December'}");

  @::mNames=("$::phr{'Jan'}","$::phr{'Feb'}","$::phr{'Mar'}","$::phr{'Apr'}","$::phr{'May'}","$::phr{'Jun'}",
	     "$::phr{'Jul'}","$::phr{'Aug'}","$::phr{'Sep'}","$::phr{'Oct'}","$::phr{'Nov'}","$::phr{'Dec'}");

  %::tabNames= (
	'get' => "$::phr{'Calendar'}",
	'task' => "$::phr{'Tasks'}",
	'ad' => "$::phr{'Contacts'}",
	'diary' => "$::phr{'Diary'}",
	'option' => "$::phr{'Options'}",
	'search' => "$::phr{'Search'}",
	'admin' => "$::phr{'Admin'}",
	'notes' => "$::phr{'Notes'}");

  @::nyList= (
	"n","$::phr{'N'}",
	"y","$::phr{'Y'}");

  @::switchList= (
	1,"$::phr{'Y'}",
	0,"$::phr{'N'}");

  @::boolList= (
	0,"$::phr{'Y'}",
	1,"$::phr{'N'}");

  @::unitmList= (
	"m","$::phr{'mins'}",
	"h","$::phr{'hours'}",
	"d","$::phr{'days'}",
	"w","$::phr{'weeks'}");

  @::unitList= (
	"m","$::phr{'mins'}",
	"h","$::phr{'hours'}");

  @::unit2List= (
	"d","$::phr{'days'}",
	"w","$::phr{'weeks'}");

  @::viewList= (
	3,"$::phr{'MonthView'}",
	2,"$::phr{'WeekView'}",
	1,"$::phr{'DayView'}");

  @::lsList= (
	0,"$::phr{'BlockView'}",
	1,"$::phr{'ListView'} 1",
       -1,"$::phr{'ListView'} 2");

  @::eventList= (
	1,"$::phr{'Appointment'}",
	2,"$::phr{'ToDo'}",
	3,"$::phr{'Meeting'}",
	4,"$::phr{'Special'}",
	0,"$::phr{'All'}");

  @::occurrenceList= (
	"OneTime","$::phr{'OneTime'}",
	"Daily","$::phr{'Daily'}",
	"Weekly","$::phr{'Weekly'}",
	"Every2Weeks","$::phr{'Every2Weeks'}",
	"MonthlyByDate","$::phr{'MonthlyByDate'}",
	"MonthlyByWeekday","$::phr{'MonthlyByWeekday'}",
	"Yearly","$::phr{'Yearly'}",
	"YearlyByMonthWeekday","$::phr{'YearlyByMonthWeekday'}",
	"MTWThF","$::phr{'MTWThF'}",
	"MWF","$::phr{'MWF'}",
	"TTh","$::phr{'TTh'}",
	"EveryOtherDay","$::phr{'EveryOtherDay'}",
	"Every3rdDay","$::phr{'Every3rdDay'}",
	"Every4thDay","$::phr{'Every4thDay'}",
	"Every5thDay","$::phr{'Every5thDay'}",
	"Every6thDay","$::phr{'Every6thDay'}",
);

  @::privacyList= (
	"ostxti","$::phr{'OthersSeeTextTime'}",
	"ostt","$::phr{'OthersSeeTitle'}",
	"osti","$::phr{'OthersSeeTimeOnly'}",
	"osn","$::phr{'OthersSeeNothing'}");

  @::ctypeList= (
	'private',"$::phr{'Private'}",
	'public',"$::phr{'PublicOpen'}",
        'public_m',"$::phr{'PublicModerated'}");

  @::accessList = (
     0, "$::phr{'OwnerOnly'}",
     1, "$::phr{'Editors'}",
     2, "$::phr{'Readers'}",
     3, "$::phr{'Everyone'}");


  @::sixteenColors = (
		      $::phr{'Aqua'},    'Aqua'   ,#      #00FFFF,
		      $::phr{'Black'},   'Black'  ,#      #000000,
		      $::phr{'Blue'},    'Blue'   ,#      #0000FF,
		      $::phr{'Fuchsia'}, 'Fuchsia',#      #FF00FF,
		      $::phr{'Gray'},    'Gray'   ,#      #808080,
		      $::phr{'Green'},   'Green'  ,#      #008000,
		      $::phr{'Lime'},    'Lime'   ,#      #00FF00,
		      $::phr{'Maroon'},  'Maroon' ,#      #800000,
		      $::phr{'Navy'},    'Navy'   ,#      #000080,
		      $::phr{'Olive'},   'Olive'  ,#      #808000,
		      $::phr{'Purple'},  'Purple' ,#      #800080,
		      $::phr{'Red'},     'Red'    ,#      #FF0000,
		      $::phr{'Silver'},  'Silver' ,#      #C0C0C0,
		      $::phr{'Teal'},    'Teal'   ,#      #008080,
		      $::phr{'White'},   'White'  ,#      #FFFFFF,
		      $::phr{'Yellow'},  'Yellow' ,#      #FFFF00,
		      $::phr{'none'},    ''       ,
		      );

  &setViewMode;
}
#=====================================================================================================
sub myexit {
  my $status= (@_)[0];
  &initVars;
#  if(defined $ENV{'SERVER_SOFTWARE'})
#    $_= "$ENV{'SERVER_SOFTWARE'}";
#    if (/mod_perl/) { &Apache::exit($status);}
#  }
  exit ($status);
}
#=====================================================================================================
sub requireLogin {
  my ($who, $view, $sdate, $cmd, $extra, $ls);
  ($cmd, $sdate, $extra) = (@_);
  $who = $::calinfo{'w'};
  $view = $::calinfo{'v'};
  $ls = $::calinfo{'ls'};
  &headers($::phr{'login'},undef,undef,1);
  print "<center>";
  print "<br><font color=#ff0000 size=+1><b><span class=\"miscTitle\">$::phr{'NeedAuth2Proceed'}</span></b></font>";
  print "
<Form action=\"$::o{'cginame'}\" method=POST>$::vmp
<input type=hidden name=c value=\"$cmd\">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value=\"$sdate\">
<input type=hidden name=w value=\"$who\">
$extra
<table width=\"40%\" border=0 cellspacing=2 cellpadding=0>
<tr><td align=right><b><input type=submit class=\"fmBtnSt\" name=action value=\"$::phr{'login'}\">&nbsp;&nbsp;</td>
<td align=left>&nbsp;&nbsp;<a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$sdate$::vmg\">
<img src=\"$::o{'imgdirurl'}/yearview.gif\"width=21 height=22 border=\"0\" title=\"$::phr{'Calendar'}\" alt=\"$::phr{'Calendar'}\"></a>
</td></tr></table>
</form></center>";
  &trailer(0,0);
  myexit(0);
}

#=====================================================================================================
# Contact list ....
#
sub matchAddress {
    my ($words, $addr) = (@_);
    my ($k, $v);
    foreach $k (keys %$addr) {
	if(matchMExpr($words, $addr->{$k})) {return 1;}
    }
    return 0;
}

sub loadAddressBook {
    my ($afile) = (@_);
    my ($status, $count);
    if($::o{'contactdb'} and $::o{'contactdb'} !~ /default/i) {
        ($status, $count)= &webcalContactDB::LoadAddressBook(); 
        $::calinfo{'ext-addr'} = 1;
    } else {
        if( -f $afile) { $count = doReadFile($afile);} 
    }
    return $count;
}

sub address {
  my $cmd = (@_)[0];
  my ($afile, $href, $name, $lname, $fname, $phone, $fax, $email, $addr, $info, $tag, $count, $tmp, $smp, %rows, $key);
  my ( $rwho, $who, $view, $month, $day, $year, $ii, $memail, $hpage, $mhpage, $comp, $ls, $sdate, $rlevel);
  my ( $city, $state, $zip, $country, $map, $az, $naddresses, $nhd, $nhdf);
  $who = $::calinfo{'w'};   $rwho = $who;
  $view = $::calinfo{'v'};
  $ls = $::calinfo{'ls'};
  $month= $::calinfo{'month'};
  $day  = $::calinfo{'day'};
  $year = $::calinfo{'year'};

  if(defined $::calinfo{'d'}) {  $sdate = $::calinfo{'d'};}
  else { $sdate="$month/$day/$year";}

  if( $::d{'ispublic'} == 0 and $::d{'remote_user'} eq "" ) { # need authentication
    my $sdate = "$month/$day/$year";
    requireLogin('ad', $sdate, "");
  }
  # 7/10/01
  $rlevel = 0;
  if( $::d{'ispublic'} == 0) {
      my $tmp; if($::calinfo{'paddress'}) {$tmp= $::calinfo{'paddress'};} else { $tmp = 0;}
      if($::d{'remote_user'} eq $who ) { $rlevel = 10;}
      elsif( $tmp > 0 and  isre($::d{'remote_user'}, $who, 'editors') ) { $rlevel = 10;}
      elsif( $tmp > 2 or ($tmp > 1 and isre($::d{'remote_user'}, $who, 'readers')) ) { $rlevel = 1;}
      #else {
      #    my $me = untaintname($::d{'remote_user'},$::phr{'Invalidusername'});
      #    if( -d "$::o{'spooldir'}/$me") { $::d{'authResult'} = 4; $who = $me} 
      #    else { calerror("$::phr{'You'} ($me) $::phr{'NotAllowedToEdit'} ($who)."); }
      #}
  } else { $rlevel = 10;}

  if($rlevel == 0) { calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who)."); }

  #&make_style_sheet();   
  %rows = ();
  $afile="$::o{'spooldir'}/$who/address";
  $count = &loadAddressBook($afile);
  $naddresses = scalar @::addressbook;
  if( $naddresses == 0) {
    if(!defined $count or $count == 0) { $count = 1;}
    @::addressbook=({lname=>'Zou',fname=>'Maorong',phone=>'512-471-0122',fax=>'512-471-9038',email=>'mzou@math.utexas.edu',
                     com=>'Math Dept, UT Austin',
                     hpage=>'http://www.math.utexas.edu/users/mzou', addr=>'Dept. of Math, UT Austin',
                     city=>'Austin', state=>'TX', zip=>'78712',
                     info=>'WebCalendar Author', tag=>'1',},);
  }
  if($cmd eq 'dad' and defined $::calinfo{'action'} and $::calinfo{'action'} eq "$::phr{'Cancel'}") { $cmd = "ad";}
  if($cmd eq 'sad' and ! $::calinfo{'kword'}) { $cmd = "ad";}

  if($cmd eq "ad" or $cmd eq "sad") { # display addr book
      if($cmd eq 'sad') { $::d{'SATbs'}=1;}
      my ($bscript, $script, $body)=('','', '');
      $nhd=$::calinfo{'nhd'};
      if(not $nhd) {
          ($bscript,$script) = &getClockScript(); 
          $body = $bscript; 
   
          &headers($::phr{'AddressBook'}, $script, undef,1,0,$body);

          my $headerForm=&newHeader('ad', 1);
          print $headerForm;
          $nhd=$nhdf="";
      } else {
          my $fmname=$::calinfo{'fmname'}; 
          my $eltname = $::calinfo{'eltname'}; 
          $nhd="&nhd=1&fmname=$fmname&eltname=$eltname";
          $nhdf="<input type=hidden name=nhd value=1><input type=hidden name=fmname value=$fmname><input type=hidden name=eltname value=$eltname>";
          my $script=<<END;
function taddr(){
 var ptn=/^A.+/;var f=document.ab;var list="";var n=f.elements.length-1;
 for(var i=0;i<=n;i++){var e=f.elements[i];if(e.name.match(ptn) && e.checked){list=list+e.value +', ';}}
 var o=window.opener.document.$fmname.$eltname;o.value=list+o.value;
}
END
    ;
          &headers($::phr{'AddressBook'}, $script); 
          print "<center><br><h2><span class=\"miscTitle\">$::phr{'semails'}</span></h2></center>";
      }

    print "<center>";

    $ii = 100;
    my (@searchwords, $search, $skword);
    $search=0; $skword = "";
    if($cmd eq 'sad') {
	@searchwords = &buildMExpr($::calinfo{'kword'}); $search = 1;
	if($::calinfo{'kword'}) { $skword = $::calinfo{'kword'};}
    }
    my %marks = ();
    my $taz="";
    $az="";
    if($naddresses > 100) {
        if($search) {$az="_"; delete $::calinfo{'az'};} elsif($::calinfo{'az'}) { $az = $::calinfo{'az'}; $taz="&az=$az";} else {$az="A";}
    }
    my $ae = "a"; if($::calinfo{'ext-addr'}) { $ae="b";}
    for $href (@::addressbook) {
      $lname = $href->{'lname'}; $lname ="" if !$lname;
      $fname = $href->{'fname'}; $fname ="" if !$fname;
      if($az) {
          my $n = $lname; $n=$fname if not $n;
          my $t=substr $n, 0, 1; $t=uc($t); $marks{$t}=1;
          if(not $search and $n !~ /^$az/i) { next;}
      }
      if($search and ! matchAddress(\@searchwords, $href)) {next;}

      $name = $fname." ".$lname; if($name eq " ") { $name="???????";}
      $phone = $href->{'phone'} || "";
      $phone =~ s/\n+/<br>/g;
      $fax = $href->{'fax'} || "";
      $fax =~ s/\n+/<br>/g;
      $email = $href->{'email'}; if(!$email) { $email="";}
      if($email ne "" ) {
        $email =~ s/[,;\n]+/<br>/g;
        $memail = "<a href=\"mailto:$email\">$email</a>";
      } else { $memail = "&nbsp;";}
      $addr = $href->{'addr'}; if(!$addr) {$addr="";}
      $addr =~ s/[\n]+/<br>/g;
      if($href->{'city'}) { $city = "<br>" . $href->{'city'};} else { $city = "";}
      if($href->{'state'}) { $state = $href->{'state'};} else { $state = "";}
      if($href->{'zip'}) { $zip = $href->{'zip'};} else { $zip = "";}
      if($href->{'country'}) { $country = "<br>" . $href->{'country'};} else { $country = "";}
      $info = $href->{'info'}; if(!$info){$info="";}
      $info =~ s/[\n]+/<br>/g;
      $hpage = $href->{'hpage'};if(!$hpage){$hpage="";}
      if(defined $href->{'com'}) {$comp = $href->{'com'};} else {$comp = "";}
      if($hpage ne "") {
        $mhpage="<a href=\"$hpage\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/home.gif\" width=11 height=10 border=\"0\"></a>";
      } else { $mhpage = "";}
      $tag = $href->{'tag'};
      if($city or $state) {
          my ($tcity, $tstate, $taddr, $tzip)=($city,$state,$addr,$zip); 
	  $tcity=~s/<[^>]+>//g; $tstate=~s/<[^>]+>//g; $taddr=~s/<[^>]+>//g; $tzip=~s/<[^>]+>//g;
          $tcity=urlencode($tcity);  $tstate=urlencode($tstate); $taddr = urlencode($taddr); $tzip=urlencode($tzip); 
          $map = "&nbsp;<a href=\"http://maps.yahoo.com/py/maps.py?addr=$taddr&city=$tcity&state=$tstate&zip=$tzip\" target=i><img src=\"$::o{'imgdirurl'}/web1.gif\" width=9 height=9 border=0></a>";
      } else {$map = "";}
      $key = $lname . $fname . $ii;
      $info = &substImages($info);
      $rows{$key} ="
<tr><td class=\"addrckbox_rwhldr\" bgcolor=clr_hldr><input type=checkbox class=\"fmRadio\" name=A$ii value=$email></td>
<td class=\"addrName_rwhldr\" bgcolor=clr_hldr><$ae href=\"$::o{'cginame'}?w=$who&c=ead&t=$tag$taz$::vmg\"><font size=-1><b><span class=\"addrName\">$name</span>&nbsp;</b></font></$ae>$mhpage</td>
<td class=\"addrEmail_rwhldr\" bgcolor=clr_hldr><font size=-1><span class=\"addrEmail\">$memail</span>&nbsp;</font></td>
<td class=\"addrPhone_rwhldr\" bgcolor=clr_hldr nowrap><font size=-1><span class=\"addrPhone\">$phone</span>&nbsp;</font></td><td bgcolor=clr_hldr nowrap class=\"addrFax_rwhldr\"><font size=-1><span class=\"addrFax\">$fax</span>&nbsp;</font></td>
<td class=\"addrCompany_rwhldr\" bgcolor=clr_hldr><font size=-2><span class=\"addrCompany\">$comp</span>&nbsp;</font></td>
<td class=\"addrAddr_rwhldr\" bgcolor=clr_hldr><font size=-2><span class=\"addrAddr\">$addr&nbsp; $city $state $zip $country $map</span></font></td>
<td class=\"addrInfo_rwhldr\" bgcolor=clr_hldr><font size=-2><span class=\"addrInfo\">$info</span>&nbsp;</font></td></tr>
";
      $ii++;
  }

#==========================================
      if($az) {
	  print <<END;	  
<br>
<table width="$::o{'tw'}%" border=0 cellpadding=0 cellspacing=0 class="addrIndex"><tr><td width="80%" align=center>
<table width="100%" cellspacing=0 cellpadding=0><tr>
<td align=center nowrap class="addrIndex">
END
    ;
	  my ($link,$tmp) ;
	  $link="<a href=\"$::o{'cginame'}?c=ad&w=$who&ls=$ls&v=$view&d=$sdate$nhd&az=";
	  for $tmp ('A'..'Z') {
	      if($az =~ /$tmp/i) { print "<b><span class=\"addrIndex\"><font color=red>$tmp</font> &nbsp;</span></b>";}
	      elsif(not $marks{$tmp}) { print "<b><span class=\"addrIndex\"><font color=#cccccc>$tmp &nbsp;</font></span></b>";}
	      else { print $link, $tmp, "\"><span class=\"addrIndex\"><font color=blue>$tmp</font></span></b></a> &nbsp;";}
	  }
	  print <<END;
</td></tr></table></td>
<td width="20%" align=center nowrap>
<table border=0 cellspacing=0 cellpadding=0 class="addrSearch"><tr><td nowrap>
<form name=sa action="$::o{'cginame'}" method=POST  class="searchform">$::vmp$nhdf
<input type=hidden name=c value="sad">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$sdate">
<input type=hidden name=w value="$who">
<font size=1>
<b><span class="fmLabelSa">$::phr{'Search'}&nbsp;</span></b><input type=text class="fmEntrySa" size=8 maxlength=100 name=kword value="$skword">
</font> <font size=1><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font>
</form></td></tr></table>
</td></tr></table>

END
    ;
      }
  if($ii > 100) {
      if($search) { print "<br><font color=#ff0000><b><span class=\"miscTitleSmall\">$::phr{'Search_Results'}</span></b></font>";}
#==========================================
      my $faz=""; if($::calinfo{'az'}) { $faz="<input type=hidden name=az value=\"$::calinfo{'az'}\">";}
      my $adjwidth=$::o{'tw'} - 4;
      my ($cwidth, $swidth)=(100,0); if(!$az) { $cwidth=85; $swidth=15;}
      print <<END;
<br>
<table border=0 cellpadding=0 cellspacing=0 class="backtbla" width="$adjwidth%">
<tr><td bgcolor="#9999ff" class="backtbladdress" width="$cwidth%" valign=top align=center>
<form name=ab>$faz$nhdf
<table border=0 cellpadding=2 cellspacing=1 class="address" width="100%">
<tr bgcolor="#cccc99"><td class="addrRow1Td"><span class="addrRow1Txt">&nbsp;</span></td>
<td class="addrRow1Td"><b><span class="addrRow1Txt">$::phr{'Name'}</span></b></td>
<td class="addrRow1Td"><b><span class="addrRow1Txt">$::phr{'Email'}</span></b></td>
<td class="addrRow1Td"><b><span class="addrRow1Txt">$::phr{'Phone'}</span></b></td>
<td class="addrRow1Td"><b><span class="addrRow1Txt">$::phr{'Fax'}</span></b></td>
<td class="addrRow1Td"><b><span class="addrRow1Txt">$::phr{'Affiliation'}</span></b></td>
<td class="addrRow1Td"><b><span class="addrRow1Txt">$::phr{'Address'}</span></b></td>
<td class="addrRow1Td"><b><span class="addrRow1Txt">$::phr{'Info'}</span></b></td></tr>
END
;
      # output the content of table
      {
	  my ($ct, $clr);
	  $ct = 0;

	  for $key (sort {uc($a) cmp uc($b)} (keys %rows)) {
	      $clr= $webcalConfig::r{'rowColors'}->[$ct]; $ct = ($ct? 0 : 1);
	      $tmp = $rows{$key};
	      $tmp =~ s/clr_hldr/$clr/g; $tmp =~ s/_rwhldr/$ct/g;
	      print $tmp, "\n";
	  }
      }
      print "</table></td></form>";
      if(!$az) {
	  print <<END;
<td width="$swidth%" valign=top align=right>
<table border=0 cellspacing=0 cellpadding=0 class="addrSearch"><tr><td nowrap>
<form name=sa action="$::o{'cginame'}" method=POST  class="searchform">$::vmp$nhdf
<input type=hidden name=c value="sad">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$sdate">
<input type=hidden name=w value="$who">
<font size=1><span class="fmLabelSa">$::phr{'Search'}:<br></span></font>
<input type=text size=8 maxlength=100 name=kword value="$skword" class="fmEntrySa">
<font size=1><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font>
</form>
</td></table></td>
END
    ;
      }
      
    print "</tr></table>";
    print "<br>";

    print "<a href=\"javascript:ckalladdresses()\"><font color=#0000ff><span class=\"addrCheck\">$::phr{'CheckAll'}</span></font></a>";
    print "&nbsp; - &nbsp;";
    print "<a href=\"javascript:uckalladdresses()\"><font color=#0000ff><span class=\"addrCheck\">$::phr{'UncheckAll'}</span></font></a>";
    print "<img src=\"$::o{'imgdirurl'}/spacer.gif\" width=300 height=1 border=0>";
    if(not $nhd) {
        print "<a href=\"javascript:domail()\"><font color=#0000ff><b><span class=\"addrSmail\">$::phr{'Email2Selected'}</span></b></font></a>";
    } else {
        my $autoclose="";
        if(!$az){ $autoclose="self.close()";}
        print <<EOF;
<center>
<Form name=mform>
<table border=0>
<tr><td align=center>
<br><font color=red><b>
<input type=button name=xz value="$::phr{'addinvitee'}" onclick="taddr();$autoclose" class="fmBtnSt"> &nbsp;
<input type=button name=zx value="$::phr{'Close'}" onclick="self.close()" class="fmBtnSt">
</b></font>
</td></tr></table></form>
<br>
</center>
EOF
    ;
    }
  } else {
     if($search) {print "<br><b>No match found</b><br>";}
  }
  
  if(! $az) {
    print <<END;

END
    ;
}
    print "</center>";
    &trailer(0,1);
  } elsif($cmd eq 'ead') { # edit address book
    &headers($::phr{'AddressBookEditor'},undef,undef,1);
    print "<center>";
    print "<font color=#ff0000 size=+1><b><span class=\"miscTitle\">$::phr{'AddressBookEditor'} ($who)</span></b></font><br>\n";
    if(defined $::calinfo{'t'}) { $tag = $::calinfo{'t'};} else {$tag = 0;}
    $fname = $lname = $hpage = $comp = $phone = $fax =$email =$addr =$info= $city=$state=$zip=$country="";
    if($tag > 0) {
      for $href (@::addressbook) {
	if($href->{'tag'} == $tag) {
	  $fname = $href->{'fname'};
	  $lname = $href->{'lname'};
	  $hpage = $href->{'hpage'};
	  if(defined $href->{'com'}) {$comp = $href->{'com'};}
	  $phone = $href->{'phone'};
	  $fax = $href->{'fax'};
	  $email = $href->{'email'};
	  $addr = $href->{'addr'};
	  if($href->{'info'}) { $info = $href->{'info'}; } else { $info="";}
          if($href->{'city'}) { $city = $href->{'city'};} else { $city = "";}
          if($href->{'state'}) { $state = $href->{'state'};} else { $state = "";}
          if($href->{'zip'}) { $zip = $href->{'zip'};} else { $zip = "";}
          if($href->{'country'}) { $country = $href->{'country'};} else { $country = "";}
	  last;
	}
      }
    }
    # the form
    if(($::d{'authResult'} | $::d{'ispublic'}) < 4 or $::d{'validuser'} == 0) {
        print "<font color=#999900><b><span class=\"authWarn\">$::phr{'AuthRequired'}!</span></b></font>";
    }
    my $faz=""; if($::calinfo{'az'}) { $faz="<input type=hidden name=az value=\"$::calinfo{'az'}\">";}
    print "
<Form action=\"$::o{'cginame'}\" method=POST>$::vmp $faz
 <input type=hidden name=c value=\"dad\">
 <input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
 <input type=hidden name=d value=\"$month/$day/$year\">
 <input type=hidden name=w value=\"$who\">
 <table border=0 cellspacing=2 cellpadding=0>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'FirstName'}:</span></b></td><td><input type=text name=afname class=\"fmEntry\" size=50 value=\"$fname\"></td></tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'LastName'}:</span></b></td><td><input type=text name=alname  class=\"fmEntry\" size=50 value=\"$lname\"></td></tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'Phone'}:</span></b></td><td>
<textarea name=aphone cols=50 rows=3 class=\"fmText\">$phone</textarea></td></tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'Fax'}:</span></b></td><td><input type=text class=\"fmEntry\" name=afax size=50 value=\"$fax\"></td></tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'Email'}:</span></b></td><td><input type=text class=\"fmEntry\" name=aemail size=50 value=\"$email\"></td></tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'Homepage'}:</span></b></td><td><input type=text class=\"fmEntry\" name=ahpage size=50 value=\"$hpage\"></td></tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'Affiliation'}:</span></b></td><td><textarea name=acom cols=50 rows=3 class=\"fmText\">$comp</textarea></td></tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'Address'}:</span></b></td><td><input type=text class=\"fmEntry\" name=aaddr size=50 value=\"$addr\"></td></tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'City'}:</span></b></td><td><input type=text class=\"fmEntry\" name=acity size=30 value=\"$city\"></td></tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'State'}:</span></b></td><td><input type=text class=\"fmEntry\" name=astate size=30 value=\"$state\"></td></tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'Zip'}:</span></b></td><td><input type=text class=\"fmEntry\" name=azip size=20 value=\"$zip\"></td></tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'Country'}:</span></b></td><td><input type=text class=\"fmEntry\" name=acountry size=20 value=\"$country\"></td></tr>
 <tr><td align=right><b><span class=\"fmLabel\">$::phr{'Info'}:</span></b></td><td><textarea name=ainfo cols=50 rows=4 class=\"fmText\">$info</textarea></td></tr>
 <tr><td colspan=2><hr></td></tr>
 <tr><td colspan=2 align=center>
 <a href=\"#uu\"><img src=\"$::o{'imgdirurl'}/upper.gif\" width=25 height=16 border=0></a>&nbsp;";

    if($tag > 0) {
      print "<input type=submit name=action value=\"$::phr{'InsertAsNew'}\" class=\"fmBtnSt\">
             <input type=submit name=action value=\"$::phr{'Modify'}\" class=\"fmBtnSt\">
             <input type=submit name=action value=\"$::phr{'Delete'}\" class=\"fmBtnSt\">";
      print "<input type=hidden name=t value=\"$tag\">";
    } else {
      print "<input type=submit name=action value=\"$::phr{'Insert'}\" class=\"fmBtnSt\">
 <input type=submit name=action value=\"$::phr{'NextNew'}\" class=\"fmBtnSt\">";
    }
    print "
   <input type=submit name=action value=\"$::phr{'Cancel'}\" class=\"fmBtnSt\">
   </td></tr>
 <tr><td colspan=2><hr></td></tr>
 </table>
 </form>";
    print "</center>";
    &trailer(0,0);
  } elsif ($cmd eq 'dad') {
    if( $::d{'authResult'} != 4) {calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who).");}
    my $ac = $::calinfo{'action'};
    my ($insert, $key, $revision);
    if($ac ne "$::phr{'Delete'}") { $insert = 1;} else { $insert = 0;}
    if($ac eq "$::phr{'Delete'}" or $ac eq "$::phr{'Modify'}") {
      $tag = $::calinfo{'t'};
      for $href (@::addressbook) {
	if($href->{'tag'} == $tag) { $href->{'deleted'} = 1; last;}
      }
    }
    my $fhua = gensym;
    if(sysopen($fhua, "$afile", O_WRONLY | O_CREAT, 0644) ) {
      &webcalLock::doflock( \*$fhua, LOCK_EX,"$afile") or calerror("Cannot lock file '$afile': $!\n",1);
      truncate($fhua, 0);
      print $fhua '@::addressbook = (', "\n";
      for $href (@::addressbook) {
	  next if $href->{'deleted'};
	  $tmp=print1Address($href);
	  print $fhua "$tmp\n";
      }
      if($insert) {
	$count++;
	my %hash=();
	$hash{'fname'} = $::calinfo{'afname'};
	$hash{'lname'} = $::calinfo{'alname'};
	$hash{'hpage'} = $::calinfo{'ahpage'};
	$hash{'com'} = $::calinfo{'acom'};
	$hash{'phone'} = $::calinfo{'aphone'};
	$hash{'fax'} = $::calinfo{'afax'};
	$hash{'email'} = $::calinfo{'aemail'};
	$hash{'addr'} = $::calinfo{'aaddr'};
	$hash{'city'} = $::calinfo{'acity'};
	$hash{'state'} = $::calinfo{'astate'};
	$hash{'zip'} = $::calinfo{'azip'};
	$hash{'country'} = $::calinfo{'acountry'};
	$hash{'info'} = $::calinfo{'ainfo'};
	$hash{'tag'} = $count;
        if($hash{'fname'} ne "" or $hash{'lname'} ne "" or $hash{'phone'} or $hash{'com'} or $hash{'addr'}) {
	    my $tmp = print1Address(\%hash);
	    print $fhua "$tmp\n";
        }
      }
      $count++;
      print $fhua ");\n$count;\n";
      &webcalLock::doflock( \*$fhua, LOCK_UN,"$afile") or calerror("Cannot unlock file '$afile': $!\n",1);
      close($fhua);
       if($::calinfo{'action'} and $::calinfo{'action'} eq "$::phr{'NextNew'}") {
 	  $::calinfo{'t'} = 0;
 	  address('ead');
 	  myexit(0);
       }
      my $gaz=""; if($::calinfo{'az'}) { $gaz="&az=$::calinfo{'az'}";}      
      # generate acknowledge page
      &headers($::phr{'Acknowledgement'},undef,"1; URL=$::o{'cginame'}?c=ad&w=$who&ls=$ls&v=$view$gaz&d=$month/$day/$year$::vmg");
      print "<center><br>";
      print "<br><font color=#ff0000 size=+1><span class=\"miscTitleSmall\">$::phr{'AddressBookUpdated'}</span></font><br>";
      print "<table bgcolor=$webcalConfig::r{'dkbackground'} border=2 cellpadding=2><tr><td><a href=\"$::o{'cginame'}?c=ad&w=$who&ls=$ls&v=$view$gaz&d=$month/$day/$year$::vmg\">$::phr{'BackToAddressBook'}</a></tr></table>";
      print "<br>";
      print "<table  bgcolor=$webcalConfig::r{'dkbackground'} border=2 cellpadding=2><tr><td><a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$month/$day/$year$::vmg\">$::phr{'BackToCalendar'}</a></tr></table>";
      print "</center>";
      &trailer(0,0);
      myexit(0);
    } else { calerror("$::phr{'OpenFailed'}",1);}
  } else { calerror("$::phr{'Unknown_command'} $cmd",1); }
}

#=====================================================================================================
sub print1Address {
    my ($hash)=(@_);
    my ($k, $v, $msg, $tmp);
    if(! $hash->{'rev'}) {
	my @z = gmtime(time); 
	my $revision =sprintf "%4d%02d%02dT%02d%02d%02dZ", $z[5]+1900,$z[4]+1,$z[3],$z[2],$z[1],$z[0];
	$hash->{'rev'} = $revision;
    }
    $msg = "{\n";
    for $k (keys %$hash) {
	$v = $hash->{$k};
	$v =~ s/\\//g; $v =~ s/\'/\\\'/g; $v=~ s/^\s+|\s+$//g;  #strip out leading/trailing spaces 
	$msg .= "$k => \'$v\',\n";
    }
    $msg .= "},\n";
    return $msg;
}
#=====================================================================================================
sub add2addressbook {
    my ($who, $abook, $a, $msg, $tmp, $count, $href, $city, $state, $zip, $country);
    $who = untaintname($::d{'remote_user'},$::phr{'Invalidusername'});
    $abook = "$::o{'spooldir'}/$who/address";
    if( -f $abook) { $count = doReadFile("$abook");} else {$count = 1; @::addressbook =();}
    $msg = "";
    my ($toaddr) = (@_);
    $toaddr =~ s/^[ ]+//g; $toaddr =~ s/[, ]+$//g;
    my (@list) = split(/[ ,]+/, $toaddr);
    for $a (@list) {
	if(! inabook($a)) { 
	    my %hash=();
	    $hash{'fname'} = 'Unknown';	$hash{'lname'} = "";
	    $hash{'hpage'} = ""; $hash{'com'} = "";
	    $hash{'phone'} = ""; $hash{'fax'} = "";
	    $hash{'email'} = $a;
	    $hash{'addr'} = ""; $hash{'city'} = ""; $hash{'state'} = "";
	    $hash{'zip'} = "",	$hash{'country'} = "", 	$hash{'info'} = "";
	    $hash{'tag'} = $count;
	    $tmp = print1Address(\%hash);
	    $count++; $msg .= $tmp;
	}
    }
    if($msg) {
	my $fhub = gensym;
	if(sysopen($fhub, "$abook", O_WRONLY | O_CREAT, 0644) ) {
	    &webcalLock::doflock( \*$fhub, LOCK_EX,"$abook") or calerror("Cannot lock file '$abook': $!\n",1);
            truncate($fhub, 0);
	    print $fhub '@::addressbook = (', "\n";
	    for $href (@::addressbook) {
		my $tmp = print1Address($href);
		print $fhub "$tmp\n";		
	    }
	    print $fhub "$msg","\n";
	    print $fhub ");\n$count;\n";
	    &webcalLock::doflock( \*$fhub, LOCK_UN,"$abook") or calerror("Cannot unlock file '$abook': $!\n",1);
	    close($fhub);
	}
    }
}
sub inabook {
    my ($a) =(@_);
    my ($href, $email);
    for $href (@::addressbook) {
	$email = $href->{'email'};
	$email =~ s/^[\s]+//g; $email =~ s/[\s]$//g;
	if($a eq $email) {return 1;}
    }
    return 0;
}
#=====================================================================================================
sub hasdiary {
  my ($month, $day, $year, $rest, $arg, $who);
  if($::d{'megaCal'} ne "") {return 0;}
  ($who, $arg) = (@_);
  ($month, $day, $year, $rest) = split(/\//, $arg);
  if( -f "$::o{'spooldir'}/$who/$year/$month/$day") { return 1;}
  return 0;
}

sub diary { 
  my($cmd,$who, $month, $day, $year, $sdate, $notes, $file, $view, $tmp, $ls, $rwho, $rlevel, $mg, $dview);
  $who = $::calinfo{'w'}; $rwho = $who;

  if( $::d{'ispublic'} == 0 and $::d{'remote_user'} eq "" ) { # need authentication
    $sdate = $::calinfo{'d'};
    # send an authentication form
    requireLogin('diary', $sdate, "");
  }

  # 7/10/01 modify so that readers/editors of the calendar can read the diary
  $rlevel = 0;
  if( $::d{'ispublic'} == 0) {
      my $tmp; if($::calinfo{'pdiary'}) {$tmp= $::calinfo{'pdiary'};} else { $tmp = 0;}
      if($::d{'remote_user'} eq $who ) { $rlevel = 10;}
      elsif( $tmp > 0 and isre($::d{'remote_user'}, $who, 'editors') ) { $rlevel = 10;}
      elsif( $tmp > 2 or ($tmp > 1 and isre($::d{'remote_user'}, $who, 'readers')) ) { $rlevel = 1;}
  } else { $rlevel = 10;}
  
  if($rlevel == 0) { calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who)."); }
  
  if(defined $::calinfo{'mg'} and $::calinfo{'mg'} ne "") {$mg="&mg=$::calinfo{'mg'}";} else {$mg="";}
  
  if( $rlevel ) {
    $cmd = (@_)[0]; if($cmd eq 's') { $::d{'SATbs'}=1;}
    $view = $::calinfo{'v'};
    if($::calinfo{'vd'}) { $dview = 1;} else {$dview = $view;}
    $ls = $::calinfo{'ls'};
    $sdate = $::calinfo{'d'};
    ($month, $day, $year) = split(/\//, $sdate);
    ($month, $day, $year) = validateDate($month, $day, $year);

    #&make_style_sheet();       
    if($cmd ne 'w') {
	if(not $::calinfo{'pnt'}) {
	    my ($bscript, $clockscript) = &getClockScript();
	    my $body = $bscript;
	    my ($mm, $dd, $yy, $qscript);
	    if($cmd eq 'n') {$yy = $::now{'year'}; $mm = $::now{'month'}; $dd = $::now{'day'};}	    
	    else { $yy=$year; $mm=$month; $dd=$day;}
	    $qscript =<<END;
function qa(){q=window.open("$::o{'cginame'}?c=qa&w=$who&v=$view&ls=$ls&d=$mm/$dd/$yy&mg=$::calinfo{'mg'}","qa", "scrollbars=yes,resizable=yes,width=600,height=300");if(window.focus){q.window.focus(); }}
END
    ;
	    &headers($::phr{'Diary'}, $qscript . $clockscript,undef,1,1, $body);
	    my $headerForm=&newHeader('diary', 1);
	    print $headerForm;

	    # 7/10/01: add a navigation bar.
	    # 01/07/02: 
	    if(!($::vm & 0x8)) {
		my($rm, $rd, $ry, $rr, $wd, $dfname);
		print "<table width=\"$::o{'tw'}%\" border=0 cellpadding=0 cellspacing=0 bgcolor=\"#ffcc66\" class=\"dnbar\"><tr>";
		print "<td align=left noWrap height=16 width=\"2%\" class=\"dnbarTd\"><font size=1>&nbsp;</font></td>";
		print "<td align=center noWrap width=\"96%\" class=\"dnbarTd\"><font size=-2>";
		&ndbar('diary', $month, $day, $year,  $who, $view, $ls, $mg);
		print "</font></td>";
		print "<td align=right noWrap width=\"2%\" class=\"dnbarTd\"><font size=1>&nbsp;</font></td>";
		print "</tr>";
		print <<ENBD;
<tr><td colspan=3 bgcolor="#666633"><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=1 border=0></td></tr>
ENBD
    ;
		print"</table>";
	    }
	} else {
	    &headers($::phr{'Diary'}, "" ,undef,1,1, "onLoad=\"window.print()\"");
	}
    }
    
    if($cmd eq 'r') { #Read diary
	my ($fdate, $tdate, $fmonth, $fday, $fyear, $tmonth, $tday, $tyear, $m,$d, $y, $ndays, $i, $j, $dir, $tt, 
	    $tmon, $body, $qscript, $labelstr, $prevc, $nextc, $save, $pevent, $aper, $bper);
	my ($border);
	my $adjwidth = $::o{'tw'} - 8;
	if($::calinfo{'pnt'}){$border=1;}else{$border=0;} 
	$sdate = $::calinfo{'d'};
	if($::vm & 0x8000) {
	    if($dview != 4) {
		$save = $::d{'megaCal'}; delete $::d{'megaCal'}; &readData; if($save) {$::d{'megaCal'} = $save;} 
	    } else {
		my $file = "$::o{'spooldir'}/$who/data";
		doReadFile($file);
	    }
	    $pevent=1; 	$aper = "75%";
	} else {$pevent=0; $aper="100%";}
	if($::calinfo{'pnt'}) { $body = " onLoad=\"window.print()\"";}	else { $body="";}
	if($dview == 1) {
	    $fmonth=$tmonth = $month; $fday=$tday=$day; $fyear=$tyear=$year;
	    $labelstr = mdy_wstring($month,$day,$year);
	    $prevc = printDate0( $month, $day -1, $year); $nextc = printDate0( $month, $day +1, $year); 
	    $labelstr = "<span class=\"dvTitle\">$labelstr</span>"; 
	} elsif($dview == 2) {
	    my $wd = wday($month, $day, $year) -$::o{'weekstart'}; $wd = 6 if $wd < 0;    
	    ($fmonth, $fday, $fyear) = canDate($month, $day-$wd, $year);
	    ($tmonth, $tday, $tyear) = canDate($fmonth, $fday+7, $fyear);	    
	    $labelstr = "$::phr{'Week_starts_on'} ".mdy_string($fmonth,$fday,$fyear);
	    $prevc = printDate0( $month, $day -7, $year); $nextc = printDate0( $month, $day +7, $year);
	    $labelstr = "<span class=\"wvTitle\">$labelstr</span>"; 
	} elsif($dview == 3) {
	    $fmonth=$tmonth = $month; $fday=1;  $fyear=$tyear=$year;
	    if($month != 1) {$tday=$::mdays[$month];} else { if(isleap($year)) {$tday=29;} else {$tday=28;}}
	    $labelstr= "$::mname[$fmonth] $fyear\n";
	    $prevc = printDate0( $month-1, 1, $year); $nextc = printDate0( $month+1, 1, $year); 
	    $labelstr = "<span class=\"mvTitle\">$labelstr</span>"; 
	} else {
	    $fmonth=0; $tmonth = 11; $fday=1; $tday=31; $fyear=$tyear=$year;	    
	    $labelstr= "$fyear";	    
	    $prevc = printDate0( $month, 1, $year-1); $nextc = printDate0( $month, 1, $year+1); 
	    $labelstr = "<span class=\"yvTitle\">$labelstr</span>"; 
	}
	my ($zmonth, $zday, $zyear) = canDate($fmonth, $fday, $fyear);
	if($zmonth != $fmonth or $zday != $fday or  $zyear != $fyear){
	    calerror("$::phr{'invalid_date'}: [$fmonth/$fday/$fyear] != [$zmonth/$zday/$zyear]",1);
	}
	($zmonth, $zday, $zyear) = canDate($tmonth, $tday, $tyear);
	if($zmonth != $tmonth or $zday != $tday or  $zyear != $tyear) {
	    calerror("$::phr{'invalid_date'}: [$tmonth/$tday/$tyear] != [$zmonth/$zday/$zyear]",1);
	}
	if($fyear < 1990) {$fyear =1990;} elsif ($fyear > 2050) { $fyear=2050;}
	if($tyear < 1990) {$tyear =1990;} elsif ($tyear > 2050) { $tyear=2050;}
	
	$ndays = ndays($tmonth, $tday, $tyear, $fmonth, $fday, $fyear);
	if($ndays < 0) { $ndays = 1;}
	if(not $::calinfo{'pnt'}) {
	    $labelstr= <<END;
<a href="$::o{'cginame'}?c=diary&ls=$ls&w=$who&v=$dview&d=$prevc$mg$::vmg" class="transparent"><img src="$::o{'imgdirurl'}/rleft.gif" width=10 height=12 border=0></a>&nbsp;&nbsp;
<b>$labelstr</b>
&nbsp;&nbsp;<a href="$::o{'cginame'}?c=diary&ls=$ls&w=$who&v=$dview&d=$nextc$mg$::vmg" class="transparent"><img src="$::o{'imgdirurl'}/rright.gif" width=10 height=12 border=0></a>
</font>
END
    ;
	}
	print <<END;

<center>
<table border=0 cellspacing=1 cellpadding=0 width="$adjwidth%">
<tr><td width="55%" align=right><font color=red>$labelstr</font></td><td align=right width="45%">
<table border=0 cellpadding=0 cellspacing=0 class="diarySearch"><tr><td nowrap>
<Form name=diary action="$::o{'cginame'}" method=GET  class="searchform">$::vmp
<input type=hidden name=c value="sdiary">
<input type=hidden name=w value="$who">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=searchRange value="all">
<font size=1><span class="fmLabelSa">$::phr{'Search'}:</span></font>
<font size=1><input type=text size=10 maxlength=128 name=stopic value="" class="fmEntrySa"></font>
<font size=1><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font>
</form></td></tr></table>
</td></tr></table></center>

END
    ;
	
	print "<center>\n";
	($m, $d, $y) = ($fmonth, $fday, $fyear);
	($m, $d, $y) = validateDate($m, $d, $y);
	$dir= "$::o{'spooldir'}/$who";
	my $tentries = 0;
	for($i=0, $j=0; $i < $ndays; $i++) {
	    ($m, $d, $y) = canDate($m, $d, $y);
	    my $sevents=""; 
            $m=untaintname($m,"");$d=untaintname($d,"");$y=untaintname($y,"");
	    if( -f "$dir/$y/$m/$d") {
		$tentries++;
		$::diaryContent = '';
		doReadFile("$dir/$y/$m/$d");
		if($pevent) {
		    my $events = oneDaySummary($m, $d, $y, '1/1/1991', $webcalConfig::fontsize{'summary'}, 0);
		    if(not $events) { $events = "<b><span class=\"diaryEtTitle\">$::phr{'NoEvents'}</span></b><br><br>";}
		    else {
			$events = "<font color=#ff0000><b><span class=\"diaryEtTitle\">$::phr{'Events'}</span></b></font><br><br>$events";
		    }
		    $sevents = <<END;
<td width="24%">
  <table border=0 cellspacing=0 cellpadding=0 width="100%" bgcolor="#ffffff" class="diaryEtHolder">
   <tr><td bgcolor="#333333" width="100%" class="diaryEtHolderTd">
      <table width="100%" cellpadding=6 cellspacing=1 border=$border bgcolor="#333333" class="diaryEtTbl">
      <tr><td align=center bgcolor="#ccccee" class="diaryEtTd">$events</td></tr></table>
     </td>
    </tr>
  </table>
  </td>
END
    ;
		}
		$tmon = $m+1;
		my $content = wrapDiaryLines($::diaryContent,0);
		if($content eq "") { $content = "<br><br><br>";}
		my $mdystr = mdy_wstring($m, $d, $y);
		my ($editdiary, $printdiary)= ("", "");
		if(not $::calinfo{'pnt'}) {
		    $editdiary=<<EOF;
<a href="$::o{'cginame'}?c=ediary&ls=$ls&w=$who&v=$dview&d=$m/$d/$y$mg$::vmg"><font size=1 color="#666600"><span class="diaryEdit">$::phr{'Edit'}</span></font></a>
EOF
    ;
		    $printdiary=<<EOF;
<a href="$::o{'cginame'}?c=diary&pnt=1&ls=$ls&w=$who&v=1&d=$m/$d/$y" target=pnt><font size=1 color="#666600"><span class="diaryPrint">$::phr{'Print'}</span></font></a>
EOF
    ;
		}
		print <<END;
<table border=0 cellpadding=0 cellspacing=0 width="${adjwidth}%">
<tr><td colspan=3 width="100%" background="$::o{'imgdirurl'}/tbg.gif" class="diarytbarTd"><font color="#666600"><b><span class="diaryDate">&nbsp;$mdystr</span></b></font><img src="$::o{'imgdirurl'}/spacer.gif" width=40 height=1>$editdiary<img src="$::o{'imgdirurl'}/spacer.gif" width=40 height=1>$printdiary</td></tr>
 <tr><td height=10 colspan=2> <img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=6></td></tr>
 <tr valign=top>
  <td width="$aper">
  <table border=0 cellspacing=0 cellpadding=0 width="100%" bgcolor="#ffffff" class="diaryHolder">
   <tr><td bgcolor="#333333" width="100%" class="diaryHolderTd">
      <table width="100%" cellpadding=8 cellspacing=1 border=$border bgcolor="#333333" class="diaryCTbl">
         <tr><td bgcolor="#eeeecc" class="diaryTd">
            <blockquote><p class="diaryContent">$content</p></blockquote>
          </td></tr>
      </table>
     </td>
    </tr>
  </table>
  </td>
<td width=10 rowspan=2 align=left><img src="$::o{'imgdirurl'}/spacer.gif" width=2 height=1></td>
$sevents
</td></tr>
<tr><td colspan=2>&nbsp;</td></tr>
</table>
END
    ;
		$j++;
	    }
	    $d++;
	}
	if($tentries == 0) {
	    print "<br><br><b>No Entries Available.</b> To add a diary entry, click on the <b>'Add New Entry'</b> button on the navigation bar.";
	}
	print "</center>";
	&trailer(0,1);
    } elsif($cmd eq 's') {
	my($srange, $sfrom, $sto, $file, $view, $tmp, $stopic);$view=$::calinfo{'v'}; $ls=$::calinfo{'ls'};
	if(defined $::calinfo{'action'} and  $::calinfo{'action'} eq "$::phr{'Cancel'}") { &readData;  &calendar; myexit(0);}
	$stopic = $::calinfo{'stopic'};
	if(! $stopic) { calerror("$::phr{'SearchSubjectEmpty'}",1);}
	my ($border);
	if($::calinfo{'pnt'}){$border=1;}else{$border=0;} 
	my @searchwords = &buildMExpr($stopic);

	$srange = $::calinfo{'searchRange'};
	$sfrom = $::calinfo{'searchFrom'};
	$sto = $::calinfo{'searchTo'};

	my ($fdate, $tdate, $fmonth, $fday, $fyear, $tmonth, $tday, $tyear, $m,$d, $y, $ndays, $i, $j, $dir, $tt, $msg);
	if($srange eq 'all') {
	    $sfrom = $::calinfo{'searchFrom'} = '1/1/1999';
	    $sto = $::calinfo{'searchTo'} = '12/31/2050';
	}
	($fmonth, $fday, $fyear) = split(/\//, $sfrom); 
	($tmonth, $tday, $tyear) = split(/\//, $sto); 
	if(!$fmonth or !$fday or !$fyear or !$tmonth or !$tday or !$tyear) {
	    calerror("$::phr{'invalid_date'}: [$fdate] [$tdate]",1);
	}
	$tmonth--; $fmonth--;
	my ($zmonth, $zday, $zyear) = canDate($fmonth, $fday, $fyear);
	if($zmonth != $fmonth or $zday != $fday or  $zyear != $fyear) {
	    calerror("$::phr{'invalid_date'}: [$fmonth/$fday/$fyear] != [$zmonth/$zday/$zyear]",1);
	}
	($zmonth, $zday, $zyear) = canDate($tmonth, $tday, $tyear);
	if($zmonth != $tmonth or $zday != $tday or  $zyear != $tyear) {
	    calerror("$::phr{'invalid_date'}: [$tmonth/$tday/$tyear] != [$zmonth/$zday/$zyear]",1);
	}
	$ndays = ndays($tmonth, $tday, $tyear, $fmonth, $fday, $fyear);
	if($ndays < 0) { $ndays = 1;}
	if($::d{'ispublic'}) {$msg= " -- $::phr{'PublicCalendar'}";} else {$msg="";}

#	print "<center>";
#	print "<br><font color=#ff0000 size=+1><b><span class=\"miscTitle\">$::phr{'Search_Results'} ($who$msg)</span></b></font><br>";
	my $adjwidth = $::o{'tw'} - 8;
	print <<END;
<table border=0 cellspacing=0 cellpadding=0 width="$adjwidth%">
<tr><td width="55%" align=right><font color=red>
<b><span class="miscTitle">$::phr{'Search_Results'} ($who$msg)</span></b>
</font></td><td align=right width="45%">
<Form name=diary action="$::o{'cginame'}" method=GET  class="searchform">$::vmp
<input type=hidden name=c value="sdiary">
<input type=hidden name=w value="$who">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=searchRange value="all">
<font size=1><span class="fmLabelSa">$::phr{'Search'}:</span></font>
<font size=1><input type=text size=10 maxlength=128 name=stopic value="" class="fmEntrySa"></font>
<font size=1><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font>
</form></td></tr></table>
END
    ;


	($m, $d, $y) = ($fmonth, $fday, $fyear);
	($m, $d, $y) = validateDate($m,$d, $y);
	$dir= "$::o{'spooldir'}/$who";
	my $tentries = 0;
	my ($aper, $pevent);
	if($::vm & 0x8000) {
	    my $save = $::d{'megaCal'}; delete $::d{'megaCal'}; &readData; if($save) {$::d{'megaCal'} = $save;} 	
	    $pevent =1; $aper = "75%";
	} else { $pevent = 0; $aper = "100%";}
	
	for($i=0, $j=0; $i < $ndays; $i++) {
	    ($m, $d, $y) = canDate($m, $d, $y);
            $m=untaintname($m,"");$d=untaintname($d,"");$y=untaintname($y,"");
	    if( -f "$dir/$y/$m/$d") {
		$::diaryContent = '';
		doReadFile("$dir/$y/$m/$d");
		if( matchMExpr(\@searchwords, $::diaryContent)) {
		    $tentries ++;
		    my $sevents = "";
		    my ($editdiary, $printdiary)= ("", "");
		    my $content = wrapDiaryLines($::diaryContent,0);
                    $content = annotate(\@searchwords, $content);
		    my $mdystr = mdy_wstring($m, $d, $y);
		    if($pevent) {
			my $events = oneDaySummary($m, $d, $y, '1/1/1991', $webcalConfig::fontsize{'summary'}, 0);
			if(not $events) { $events = "<b><span class=\"diaryEtTitle\">$::phr{'NoEvents'}</span></b><br><br>";}
			else {
			    $events = "<font color=#ff0000><b><span class=\"diaryEtTitle\">$::phr{'Events'}</span></b></font><br><br>$events";
			}
			$sevents = <<END;
<td width="24%">
  <table border=0 cellspacing=0 cellpadding=0 width="100%" bgcolor="#333333">
   <tr><td bgcolor="#333333" width="100%">
      <table width="100%" cellpadding=6 cellspacing=1 border=$border bgcolor="#333333" class="diaryEtTbl">
      <tr><td align=center bgcolor="#ccccee" class="diaryEtTd">$events</td></tr></table>
     </td>
    </tr>
  </table>
  </td>
END
    ;
		    }
		    if(not $::calinfo{'pnt'}) {
			$editdiary=<<EOF;
<a href="$::o{'cginame'}?c=ediary&ls=$ls&w=$who&v=$dview&d=$m/$d/$y$mg$::vmg"><font size=1 color="#666600"><span class="diaryEdit">$::phr{'Edit'}</span></font></a>
EOF
    ;
			$printdiary=<<EOF;
<a href="$::o{'cginame'}?c=diary&pnt=1&ls=$ls&w=$who&v=1&d=$m/$d/$y" target=pnt><font size=1 color="#666600"><span class="diaryPrint">$::phr{'Print'}</span></font></a>
EOF
    ;
		    }
		    my $adjwidth = $::o{'tw'} - 8;

		    print <<END;
<table border=0 cellpadding=0 cellspacing=0 width="${adjwidth}%">
 <tr><td colspan=3 width="100%" background="$::o{'imgdirurl'}/tbg.gif" class="diarytbarTd"><font color="#666600"><b><span class="diaryDate">&nbsp;$mdystr</span></b></font>
  <img src="$::o{'imgdirurl'}/spacer.gif" width=40 height=1>$editdiary
  <img src="$::o{'imgdirurl'}/spacer.gif" width=40 height=1>$printdiary</td></tr>
  <tr><td height=10 colspan=2> <img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=6></td></tr>
 <tr valign=top>
  <td width="$aper">
  <table border=0 cellspacing=0 cellpadding=0 width="100%" bgcolor="#333333">
   <tr><td bgcolor="#333333" width="99%">
      <table width="100%" cellpadding=8 cellspacing=1 border=$border bgcolor="#333333" class="diaryCTbl"><tr>
<td bgcolor="#eeeecc" class="diaryTd"><blockquote><span class="diaryContent">$content</span></blockquote></td></tr></table>
     </td>
    </tr>
  </table>
  </td>
<td width=10 rowspan=2 align=left><img src="$::o{'imgdirurl'}/spacer.gif" width=2 height=1></td>
$sevents
</td></tr>
<tr><td colspan=2>&nbsp;</td></tr>
</table>
END
    ;
		}
	    }
	    $d++;
	}
	if($tentries == 0) {  print "<br><br><b>No Match found.</b>";}
	print "</center>";
	&trailer(0,0);
    } elsif($cmd eq 'e' or $cmd eq 'n') { # read and edit current diary file
      my ($events, $evtmp, $tpercent);
      $::diaryContent = '';
      if($cmd eq 'n') {$year = $::now{'year'}; $month = $::now{'month'}; $day = $::now{'day'};}
      $year = untaintname($year, ""); $month = untaintname($month, ""); $day = untaintname($day, "");
      $file = "$::o{'spooldir'}/$who/$year/$month/$day";
      if( -f $file) { doReadFile($file);}
      # create form
      $tmp = mdy_nstring($month+1, $day, $year);
      &readData;  $events = oneDaySummary($month, $day, $year, '1/1/1991', $webcalConfig::fontsize{'summary'}, 0);
      if($events) { 
          $tpercent=76;
          $evtmp="<td rowspan=2 valign=top width=\"20%\" bgcolor=$webcalConfig::r{'dkbackground'}><br><font color=#ff0000><b><span class=\"miscTitleSmall\">$::phr{'Events'}</span></b></font><br><font size=-1><span class=\"miscTitleSmall\">$tmp</span></font><br><br>$events</td>";
      } else { $evtmp = ""; $tpercent=96;}

      print "<center>";
      if(($::d{'authResult'} | $::d{'ispublic'}) < 4 or $::d{'validuser'} == 0) {
          print "<font color=#999900><b><span class=\"authWarn\">$::phr{'AuthRequired'}!</span></b></font>";
      }

      my ($upload, $uscript)=("",""); 
      if($::o{'allowImageUpload'}
) {
	  my $iurl="$::o{'cgiupload'}?c=ui&w=$who";
	  $upload = "<a href=\"Javascript:openpopup(\'$iurl\','uls',500,400)\"><font size=1 color=#0000cc><span class=\"iupload\">$::phr{'IUpload'}</span></font></a>&nbsp;";
      }
      my $repos = "$::o{'imgdir'}/$::o{'uploadsubdir'}";
      my @list= listImgDirContents($repos, 1);
      if (scalar @list) {
	  my $surl="$::o{'cginame'}?c=simage&imgoffset=0&w=$who&the_form=webcaldiary&the_elt=diaryc";
	  $upload .= "&nbsp;&nbsp;<a href=\"Javascript:openpopup(\'$surl\','imgs',500,600)\" style=\"color:green;background-color:#cccc00\"><font size=1><span class=\"iselect\">$::phr{'UsableImgs'}</span></font></a><br><br>";
      }
      print <<END;
<Form name=webcaldiary action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value="wdiary">
<input type=hidden name=v value=$dview>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$sdate">
<input type=hidden name=w value="$who">
<table width="$::o{'tw'}%" border=0 cellspacing=2 cellpadding=0><tr><td align=center width=$tpercent%>
<table border=0 cellspacing=0 cellpadding=0>
<tr>
<td><b><span class="fmLabel">$::phr{'Date'}:</span></b>&nbsp;<input type=text size=16 name=sdate value="$tmp" class="fmEntry">
END
    ;
      print linkSmallCal("webcaldiary.sdate",$who,$month,$year);
      print <<END;
&nbsp;&nbsp;$upload</td>
<td align=right>$::o{'qadd'}</td>
</tr>
<tr><td><font size=1><span class="fmLabelS">Supported HTML tags: &lt;b&gt;, &lt;i&gt;, &lt;u&gt;, &lt;br&gt;, &lt;font&gt;, &lt;p&gt; and &lt;pre&gt;</span></font></td></tr>
<tr><td colspan=2><textarea name=diaryc wrap=physical cols=60 rows=18 class="fmText">$::diaryContent</textarea></td></tr>
</table>
</td>
$evtmp
</tr>
<tr><td align=center>
END
    ;

    if($rlevel > 1) {
      if($::diaryContent) {
	print "<b><input type=submit name=action value=\"$::phr{'Insert'}\" class=\"fmBtnSt\"></b>";
	print "<b><input type=submit name=action value=\"$::phr{'Modify'}\" class=\"fmBtnSt\">
             <input type=submit name=action value=\"$::phr{'Delete'}\" class=\"fmBtnSt\"></b>";
      } else {
	print "<b><input type=submit name=action value=\"$::phr{'Insert'}\" class=\"fmBtnSt\"></b>";
      }
       print "<b><input type=submit name=action value=\"$::phr{'Cancel'}\" class=\"fmBtnSt\"></b>";
  } else {
      print "<b><input type=button value=\"$::phr{'GoBack'}\" onclick=\"javascript:history.go(-1)\" class=\"fmBtnSt\"></b>";
  }
      print "
</td></tr>
</table>
</form>";
      print "</center>";
      &trailer(0,0);
  } elsif($cmd eq 'w') { # write to diary file
      if($rlevel <= 1) { calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who)."); }
      my $ac = $::calinfo{'action'};
      if($ac eq  "$::phr{'Cancel'}") { &readData; &diary('r'); myexit(0);}
      $sdate = $::calinfo{'sdate'};
      ($month, $day, $year) = split(/\//, $sdate); 
      if(!$month or !$day or !$year) { calerror("$::phr{'invalid_date'}: $sdate",1);}
      if($year < 100) { if($year >= 90) {$year += 1900;} else {$year += 2000;}}
      $month--; $day = 0+$day; $year= 0+$year;
      my ($zmonth, $zday, $zyear) = canDate($month, $day, $year);
      if($zmonth != $month or $zday != $day or  $zyear != $year) {calerror("$::phr{'invalid_date'}: [$month/$day/$year] != [$zmonth/$zday/$zyear]",1);}
      ($month, $day, $year) = validateDate($month, $day, $year);
      $who = untaintname($who, "");$year = untaintname($year, "");$month = untaintname($month, "");$day = untaintname($day, "");
      $file = "$::o{'spooldir'}/$who/$year/$month/$day";
      if($ac eq "$::phr{'Cancel'}") {  &readData;  &calendar; myexit(0);}
      elsif($ac eq "$::phr{'Delete'}") {
	if( -f $file) {unlink $file;}
	acknowledge($who,$dview,$ls, "$month/$day/$year",$::phr{'DiaryUpdated'});
      } else {
	my ($dira, $dirb, $ok, $err);
	$ok = 1; $err="";
	$who = untaintname($who, ""); $year = untaintname($year, "");
	$dira = "$::o{'spooldir'}/$who/$year";
	if( ! -d $dira) { $ok = mkdir($dira, 0711);}
	if($ok) {
	  $month = untaintname($month, "");
	  $dirb = "$dira/$month";
	  if( ! -d $dirb) { $ok = mkdir($dirb, 0711);}
	  if(!$ok) { $err = "$!";}
	} else {$err = "$!";}
	if(!$ok) { calerror($err);}

	if( $ac eq "$::phr{'Insert'}" and  -f "$file") {
	    my $tstr = mdy_string($month, $day, $year);
	    calerror("There is already a diary entry for $tstr. If you want to replace this entry, please
go back and click on the <font color=#0000ff><b>$::phr{'Modify'}</b></font> button to override.", 1);
	}
	my $fhz = gensym;
	if(sysopen($fhz, "$file", O_WRONLY | O_CREAT, 0644 ) ) {
          &webcalLock::doflock( \*$fhz, LOCK_EX,"$file") or calerror("Cannot lock file '$file': $!\n",1);
          truncate($fhz, 0);
	  my $ddcc= $::calinfo{'diaryc'};
	  $ddcc =~ s/\\//g; $ddcc =~ s/\'/\\\'/g;
	  print $fhz "\$::diaryContent=\'";
	  print $fhz $ddcc;
	  print $fhz "\';\n1;";
          &webcalLock::doflock( \*$fhz, LOCK_UN,"$file") or calerror("Cannot unlock file '$file': $!\n",1);
	  close $fhz;
	  my $msg;
	  if($::d{'ispublic'}) {$msg= "$::phr{'DiaryUpdated'}" . "$::phr{'PublicCalendar'}";}
	  else {$msg= "$::phr{'DiaryUpdated'}"};
	  acknowledge($who,$dview, $ls,"$month/$day/$year",$msg, 'diary');
	} else { calerror("$::phr{'OpenFailed'} ($file)",1);}
      }
  }
 } else {
      calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who) <br> $::phr{'errorPerm'}");
  }
}

sub wrapDiaryLines {
    my ($in,$brk) = (@_);
    $in =~ s/\n\s*\n/<br><br>/g;
    $in =~ s/&quot;/\"/gi; #"

    if( $in =~ /^s*&lt;\s*html\s*&gt;/i) { $brk = 0;}
    if($brk) { $in =~ s/\n/<br>/g;}
#    if($brk) {
#	my $i=0;
#	$in =~ s{(.)}{
#	    if ($i >=80 and ($1 eq ' ' or $1 eq '\n' or $1 eq '\t')) { $i=0; ' <br>'}
#	    else { $i++; $1}
#	}gsex;
#    }
    $in =~ s/&lt;(\/?)(b|p|pre|i|u|blockquote|br|strike|font|a|img|html|h1|h2|h3|ul|li|ol)(.*?)&gt;/<$1$2$3>/gi;
    return  &substImages($in);
}
sub validateDate {
  my ($m, $d, $y) = (@_);
       if ($m =~ /^([0-9]*)$/) {
         $m = $1;
       } else {
         calerror( "$::phr{'invalid_date'}",1);
       }
       if ($d =~ /^([0-9]*)$/) {
         $d = $1;
       } else {
         calerror( "$::phr{'invalid_date'}",1);
       }
       if ($y =~ /^([0-9]*)$/) {
         $y = $1;
       } else {
         calerror( "$::phr{'invalid_date'}",1);
       }
  return($m, $d, $y);
}
#=====================================================================================================
sub acknowledge {
  my($who, $view, $ls, $d, $msg, $cmd)=(@_);
  if(! $cmd) { $cmd = 'get';}
  my $extra;
  if($::calinfo{'exf'}) { $extra=$::calinfo{'exf'};} else {$extra = "";}
  &headers($::phr{'Acknowledgement'},undef,"1; URL=$::o{'cginame'}?c=$cmd$extra&ls=$ls&w=$who&v=$view&d=$d$::vmg");
  print "<center><br>";
  print "<br><font color=#ff0000><span class=\"msg\">$msg</span></font><br>";
  print "<table bgcolor=$webcalConfig::r{'dkbackground'} border=2 cellpadding=2><tr><td><a href=\"$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=$view&d=$d$::vmg\">$::phr{'BackToCalendar'}</a></tr></table>";
  print "</center>";
  &trailer(0,0);
}

sub ackpopup {
    my ($msg) = (@_);
    if( ! $::phr{'GoBack'}) { &loadLangfile;}
    &headers("WebCalendar Acknowledge"," ",undef,1);
    print "<center><br>&nbsp;<br><br>";
    print "<table cellspacing=0 cellpadding=2 border=0 bgcolor=#009900><tr><td>";
    print   "<table width=460 bgcolor=#eeeeff border=0 cellpadding=12 cellspacing=0><tr><td>";
    print   "<font color=#ff0000 size=2><b><span class=\"errorMsg\">$msg</span></b></font><br>";
    print   "</td></tr></table>";
    print "</td></tr></table>";
    print "<br><br>";
    print "<form><table border=0><tr><td><b><input type=button value=\"$::phr{'Close'}\" onClick=\"self.close()\" class=\"fmBtnSt\"></b></td></tr></table></form></br>";
    print "</center>";
    &trailer(0,0);
    myexit(0) ;
}
#=====================================================================================================
sub prepareCookie {
  my ($name, $value, $path, $domain, $remember) = (@_);
  my $tmp = "Set-Cookie: $name=".urlencode($value);
  $tmp .= "; path=$path" if ($path);
  $tmp .= "; domain=$domain" if ($domain);
  if($remember) {$tmp .= "; expires=Thursday, 31-Dec-2037 00:00:00 GMT;";}
  return "$tmp\n";
}
#=====================================================================================================
sub killCookie {
  my ($name, $value, $path, $domain) = (@_);
  my $tmp = "Set-Cookie: $name=".urlencode($value);
  $tmp .= "; path=$path" if ($path);
  $tmp .= "; domain=$domain" if ($domain);
  if( $ =~ m/MSWin|NT/i ) { $tmp .= "; expires=Thursday, 31-Dec-2037 00:00:00 GMT;";}
  else { $tmp .= "; expires=Saturday, 01-Jan-2000 00:00:00 GMT;";}
  return "$tmp\n";
}
#=====================================================================================================
sub getCookies {
  my $cookies=$ENV{'HTTP_COOKIE'};
  my %cookies = ();
  if(defined $cookies) {
      my(@cookies) = split (/; /, $cookies); # cookies are name=value; (separated by ; )
      my($key, $value, %cookies);
      foreach(@cookies) {
	  ($key, $value) = split (/=/,$_,2);
	  $cookies{$key} = $value;
      }
      return \%cookies;
  }
  return \%cookies;
}
#=====================================================================================================
sub readCookie {
  my ($name) = (@_);
  if(defined $name and $name ne "") {
      my $href = getCookies();
      my $value = $href->{$name};
      return urldecode($value,0) if (defined $value);
  }
  return undef;
}
#=====================================================================================================
sub cookieLogout {
    my ($scriptname) = (@_);
    my $oldname = $scriptname;
    $scriptname =~ s/[^\/|\\]+$//g; #cookie is set on the directory
    my $cookie = killCookie('wcalusername', "x", $scriptname, "");
    $cookie .= killCookie('wcalpassword', "x", $scriptname, "");
    $cookie .= killCookie('wcalusername', "x", $oldname, "");
    $cookie .= killCookie('wcalpassword', "x", $oldname, "");
    $::authCookie .= $cookie; $::vm=0; $::vmp=$::vmg=$::vmc="";
    &cookieLogin("","$::phr{'You_ve_logout'}", "");
}
#=====================================================================================================
sub cookieLogin {
  my ($uname, $msg, $cmd) = (@_);
  my ($body, $setup, $cals);

  if($msg ne "") {$msg = "<tr><td nowrap width=\"100%\" colspan=2><font color=#ff0000><b>$msg</b></font></td></tr>";}
  if($uname eq "") {
      $body = 'onload="document.login.uname.focus();"';
  } else {
      $body = 'onload="document.login.pswd.focus();"';
  }

  &headers("Web Calendar",undef, undef,1,undef,$body);
  if($::calinfo{'c'} eq 'option') { $setup = "<input type=hidden name=c value=option>";} else {$setup="";}
  $cals=""; 
  if($::calinfo{'calendar'}) {$cals="<input type=hidden name=calendar value=\"$::calinfo{'calendar'}\">";}

  if($cmd eq "clogina") {
      print <<END;
<br>
<center>
<Form action="$::o{'cginame'}" name="login" method=POST>$::vmp
<input type=hidden name=c value=clogina>$cals
<font size="+1" color="#0000aa"><b><span class="miscTitle">$::phr{'WelcomeToWebCalendar'}</span></b></font><br><br>
<table border=0 width="100%" cellspacing=2 cellpadding=2>
<tr><td width="100%">
<table border=0 width=350>
<span class="msg">$msg</span>
<tr><td width="20%" align=right><b><span class="fmLabel">$::phr{'Calendar'}:</span></b></td><td width="60%"><input type=text size=20 value="$uname" name="uname" class="fmEntry"></td></tr>
<tr><td width="20%" align=right><b><span class="fmLabel">$::phr{'Password'}:</span></b></td><td width="60%"><input type=password size=20 value="" name="pswd" class="fmEntryP" onChange="javascript:document.login.submit()"></td></tr>
<tr><td>&nbsp;</td><td>&nbsp;&nbsp;<b><input type=submit name=action value=" $::phr{'login'} " class="fmBtnSt">
&nbsp;&nbsp;&nbsp;<input type=button value="$::phr{'Close'}" onClick="self.close()" class="fmBtn"></b></td></tr>
</table>
</td></tr>
</table>
</form>
</center>
END
    ;  
  } else {
  my $rememberpswd="checked"; if($webcalConfig::r{'forget_password'}) { $rememberpswd="";}
  print <<END;
<br>
<center>
<font size="+1" color="#0000aa"><b><span class="miscTitle">$::phr{'WelcomeToWebCalendar'}</span></b></font><br><br>
<table border=0 width="70%" cellspacing=2 cellpadding=2>
<tr><td width="100%" align=left colspan=2 bgcolor="#ccccff"><font color=blue><b><span class="greetingInstruction">$::phr{'olduserInstruction'}</span></b></font></td></tr>
<tr><td width="100%">
<Form action="$::o{'cginame'}" name="login" method=POST>$::vmp
<input type=hidden name=c value=clogin>$cals
$setup
<table border=0 width=400>
$msg
<tr><td width="20%" nowrap align=right><b><span class="fmLabel">$::phr{'CalendarName'}:</span></b></td><td width="60%"><input type=text size=20 value="$uname" name="uname" class="fmEntry"></td></tr>
<tr><td width="20%" nowrap align=right><b><span class="fmLabel">$::phr{'Password'}:</span></b></td><td width="60%"><input type=password size=20 value="" class="fmEntryP" name="pswd" onChange="javascript:document.login.submit()"></td></tr>
<tr><td align=right><input type=checkbox name=rememberit $rememberpswd class="fmRadioS"></td>
<td width="60%"><span class="fmLabelS">$::phr{'RememberIDPswd'}</span></td></tr>
<tr><td>&nbsp;</td><td align=center><b><input type=submit name=action value=" $::phr{'login'} " class="fmBtnSt"></b></td></tr>
</table></td><tr>
</form>
<tr><td><p>&nbsp;</td></tr>
<tr><td width="100%" align=left colspan=2 bgcolor="#ccccff"><font color=blue><b><span class="greetingInstruction">$::phr{'newuserInstruction'}</span></b></font></td></tr>
<tr><td align=center><a href="$::o{'cginame'}?c=signup"><font size=+1><b><span class="miscTitleSmall">$::phr{'signup'}</span></b></font></a></td></tr>
</table>
</center>
END
}
  &trailer(0,0);
}

#=====================================================================================================
# return the pair ($username, $magic)
#
sub cookieAuth {
  my ($unameI, $pswdI, $cmd) = (@_);
  my ($result,$magic,$message, $status) =("","","","");
  if($unameI eq 'anonymous' and $cmd ne "clogina") { return('anonymous', "ok");}
  if($unameI ne 'anonymous' and $unameI ne "") {
      $unameI = mychop($unameI); $pswdI = mychop($pswdI);
      ($status, $message) = &webcalAuth::VerifyPlainPassword($unameI, $pswdI);
      if($status) {$result = $unameI; $magic=&webcalAuth::CryptPlainPassword($pswdI, $message, $unameI);}
  }
  if($result eq "") {
      if($message ne "") { $result = $message; }
      $result .= "<br>";
      cookieLogin($unameI, $result, $cmd);
      myexit 0;
  }
  # succeed.
  return ($result, $magic);
}
#=====================================================================================================
sub vlogin { # verify login
    my $who = $::calinfo{'w'};
    if($::d{'remote_user'} eq "" and $webcalConfig::r{'cookieAuth'} ) {
        &loadLangfile;
        cookieLogin($who,"$::phr{'PleaseLogin'}", "");
        myexit(0);
    }
  }
#=====================================================================================================
sub popack {
    my $body = "onload=\"window.opener.history.go(-1); self.close();\"";
    &headers("Web Calendar",undef,undef,0,0, $body);
    print <<END;
<center>
<font size=+1><b><br><br>
<form><input type=button value="$::phr{'Close'}" onClick="self.close()" class="fmBtn"></form>
</b></font>
END
    &trailer(0,0);
}
#=====================================================================================================
sub gettimespec {
    my ($theE) = (@_);
    my ($da, $st, $du, $oc, $re);
    $da= $theE->{'date'}; $st= $theE->{'start'};
    if($theE->{'duration'}){$du=$theE->{'duration'};} else {$du=0;};
    if($theE->{'occurs'}){$oc=$theE->{'occurs'};} else {$oc="OneTime";};
    if($theE->{'repeat'}) {$re=$theE->{'repeat'};} else {$re=0;}
    return "$da/$st:$du/$oc/$re"; 
}

sub doimport {
    my ($tcal, $dir, $cal, @cals, $who, $tag, $theE, $href, $gprivacy, $eprivacy, $msg, $tmp, $pcal, $ical, $gcal, $ccal, $acal);
    my ($view, $ls, $d, $ncals, $first, $i, $self, $toall); my $inpopup = $::calinfo{'inpopup'};
    $who = $::calinfo{'w'};
    $tcal = $::calinfo{'tcal'};
    $tcal =~ s/[,; ]+/:/g; $tcal =~ s/:$//g;
    @cals = split(/:/, $tcal);
    $ncals = 0+@cals; $self=0; $toall = 0;
    # remove $who. There is no need to import the same event back to itself.
    for($i=0; $i<$ncals; $i++) { if($cals[$i] eq $who) { splice @cals, $i, 1; $ncals -= 1;  $self=1; last;}} 
    if($::o{'corporate_calendar'}) {
	for($i=0; $i<$ncals; $i++) {
	    if(ismember($cals[$i], $::o{'corporate_calendar'})) {
		$cals[0] = $cals[$i]; $ncals=1; $toall = 1; last;
	    }
	}
    }

    if($ncals > 0) {
	$view = $::calinfo{'v'};
	$ls = $::calinfo{'ls'};
	$d = $::calinfo{'d'};
	($gprivacy, $tmp) = getPrivacy(0);
	$tag = $::calinfo{'t'};
	$theE = undef;
	&readData();
	for $href (@::caldata) {
	    if($href->{'key'} == $tag) {
		if($gprivacy > 2) { $eprivacy = 3;}	#authorized editor or self
		else {
		    if($href->{'privacy'}) {$tmp = $href->{'privacy'}; $eprivacy = $::privacyTable{$tmp} - 1;}
		    else {$eprivacy = $gprivacy;}
		}
		$theE = $href;
		last;
	    }
	}
	if(not $theE or $eprivacy < 3) { calerror("Cannot read event $tag on calendar $who",1);}

	my @theEvent=();
	$theE = copyTask($theE);
	push @theEvent, $theE;
	# do import
	$pcal = $ical = $gcal = $ccal = $acal = "";
	my  ($isadm, @keys, $cnt, $ee, $key, $flag, $matched);
	$isadm = isadmin($::d{'remote_user'});
	@keys = ('kind', 'date', 'start', 'duration', 'occurs',  'repeat', 'what', 'detail');
	$first = $cals[0];	
	if($ncals <= 1 and ! $toall) { # import to one calendar 
	    if($::o{'dependency'}) {	    
		my $dependants = getdependants($first); 
		if($dependants) {
		    push @cals, split(/:/, $dependants);
		    $ncals = 0+@cals;
		}
	    }
	}
	if($ncals > 1) { # import to multiple calendars
	    for $tcal (@cals) {  $cal = untaintname($tcal,$::phr{'Invalidusername'});}
	    my ($omega, $ow, $osmtgp) = ($::d{'megaCal'}, $::calinfo{'w'}, $::calinfo{'smtgp'});
	    $::d{'megaCal'} ="";   $::calinfo{'w'} = $first;
	    $::calinfo{'smtgp'} = join(":", @cals);
	    my($amsg, $imsg) = importwork($first, \@theEvent, 0);
	    my $timeout=10; $timeout = 30 if $imsg;
	    &headers($::phr{'Acknowledgement'},undef,
		     "$timeout; URL=$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$d$::vmg",1);
	    print "<br><br><center><table border=1><tr><td>";
	    print "<font color=#00cc00><span class=\"warnMsg\">$amsg</span></font><br><br>";
	    if($imsg) { 
		print "</td></tr><tr><td>";
		print "<b><span class=\"warnMsg\">$::phr{'AlreadyOnCalendar'}</span></b>";
		print "<br><font color=#000099><span class=\"warnMsg\">$imsg</span></font><br>";
	    }
	    print "</td></tr></table>\n<br><br>";
	    print "<table border=2 bgcolor=$webcalConfig::r{'dkbackground'} cellpadding=2><tr><td><a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$d$::vmg\">$::phr{'BackToCalendar'}</a></tr></table>";
	    &trailer(0,0);	    
	} else { # import to one calendar only.
	    $cal = untaintname($first,$::phr{'Invalidusername'});
	    next if $cal eq $who;
	    next if $cal =~ /\//;
	    $dir="$::o{'spooldir'}/$cal";
	    if( -f "$dir/data" and -f "$dir/info") {
		$matched = 0; my $ict=getinfo($cal, 'ctype');
		if( $isadm or isvgadmin($::d{'remote_user'}, $cal) or
		    isre($::d{'remote_user'}, $cal, 'editors') or ($ict and $ict =~ 'public')) { 
		    $cnt = doReadFile( "$dir/data");
		    for $ee (@::caldata) {
			$flag = 1;
			for $key (@keys)  { if($ee->{$key} ne $theE->{$key}) { $flag = 0; last;}}
			if($flag) {$matched = 1; last;}
		    }
		    if($matched == 0) { 
			my $addit = 1;
			if($theE->{'kind'}  & 1) { # check time conflict for appointment and meeting events
			    delete $::calinfo{'ol'};  delete $::calinfo{'dcs'}; 
			    doReadFile( "$dir/info");
			    my $dcs = $::calinfo{'dcs'};
			    if($dcs or ($::calinfo{'ol'} and $::calinfo{'ol'} > 1)) {
				my $others = ""; if($dcs) { $others="$dcs:$tcal"};
				my $timespec = &gettimespec($theE);
				my $cmsg = checkOverlap($timespec,$others, $tcal, 0, $theE->{'what'});
				if($cmsg) { $addit = 0;}
			    }
			}
			if($addit) {
			    $cnt++; $theE->{'key'} = $cnt; $cnt++;
			    if($toall) {
				if($theE->{'seq'}) { $theE->{'seq'} = "C" . $theE->{'seq'}; }
				else { $theE->{'seq'} = "C" . time;}
				delete $theE->{'attendants'};
			    }
			    push @::caldata, $theE;
			    my $fhtz = gensym;
			    if(sysopen($fhtz, "$dir/data", O_WRONLY | O_CREAT, 0644 ) ) {
				&webcalLock::doflock( \*$fhtz, LOCK_EX, "$dir/data") or calerror("Cannot lock file '$cal/data': $!\n",1);
				truncate($fhtz, 0);
				print $fhtz "\@::caldata = (\n";
				for $href (@::caldata) {
				    $tmp = print1Entry($href);
				    print $fhtz $tmp;
				}
				print $fhtz ");\n$cnt;\n";
				&webcalLock::doflock( \*$fhtz, LOCK_UN, "$dir/data") or calerror("Cannot unlock file '$cal/data': $!\n",1);
				close $fhtz;	
				if($toall) { my @vevents=($theE); insert_to_all(\@vevents, $who);}
			    }
			    $gcal = "$tcal";
			} else {$ccal = "$tcal"; }
		    } else {  $acal = "$tcal";}
		} else {
		    $pcal .= "$tcal";
		}
	    } else { $ical  .= "$tcal";}
	}
	if($gcal) {$msg .= "$::phr{'UpdatedOK'}: <b>$gcal</b><br>";}
	if($pcal) {$msg .= "$::phr{'errorPerm'}: <b>$pcal</b><br>";}
	if($ical) {$msg .= "$::phr{'Invalidcalendarname'}: <b>$ical</b><br>";}
	if($acal) {$msg .= "Event is already on calendar: <b>$acal</b><br>";}
	if($ccal) {$msg .= "Rejected due to time conflict: <b>$ccal</b><br>";}
	if($pcal or $ical or $ccal) {calerror($msg,$inpopup?-1:1);}
	elsif($inpopup) {
	    &headers("");
	    print <<END;
<br><br><center>
$msg
<br><br>
<form><table border=0><tr><td><b><input type=button value="$::phr{'Close'}" onClick="self.close()" class="fmBtnSt"></b></td></tr></table></form>
</center>
END
    ;
	    &trailer(0,0);
	} else {acknowledge($who, $view, $ls, $d, $msg); }
    } elsif($self) {
	calerror("Import: event is already on your calendar.",$inpopup?-1:1);	
    } else { 
	calerror("Import: no calendar was selected.",$inpopup?-1:1);
    }
}
#=====================================================================================================

sub mailto {
    my ($cmd, $who, $view, $month, $day, $year, $hour, $min, $name, $author, $theevent, $ls, $date, $kind, $junk, $mform, $mg);
    my ($gprivacy, $eprivacy, $privacy, $tag, $mme, $href, $msg, $vcal, $uvcal, $email, $mname, $tmp, $maillist, $noimport, $seq);
    my ($invitee_addresses) = ("","");
    $who = $::calinfo{'w'};    $view = $::calinfo{'v'};    $ls = $::calinfo{'ls'};
    $month= $::calinfo{'month'};  $day  = $::calinfo{'day'};  $year = $::calinfo{'year'};
    $hour = $::calinfo{'hour'};    $min  = $::calinfo{'min'};
    $name = $::calinfo{'dname'}; $name = $::calinfo{'name'} unless $name;   $name = $who unless $name;
    $author= $::d{'ceditor'};
    $tag=$::calinfo{'t'};  
    if($::calinfo{'to_new_invitee_only'}) { $invitee_addresses = $::calinfo{'new_invitee_addresses'};}
    elsif($::calinfo{'invitee_addresses'}) {$invitee_addresses = $::calinfo{'invitee_addresses'};}
    elsif($::calinfo{'toauthor'}) { $invitee_addresses =$::calinfo{'toauthor'}; }
    $privacy="";
    $date = printDate($month, $day, $year);

    ($cmd, $noimport, $mform) = (@_);  # if $noimport is set, don't display VCALENDAR
    &readData();
    $theevent=undef;

    ($gprivacy, $junk) = getPrivacy(0);
    my $inpopup="";if($::calinfo{'inpopup'}) { $inpopup="<input type=hidden name=inpopup value=1>";} 
    #if($::calinfo{'dmode'}){$::calinfo{'inpopup'}=1;}
    if($gprivacy < 4) { # use event based privacy
	my ($tattendants, $tauthor, $mkey);
	for $href (@::caldata) {
	    if( $href->{'key'} == $tag) { $theevent = $href; last;}
	}
	$href=$theevent;
	$kind = $href->{'kind'};
	if(1) {
	    if($href->{'mkey'}) {
		$mkey = $href->{'mkey'};
		$mkey =~ s/_eMe_\d+//g;
		$tattendants = $href->{'attendants'};
		$tattendants =~ s/[,; ]+/:/g;
		$tattendants =~ s/:$//g;
		$tattendants = expandMeetingGroups($mkey, $tattendants);
		if(ismember($::d{'remote_user'}, $tattendants) or $::d{'remote_user'} eq $mkey){$::d{'authResult'} = 3;$gprivacy=3;}
	    }
	}
    }
    # Display the content only when permission is OK
    if($gprivacy > 3) { $eprivacy = 3;}
    else {
	# find the relevent event
	for $href (@::caldata) {
	    if( $href->{'key'} == $tag) {
		$tmp = $href->{'privacy'};
		if($tmp) { $eprivacy = $::privacyTable{$tmp} - 1;}
		else {$eprivacy = $gprivacy;}
		$theevent = $href;
		last;
	    }
	}
    }
    if(not $theevent) {
	for $href (@::caldata) {
	    if( $href->{'key'} == $tag) { $theevent = $href; last;}
	}
    }

    $seq = $theevent->{'seq'};    

    my $u = $::d{'remote_user'};
    if($::calinfo{'vcal'}) {$uvcal = 1;}
    elsif($u ne $who) { $uvcal = getinfo($u, 'vcal');}
    if($uvcal) {$vcal = "checked"; }
    else {$vcal = "";}
    if($u ne $who) { $email = getinfo($u, 'email'); $mname= getinfo($u, 'name');}
    else { $email = $::calinfo{'email'};  $mname=$::calinfo{'name'}; }
    $email="" unless $email;    $mname="" unless $mname;

    if($cmd == 0) { # display form
	#&make_style_sheet();
	if($::calinfo{'pnt'}) {
	    &headers(undef," ",0,0,0, ' onLoad="window.print()"');
	} else {
	    &headers(undef," ",0,1,0,undef);
	}
	if(!$inpopup) {
	    my $header = "";
	    if($::vm & 0x4) { # use the customized header 
		if($::calinfo{'hdr'}) { $header =  customize_header(substImages($::calinfo{'hdr'}));}
	    }
	    print $header;
       }

	#print "U=$u, remote=$::d{'remote_user'}<br>";
	$kind = $theevent->{'kind'};

	if($::calinfo{'mg'}) {$mg="&mg=$::calinfo{'mg'}";} else {$mg="";}

        if($eprivacy < 3 or $::d{'remote_user'} eq 'anonymous' or $::d{'remote_user'} eq 'nobody') {
            $noimport = 1;
        }
	if($::calinfo{'pnt'}) {
	    print "<br><center><h2>$name</h2></center><br>";
	} elsif(!$noimport) {
	    my ($allcals, $prompt);
	    if($::o{'listAllCals'} and &use_pulldown_nemu() ) {
		$::calinfo{'_clist_'} = 1;
		my @allcals = &listcals;
		delete $::calinfo{'_clist_'};
		unshift @allcals, "???";
		$allcals = select_option('tcal',"", @allcals);
		$allcals =~ s/class=\"fmList\"/class=\"fmListS\"/g;
		$allcals =~ s/>/ onChange=\"javascript:document.inport.submit();\">/;
		$prompt = "<a href=\"javascript:openpopup('$::o{'cginame'}?c=listcal&w=$who',\'calendars\',500,400)\"><font color=#666666><span class=\"fmLabel\">$::phr{'Import2Cal'}</span></font></a>";
	    } else {
		$allcals ="<input type=text name=tcal size=16 class=\"fmEntryS\">";
		$prompt="<a href=\"javascript:openpopup('$::o{'cginame'}?c=getcala&w=$who')\",\'calendars\',500,400><font color=#666666><span class=\"fmLabel\">$::phr{'Import2Cal'}</span></font></a>";
	    }

#import is a reserverd JS word !!!
	    print <<END;
<table border=0 cellpadding=0 cellspacing=0 width="$::o{'tw'}%"><tr><td width="100%">
<form name=inport action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value="dim">$inpopup
<input type=hidden name=v value=$view>
<input type=hidden name=t value=$tag>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$month/$day/$year/$hour/$min">
<input type=hidden name=w value="$who">
<table border=0 cellpadding=0 cellspacing=0 width="100%">
<tr bgcolor="#ccccff"><td class="m2calTd">
<b><span class="m2cal">&nbsp;$::phr{'Calendar'}:&nbsp;</span><span class="m2calName">&nbsp;$name</span></b></td>
<td align=center class="m2calTd" width=32><a href="$::o{'cginame'}?c=m2&pnt=1&t=$tag&ls=$ls&w=$who&v=$view&d=$month/$day/$year$mg$::vmg" target=pnt><img src="$::o{'imgdirurl'}/printer.gif" width=16 height=16 border=0 title="$::phr{'Print'}" alt="$::phr{'Print'}"></a></td>
<td align=right class="m2calTd"><font color="#666666" size=1><span class="fmLabelS">$prompt:&nbsp;</span>$allcals &nbsp;&nbsp;
</td></tr></table></form>
</td></tr></table>
END
    ;
	} else {
	    print <<END;
<table border=0 cellpadding=0 cellspacing=0 width="$::o{'tw'}%"><tr bgcolor="#ccccff">
<td class="m2calTd"><b><span class="m2cal">&nbsp;$::phr{'Calendar'}:&nbsp;</span><span class="m2calName">&nbsp;$name</span></b></td>
<td align=center class="m2calTd">
<a href="$::o{'cginame'}?c=m2&pnt=1&t=$tag&ls=$ls&w=$who&v=$view&d=$month/$day/$year$mg$::vmg" target=pnt><img src="$::o{'imgdirurl'}/printer.gif" width=16 height=16 border=0 title="$::phr{'Print'}" alt="$::phr{'Print'}"></a>
</td>
</tr></table>
END
    ;
	}
	my $msg = printEvent($theevent, $eprivacy, 4, !$mform, "$month/$day/$year");
	print "<br><center>$msg</center><br>";

	if($mform) {
	    my ($bartext, $totext, $more);
	    if($invitee_addresses) {
		$bartext = "$::phr{'MailToAll'} $::phr{'Participants'}";
		$totext = "<span class=\"fmLabel\">$::phr{'To'}</span>";
	    }
	    else {
		$bartext = "$::phr{'Mail2Friend'}";
		$totext = "<span class=\"fmLabel\">$::phr{'FriendsEmail'}</span>";
	    }
	    if($::calinfo{'toauthor'}) { $bartext=$::phr{'Mail2Author'};}
	    print "<table border=0 cellpadding=2 cellspacing=0 width=\"$::o{'tw'}%\"><tr bgcolor=#ddddff><td class=\"m2m2Td\">";
	    print "<b>&nbsp;$bartext</b></td></tr></table>";

            if($::d{'validuser'} > 1) {
                $more="<br><a href=\"javascript:openpopup(\'$::o{'cginame'}?c=gEaddr&fmname=m2&eltname=femail\','ew',800,500)\"><font color=blue size=1><span class=\"fmLabelS\">$::phr{'AddressBook'}&nbsp;</span></font></a>";
            } else { $more ="";}
	    print <<END;
<br><a name=zz>
<Form name="m2" action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value="dm2">$inpopup
<input type=hidden name=v value=$view>
<input type=hidden name=t value=$tag>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$month/$day/$year/$hour/$min">
<input type=hidden name=w value="$who">
<center>
<table border=0 cellspacing=0 cellpadding=0 width="80%">

<tr><td nowrap align=right><b>$totext:</b>$more</td><td nowrap><input type=text size=40 name="femail" class="fmEntry" value="$invitee_addresses"></td></tr>
<tr><td nowrap align=right><b><span class="fmLabel">Cc:</span></b></td><td><input type=text size=40 name="mcc" value="" class="fmEntry"></td></tr>
<tr><td nowrap align=right><b><span class="fmLabel">Bcc:</span></b></td><td><input type=text size=40 name="mbcc" value="" class="fmEntry"></td></tr>
END
           if($::d{'remote_user'} and $::d{'remote_user'} ne 'anonymous' and 
              (not $::o{'contactdb'} or $::o{'contactdb'} =~ /default/i ) ) {
	       print "
<tr><td align=center colspan=2><font color=#ff0000><span class=\"fmLabel\">$::phr{'AddNewEmail'}:</span>
<b>",input_radio("amail",0,@::switchList),"</b></font>
</td></tr>";
    }
	    my $closebtn;
	    if($inpopup){
		$closebtn .= <<END;
<input type=submit name=action value="$::phr{'Close'}" class="fmBtnSt" 
onclick="javascript:self.close()"></b>
END
    ;
	    } else {
		$closebtn = "<input type=submit name=action value=\"$::phr{'Cancel'}\" class=\"fmBtnSt\"></b>";
	    }

	    my $munits = select_value("mdelayu", "", @::unitmList);
            my ($signature, $sigfile, $siglink); 
            $sigfile="$::o{'spooldir'}/$::d{'remote_user'}/signature"; $signature="";
            if( -f $sigfile) { $signature = read_file_content($sigfile);}
	    else {
		$sigfile = "$::o{'spooldir'}/$who/signature";
		if( -f $sigfile ) {$signature = read_file_content($sigfile);}
	    }

            if($::d{'remote_user'} ne 'anonymous' and $::d{'remote_user'} ne 'nobody') {
                my $u=$::d{'remote_user'};
                my $url="$::o{'cgimisc'}?w=$u&cmd=signature";
                $siglink= "<a href=\"javascript:openpopup('$url','sig',680,600)\"><img src=\"$::o{imgdirurl}/q.gif\" width=17 height=15 border=0></a>";
            } else { $siglink="";}
	    $munits =~ s/>/ onChange=\"javascript:document.m2.mnow.checked=false;\">/;
	    print <<END;
<tr><td nowrap align=right><b><span class="fmLabel">$::phr{'YourEmailAddress'}:</span></b></td><td><input type=text size=40  class="fmEntry" name=memail value="$email"></td></tr>
<tr><td nowrap align=right><b><span class="fmLabel">$::phr{'YourName'}:</span></b></td><td><input type=text size=32  class="fmEntry" name=mname value="$mname">&nbsp;&nbsp;$siglink</td></tr>
<tr><td nowrap align=right valign=top><b><span class="fmLabel">$::phr{'PersonalMessage'}:</span></b></td><td>
<textarea name=pmsg nowrap cols=40 rows=5 class="fmText">$signature</textarea></td></tr>
<tr><td align=right><span class="fmLabel">$::phr{'SendMailUsing'}</span></td><td>
<input type=checkbox name="uhtml" value=1 class="fmRadio"><span class="fmLabel">&nbsp;HTML &nbsp;&nbsp;</span>
<input checked type=checkbox name="utxt" value=1 class="fmRadio"><span class="fmLabel">&nbsp;$::phr{'PlainText'}&nbsp;&nbsp;</span>
<input $vcal type=checkbox name="uvcal" value=1 class="fmRadio"><span class="fmLabel">&nbsp;vCal</span>
</td></tr>

<tr><td align=center colspan=2><font color="#ff0000"><b><span class="fmLabel">$::phr{'Sendmail'}</span>
<input type=checkbox name="mnow" checked value=1 class="fmRadio"><span class="fmLabel">&nbsp;$::phr{'immediately'}&nbsp;$::phr{'or'}&nbsp;</span>
<input type=text size=5 name="mdelay" value="" onChange="Javascript:document.m2.mnow.checked=false;" class="fmEntry">
&nbsp; $munits
<span class="fmLabel">$::phr{'beforeEvent'}.</span></b></font>
</td></tr>

<tr><td colspan=2><br></td></tr>
<tr><td colspan=2 align=center>
<b><input type=submit name=action value="$::phr{'Submit'}" class="fmBtnSt"> &nbsp;
$closebtn
</td></tr>
</table>
</center>
</form>
END
    ;
	    #"
	} elsif($::calinfo{'inpopup'}) {
	    print <<END;
<br><br>
<center><form><input type=submit name=action value="$::phr{'Close'}" class="fmBtnSt" onclick="javascript:self.close()"></b>
</form></center>
END
    ;
	}
	&trailer(0,0);
    } else { # send mail
	my($toaddr, $fromaddr, $fname, $pmsg, $html, $txt, $uvcal, $vmsg, $hmsg, $tmsg,$mcc, $mbcc, $Cc, $Bcc);
	$toaddr = $::calinfo{'femail'};
	$mcc =  $::calinfo{'mcc'}; 
	$mbcc =  $::calinfo{'mbcc'}; 
	$fname = $::calinfo{'mname'}; if(!$fname) {$fname="Anonymous User";}
	$fromaddr = $::calinfo{'memail'};
	if(!$fromaddr){ $fromaddr=$::o{'daemonEmail'}; $fname .= " VIA ";}
	$pmsg = $::calinfo{'pmsg'};
	$html = $::calinfo{'uhtml'};
	$txt = $::calinfo{'utxt'};
	$uvcal = $::calinfo{'uvcal'};
	$toaddr =~ s/[\s,]+/:/g;  $toaddr =~ s/\s*,$//g; 
	$toaddr = unique($toaddr); $toaddr =~ s/:/, /g;
	
	if($toaddr) {	
	    if($::calinfo{'amail'}) {add2addressbook($toaddr);if($mcc) {add2addressbook($mcc);}	if($mbcc) {add2addressbook($mbcc);}}
	    $::calinfo{'mdelay'} =~ s/^\s+|\s+$//g;
	    if($::calinfo{'mnow'} or $::calinfo{'mdelay'} !~ /^\d+$/) {
		$vmsg= $hmsg= $tmsg="";
		$Cc=""; $Bcc="";
		if($mcc) { $Cc = "\015\012Cc: $mcc";}
		if($mbcc) { $Bcc = "\015\012Bcc: $mbcc";}

		my $subj;
		if($eprivacy > 1){$subj = $theevent->{'what'};} else { $subj = $::phr{'Protected'};}
		$subj =~ s/\r?\n//g; $mcc =~ s/\r?\n//g; $mbcc=~ s/\r?\n//g; $toaddr =~ s/\r?\n//g;
		my $msgbody = genEMsgBdy($theevent, $who, $eprivacy, $uvcal, $txt, $html, "$month/$day/$year", $pmsg);
		if($webcalConfig::r{'sendmail'}) {
		    if( $ !~ m/MSWin|NT/i ) {
                        if($::calinfo{'inpopup'}){
                            ackpopup("$::phr{'MailSentTo'} <i>$toaddr</i>");
                        } else {
                            acknowledge($who,$view,$ls, "$month/$day/$year","$::phr{'MailSentTo'} <b>$toaddr</b>");
                        }
			my $SENDMAIL= $webcalConfig::r{'sendmail'};
			open (MAIL,"|-") || exec($SENDMAIL, "-t", "-oi");
			my $now_string = &rfc2822_datetime;
			 print MAIL "To: $toaddr$Cc$Bcc\015\012";
			 print MAIL "From: $fname <$fromaddr>\015\012";
			 print MAIL "Subject: $subj\015\012";
			 print MAIL "Date: $now_string\015\012";
			 print MAIL "X-Mailer: webCalendar $webCalVersion $patchlevel\015\012";
			 print MAIL "$msgbody";
			 print MAIL "\015\012";
			close MAIL;
			myexit(0);
		    } else {
			&headers;
			print "<br><table><tr><td><blockquote class=\"boxMsg\"><font color=#ff0000>Sorry, sendmail is not available for \"$\". 
Please ask your system administrator to reconfigure your webCalendar installation. Ask him/her to define the
variables 'smtpto' 'smtpform' in webcalConfig.pm, and undefine the variable 'sendmail'.</font>
&nbsp;&nbsp;<a href=\"javascript:history.go(-1)\"><b>$::phr{'GoBack'}</b></a> </blockquote></td></tr></table>";
			&trailer(0,0);
			myexit(0);
		    }
		} else { # check for smtp server
		    if($webcalConfig::r{'smtpto'} and $webcalConfig::r{'smtpfrom'}) {
			my $fromsmtp = $webcalConfig::r{'smtpfrom'};
			my $tosmtp = $webcalConfig::r{'smtpto'};
			my ($status, $error) = &smtplib::SmtpSendMail( $fromaddr, $fromsmtp, $toaddr, $tosmtp, $subj, $msgbody, $mcc, $mbcc);
			
			if($status != 0) { calerror("Error sending mail: $error",1); }
			else {
			    if($::calinfo{'inpopup'}){
				ackpopup("$::phr{'MailSentTo'} <i>$toaddr</i>");
			    } else {
				acknowledge($who,$view,$ls, "$month/$day/$year","$::phr{'MailSentTo'} <b>$toaddr</b>");
			    }
			}
			myexit(0);
		    } else {
			&headers;
			print "<br><table><tr><td><blockquote class=\"boxMsg\"><font color=#ff0000>Sorry, mail is not configured for your webcal installation. 
Please ask your system administrator to reconfigure your webCalendar installation. </font>
&nbsp;&nbsp;<a href=\"javascript:history.go(-1)\"><b>$::phr{'GoBack'}</b></a> </blockquote></td></tr></table>";
			&trailer(0,0);
			myexit(0);
		    }
		}
	    } else {  # queue mail
		my $qdir = "$::o{'spooldir'}/.mailq";
		if( ! -d $qdir) { mkdir("$qdir", 0711);} 
		my ($qfile, $i, $tm, $dly, $delay, $unit, $cal, $nm, $nh, $unitname, $now); 
		($nh, $nm) = split(/:/,$theevent->{'start'});
		my ($js, $jmn, $jhr, $jdy, $jmo, $jyr, $tzone, $utm) = localToUTC(0, $nm, $nh, $day, $month, $year-1900, $ENV{'TZ'});
		$tm = $utm;
		$dly = $delay = $::calinfo{'mdelay'};
		$unit =  $::calinfo{'mdelayu'};
		if($unit eq 'm') { $delay = $delay * 60; $unitname = $::phr{'mins'};}
		elsif($unit eq 'h') { $delay = $delay * 3600; $unitname = $::phr{'hours'};}
		elsif($unit eq 'd') { $delay = $delay * 86400; $unitname = $::phr{'days'};}
		elsif($unit eq 'w') { $delay = $delay * 604800; $unitname = $::phr{'weeks'};}
		$tm -= $delay;
		$ENV{'TZ'} = 'UTC'; $now = time; if($tzone){ $ENV{'TZ'}=$tzone;} else {delete $ENV{'TZ'};}
		if($tm < $now) { 
		    ($js, $jmn, $jhr, $jdy, $jmo, $jyr, $tzone, $utm) = UTCToLocal($js, $jmn, $jhr, $jdy, $jmo, $jyr, $tzone);
		    my $queuetime = mdy_string($jmo, $jdy, $jyr+1900);
		    my $mdy = mdy_string($month, $day, $year);
		    my $hrmn = hm_string($::now{'hour'},$::now{'min'});
		    my $qhrmn = hm_string($jhr, $jmn);
		    calerror("Cannot queue mail at a time in the past.<br><br>
<font color=#000000>Queue time: $queuetime $qhrmn &nbsp; - &nbsp; $dly $unitname <br><br>Current time: $mdy $hrmn </font>", 1);
		} 
		$i = 0;
		$qfile = "$qdir/$tm-$i"; while( -f "$qfile") { $i++; $qfile = "$qdir/$tm-$i";}
		my $fhmq = gensym;
		if(open($fhmq, ">$qfile")) {
		    &webcalLock::doflock(\*$fhmq, LOCK_EX, $qfile) or calerror("Cannot lock file '$qfile': $!\n",1);
		    print $fhmq "toaddr=$toaddr", "\n", "fromaddr=$fromaddr", "\n", "fname=$fname", "\n";
		    print $fhmq "cal=$who", "\n", "date=$month/$day/$year/$nh/$nm", "\n";
		    if($mcc) { print $fhmq "Cc=$mcc", "\n";}
		    if($mbcc) { print $fhmq "Bcc=$mbcc", "\n";}
		    print $fhmq "key=$tag","\n", "seq=$seq","\n", "html=$html", "\n", "txt=$txt", "\n","uvcal=$uvcal", "\n";
		    $pmsg =~ s/\n/\\n/g;
		    print $fhmq "privacy=$eprivacy", "\n", "pmsg=$pmsg", "\n";
		    &webcalLock::doflock(\*$fhmq, LOCK_UN, $qfile) or calerror("Cannot unlock file '$qfile': $!\n",1);
		    close $fhmq;
                    if($::calinfo{'inpopup'}){
                        ackpopup("Mail queued for delivery $dly $unitname before event.");
                    } else {
                        acknowledge($who,$view,$ls, "$month/$day/$year","Mail queued for delivery $dly $unitname before event.");
                    }
		} else { calerror("Cannot open queue file $qfile. $!\n", 1);}
	    }
	} else {
	    calerror($::phr{'EmailIncomplete'},1);
	}
    }
}
#=====================================================================================================
sub genEMsgBdy {
    my($theevent, $who, $eprivacy, $uvcal, $txt, $html, $et, $pmsg) = (@_);
    my ($vmsg, $hmsg, $tmsg);
    $vmsg= $hmsg= $tmsg="";
    if($uvcal) {$vmsg = toVcal($theevent, $who, $eprivacy); $vmsg=&html_escape($vmsg,0);}
    if($txt) {$tmsg = printEvent($theevent, $eprivacy, 0, 0, $et, 1); $tmsg =~ s/\r?\n/\015\012/g; $tmsg=&html_escape($tmsg, 0);}
    if($html) {$hmsg =printEvent($theevent, $eprivacy, 4, 0, $et, 1);}
    if($pmsg or $tmsg) {
	$pmsg="\015\012--=-vCalendar-AR47921209630406600730910407937723\015\012$webcalConfig::m{'textheader'}\015\012\015\012$pmsg\015\012\015\012$tmsg\015\012";
    }

    if($vmsg) {
	$vmsg="\015\012--=-vCalendar-AR47921209630406600730910407937723\015\012$webcalConfig::m{'vcalheader'}\015\012\015\012BEGIN:VCALENDAR\015\012PRODID:-//WebCalendar $webCalVersion-$patchlevel//EN\015\012VERSION:1.0\015\012$vmsg\015\012END:VCALENDAR\015\012";
    }
    if($hmsg) {

	$hmsg="\015\012--=-vCalendar-AR47921209630406600730910407937723\015\012$webcalConfig::m{'htmlheader'}\015\012\015\012
<html>
<BODY BGCOLOR=$webcalConfig::r{'backgroundColor'} TEXT=$webcalConfig::r{'textColor'} LINK=$webcalConfig::r{'linkColor'} VLINK=$webcalConfig::r{'linkColor'} topmargin=$webcalConfig::r{'topmargin'} marginheight=$webcalConfig::r{'marginheight'} leftmargin=$webcalConfig::r{'leftmargin'} marginwidth=$webcalConfig::r{'marginwidth'}>
$hmsg
</body>
</html>
";
    }

    my $msgbody ="MIME-Version: 1.0\015\012Content-Type: multipart/mixed; boundary=\"=-vCalendar-AR47921209630406600730910407937723\"\015\012\015\012$pmsg\015\012\015\012$vmsg\015\012\015\012$hmsg\015\012\015\012--=-vCalendar-AR47921209630406600730910407937723--\015\012";
    return $msgbody;
}
#=====================================================================================================
sub getinfo {
  my($cal, $name) = (@_);
  my $ans = undef;
  if( $cal and $name) {
      my $iname="$::o{'spooldir'}/$cal/info";
      my $fhedi = gensym;
      if(open($fhedi, "<$iname")) {
	  &webcalLock::doflock( \*$fhedi, LOCK_SH, "$iname") or calerror("Cannot lock file '$iname': $!\n",1);
	  while(<$fhedi>) {
	      if(/calinfo{\'$name\'}\s*=\s*\'(.+)\'\s*;/) {
		  $ans=$1; $ans =~ s/\\\'/\'/g; last;
	      }
	  }
	  &webcalLock::doflock( \*$fhedi, LOCK_UN,"$iname") or calerror("Cannot unlock file '$iname': $!\n",1);
	  close $fhedi;
      }
  }
  return $ans;
}
sub getinfolist {
  my($cal, (@names)) = (@_);
  my ($name, @ans); @ans=();
  if( $cal) {
      my $iname="$::o{'spooldir'}/$cal/info";
      my $fhedi = gensym;
      if(open($fhedi, "<$iname")) {
	  &webcalLock::doflock( \*$fhedi, LOCK_SH, "$iname") or calerror("Cannot lock file '$iname': $!\n",1);
	  while(<$fhedi>) {
	      for $name (@names) { 
		  if(/calinfo{\'$name\'}\s*=\s*\'(.+)\'\s*;/) {
		      my $ans=$1; $ans =~ s/\\\'/\'/g;
		      push @ans, $ans;
		  }
	      }
	  }
	  &webcalLock::doflock( \*$fhedi, LOCK_UN,"$iname") or calerror("Cannot unlock file '$iname': $!\n",1);
	  close $fhedi;
      }
  }
  return @ans;
}
#=====================================================================================================
sub expand_author_name {
    my ($tmp) = (@_);
    my $kk = 0;
    if(defined $::calinfo{'aname'}) { $kk= $::calinfo{'aname'};}
    if($kk == 2) { return $tmp;}
    else {
	my @all = split(/[,;: ]+/, $tmp);
	my ($x, $y, $z); $y="";
	foreach $x (@all) {
	    $z = getinfo($x, 'name'); 
	    if($y) { $y .= ", ";}
	    if($z) { if($kk == 1) {$y .= "$z";} else { $y .= "$z ($x)";}} else { $y .= "$x ";}
	}
	return $y;
    }
}
sub printEvent {
    my ($href, $privacy, $html, $fm, $et, $fcginame)=(@_);
    my($msg, $kind, $des, $timestr,$shr,$smn,$ehr,$emn, $tim, $month, $day, $year, $duration, $utmp) ;
    my ($what, $detail, $datestr, $repeat, $occurs, $recur_str, $imgdirurl, $cginameurl);
    if($et) {  ($month, $day, $year)=split(/\//, $et); }
    else {$month= $::calinfo{'month'};  $day  = $::calinfo{'day'};  $year = $::calinfo{'year'};}

    if($fcginame) { $imgdirurl = $::o{'fimgdirurl'}; $cginameurl=$::o{'fcginame'};}
    else { $imgdirurl = $::o{'imgdirurl'}; $cginameurl=$::o{'cginame'};}
    $kind = $href->{'kind'};
    $tim = $href->{'start'};
    ($shr,$smn)=split(/:/,$tim);
    if($href->{'duration'}) {$duration = $href->{'duration'};} else {$duration = 0;}
    $utmp=$smn+$duration;
    $ehr=$shr + int($utmp/60);
    $emn = $utmp % 60; if($emn < 10) { $emn="0$emn";}
    if($href->{'overdue'}) {
	my($date, $dm, $dd, $dy, $odate);
	$date = $href->{'date'};
	($dm, $dd, $dy) = split(/\//, $date);  $dm--;
	$odate= mdy_wstring($dm,$dd,$dy);
	$datestr = "<img src=\"$imgdirurl/larr.gif\" width=14 height=10 border=0 alt=\"\"> <b><span class=\"overdue\"><font color=#ff0000>$::phr{'Overdue'}: &nbsp; $odate</font></span></b>";
    } else {
	$datestr = mdy_swstring($month, $day, $year);
    }

    $repeat= $href->{'repeat'};
    $occurs = $href->{'occurs'};

    if($privacy > 1) {
	if($href->{'what'}){$what = $href->{'what'}; $what =~ s/pp\.gif/spacer\.gif/;}else {$what="";}
	if($privacy > 2) {
	    $des=""; $des = $href->{'detail'} if $href->{'detail'};
	    if($kind == 2) { 
		my ($ccc,$jk1) = getCompletionInfo($href, 0, $month, $day, $year);
		if($ccc) {
		    $ccc =~ s/size=1//g;
		    if($html){if($des) {$des .= "<br>$ccc";} else {$des = $ccc;} } else {if($des) {$des .= "\n$ccc";} else { $des=$ccc;}}
		}
	    }
	}
    } else { 
	$what ="$::phr{'Protected'}"; $des ="";
    }
    if($kind == 1 or $kind == 3) {$timestr = hm_hm_string($shr,$smn,$ehr,$emn);}
    elsif($kind == 2) { 
	if($smn == 99) { $timestr = "<img src=\"$imgdirurl/larr.gif\" width=14 height=10 border=0 alt=\"\">";}
	else {$timestr = hm_string($shr,$smn);}
    } else {  $timestr = $::phr{'AllDay'};} 

    if( $repeat and  $repeat > 1 and $occurs and $occurs ne "OneTime") {
        my $sdate = $href->{'date'};
        my ($smn, $sdy, $syr) = split(/\//, $sdate);
        my $sstr = mdy_nstring($smn, $sdy, $syr);
	if($occurs =~ /^Z(.+),(\d+),(\d*)/ ) {
	    my ($word,$c1,$c2) = ($1,$2,$3);
	    ($occurs,$repeat)=special_recurring_rule($word, $c1, $c2, $repeat);
	} else {
	    if($occurs eq 'MTWThF') { $repeat =  int(($repeat+4) / 5);}
	    elsif ($occurs eq 'MWF') {$repeat =  int(($repeat+2) / 3);}
	    elsif ($occurs eq 'TTh') { $repeat =  ($repeat+1) >> 1;}
	    $occurs = $::phr{$occurs};
	}
	$recur_str = format_recur_string($occurs, $repeat, $sstr );
    }
    else { $recur_str = "";}

    if($html) { 
	my ($type, $bclr, $tcb, $tce, $bcs, $bce, $bgclr, $fgclr);
	#$des = &substImages($des);
	#$what = &substImages($what);
	if($href->{'fg'}){$fgclr = $href->{'fg'};} else {$fgclr="";}
	if($href->{'bg'}) {$bgclr = $href->{'bg'};} else {$bgclr="";}
	if($bgclr){ $bgclr=" bgcolor=$bgclr";} else {$bgclr="";}
	if($href->{'cs'}) {
	    $bcs="<span class=\"$href->{'cs'}\">"; $bce="</span>";  
	    if($fgclr) { $tcb="<font color=$fgclr>"; $tce="</font>";} else {$tcb=$tce="";}
	}
	else { 
	    #if(!$fgclr) { $fgclr="#1A6A6B"; $bgclr="";}
	    if(!$fgclr) { $fgclr="#f63030"; $bgclr="";}
	    $tcb = "<font color=$fgclr>"; $tce="</font>";
	    $bcs=$bce="";
	}
	my $bcg="";
	if($fcginame) {	$type= "<h2>$what</h2>";}
	else {$type= $what;} $type="" unless $type;
	if($kind == 1) {   $bclr = "$::o{'tclra'}";}
	elsif($kind == 2) { $bclr = "$::o{'tclrt'}";}
	elsif($kind == 3) { $bclr = "$::o{'tclrm'}";}
	else{ $bclr = "$::o{'tclrs'}"; if($href->{'cbg'}) {$bcg=&hack_cell_bg_style("white","right");}}    
        my $cor="";
        if($href->{'seq'} =~ /^C/) { $cor="<img src=\"$imgdirurl/pd.gif\" align=middle width=8 height=8> ";}
	my $tblheader="<table border=0 cellspacing=0 cellpadding=$html width=\"90%\" $bcg>";
	$msg = "";
	
	#$msg .= "<tr><td width=\"10%\" height=1><img src=\"$imgdirurl/spacer.gif\" width=1 height=1 border=0></td><td width=\"90%\" height=1><img src=\"$imgdirurl/spacer.gif\" width=95 height=1 border=0></td></tr>";
#	$msg .= "<tr><td colspan=2><font size=3 color=#1A6A6B><b>$type</b></font></td></tr>";	 
	$msg .= "<tr><td$bgclr colspan=2 class=\"v4titleBG$kind\"><b>$bcs$tcb$cor<font size=+1><span class=\"v4title$kind\">$type</span></font>$tce$bce</b></td></tr>";	 

	#$msg .= "<tr><td colspan=2 height=8><img src=\"$imgdirurl/spacer.gif\" width=1 height=1 border=0></td></tr>";

        if($recur_str) {
            $msg .= "<tr><td nowrap valign=top class=\"v4dateLabel\"><b>$::phr{'Date'}:</b></td><td class=\"v4dateTxt\">$datestr<br><font size=1 color=#9090ff><span class=\"v4recurrence\">$recur_str</span></font></td></tr>";
        } else {
            $msg .= "<tr><td nowrap valign=top class=\"v4dateLabel\"><b>$::phr{'Date'}:</b></td><td class=\"v4dateTxt\">$datestr</td></tr>";
        }
	$msg .= "<tr><td valign=top nowrap class=\"v4timeLabel\"><b>$::phr{'Time'}:</b></td><td class=\"v4timeTxt\"><font color=$bclr><b>$timestr</b></font></td></tr>";
	if($des) { $msg .= "<tr><td valign=top class=\"v4detailLabel\"><b>$::phr{'Details'}:</b></td><td class=\"v4detailTxt\">$des&nbsp;</td></tr>";}
    if($privacy > 2) {	
	if($href->{'attendants'}) {
	    if($href->{'rsvp'}) {  
		my ($status, $accepted, $declined, $other) = confirmMeeting($href, 0, 1);
		my $ans = "<table border=0 cellspacing=0>";
		if($accepted) { $ans .= "<tr><td width=\"4%\" nowrap valign=top>$::phr{'invitationAccepted'}:</td>
<td width=\"96%\"><font size=1>$accepted</font></td></tr>";}
		if($declined) { $ans .= "<tr><td width=\"4%\" nowrap valign=top>$::phr{'invitationDeclined'}:</td>
<td width=\"96%\"><font size=1>$declined</font></td></tr>";}
		if($other) { $ans .= "<tr><td width=\"4%\" nowrap valign=top>$::phr{'Unconfirmed'}:</td>
<td width=\"96%\"><font size=1>$other</font></td></tr>";} 
		$ans .= "</table>";		

		$msg .= "<tr><td valign=top><b>$::phr{'Participants'}:</b></td><td>$ans</td></tr>";  
	    } else {
		my $tmp = $href->{'attendants'};
		my $mkey = $href->{'mkey'};
		if($mkey) {
		    $mkey =~ s/_eMe_\d+//g;	$tmp =~ s/[,; ]+/:/g;  $tmp =~ s/:$//g;
		    $tmp = expandMeetingGroups($mkey, $tmp, 1);
		}
		my ($m, @all, $at, $name);
		$at = "";
		@all = split(/:/, $tmp);
		foreach $m (@all) {
		    $name = getinfo($m, 'name'); 
		    if($name) { $at .= "$name ($m), ";}
		    else { $at .= "$m, ";}
		}
		$at =~ s/, $//;
		$msg .= "<tr><td class=\"v4attLabel\" valign=top><b>$::phr{'Participants'}:</b></td><td class=\"v4attTxt\">$at</td></tr>";  
	    }
	}
	if($href->{'room'}) {
	    #my $tmp = substImages($href->{'room'});
            my $tmp = $href->{'room'};
	    $msg .= "<tr><td valign=top nowrap class=\"v4locationLabel\"><b>$::phr{'Location'}:</b></td><td class=\"v4locationTxt\">$tmp</td></tr>";	    	
	}
	if($href->{'pri'}) {
	    my $tmp = $href->{'pri'};
	    $msg .= "<tr><td valign=top class=\"v4priLabel\"><b>$::phr{'Priority'}:</b></td><td class=\"v4priTxt\">$tmp</td></tr>";	    	
	}
	if($href->{'url'}) {
	    my $irepository = "$imgdirurl/$::o{'uploadsubdir'}";
	    my $fff = &getIUploaddirFullURL;
	    my $url = $href->{'url'}; my ($URL, $rurl, @urls, $a, $b, $icon); 
	    $rurl="";
	    @urls = split(/\s+/, $url); 
	    foreach $b (@urls) {
		$a = $b;
		$b =~ s/\\?\^o\^\//$irepository\//g;		
		if(!$fcginame) {
		    $a =~ s/\\?\^o\^\//$fff\//g;
		    $icon = select_url_icon($a);
		    $icon=" <img src=\"$imgdirurl/$icon\" width=20 height=9 border=0>";
		} else {
		    $icon="";
		    $a = $b;
		}
		$a =~ s/^http:\/\//ptth:\/\//ig;
		$rurl .= "<a href=\"$b\"><font color=#0000ff>$a</font>$icon</a> ";
	    }	    
	    $msg .= "<tr><td valign=top class=\"v4urlLabel\"><b>URL:</b></td><td class=\"v4urlTxt\">$rurl</td></tr>";	    
	}
	if($href->{'cat'}) {
	    #my $tmp = substImages($href->{'cat'});
	    my $tmp = $href->{'cat'};
	    $msg .= "<tr><td valign=top nowrap class=\"v4catLabel\"><b>$::phr{'Category'}:</b></td><td class=\"v4catTxt\">$tmp</span></td></tr>";	    	
	}
	if($href->{'spkr'}) {
	    #my $tmp = substImages($href->{'spkr'});
	    my $tmp = $href->{'spkr'};
	    $msg .= "<tr><td valign=top nowrap class=\"v4speakerLabel\"><b>$::phr{'Speaker'}:</b></td><td class=\"v4speakerTxt\">$tmp</td></tr>";	    	
	}
	if($href->{'ctp'}) {
	    #my $tmp = substImages($href->{'ctp'});
	    my $tmp = $href->{'ctp'};
	    $msg .= "<tr><td valign=top nowrap id =\"v4ctpLabel\"><b>$::phr{'ContactP'}:</b></td><td class=\"v4ctpTxt\">$tmp</td></tr>";	    	
	}
	if($href->{'ctm'}) {
	    my $tmp = $href->{'ctm'};
	    $msg .= "<tr><td valign=top nowrap class=\"v4ctmLabel\"><b>$::phr{'ContactE'}:</b></td><td class=\"v4ctmTxt\"><a href=\"mailto:$tmp\"><font color=#0000ff>$tmp</font></a></td></tr>"; 	
	}
	if($href->{'author'}) {
	    my $tmp = expand_author_name($href->{'author'});
	    $msg .= "<tr><td valign=top class=\"v4authorLabel\"><b>$::phr{'Author'}:</b></td><td class=\"v4authorTxt\">$tmp</td></tr>";	    	
	}
    }
	# extra info ...
        if(!$::calinfo{'pnt'}) {
            my ($form, $edit) = ("", "");
            my ($who, $ls, $view, $imth, $idy, $iyr, $tag, $kind, $mg);
            $who=$::calinfo{'w'}; $view=$::calinfo{'v'}; $ls = $::calinfo{'ls'};
            #$imth= $::calinfo{'month'};  $idy  = $::calinfo{'day'};  $iyr = $::calinfo{'year'};
            $imth= $month;  $idy  = $day;  $iyr = $year;
            if($::calinfo{'mg'}) {$mg="&mg=$::calinfo{'mg'}";} else {$mg="";}
            $tag = $href->{'key'}; $kind = $href->{'kind'};

	if($fcginame) { 
	    $form=""; 
	    $edit = <<END;
<a href="$cginameurl?w=$who&c=get&anonymous=1&v=$view&ls=$ls&d=$imth/$idy/$iyr$mg$::vmg"><font size=1 color=#9999cc>$::phr{'Calendar'}</font></a>
END
    ;
	} else {
	    if($fm and $privacy > 1) {
		my $tgt=""; my $author="";
		my $label=$::phr{'Mail2Friend'};
		if($::d{'tend_2_pending'}) {
		    my($aa, $other) = split(/[,: ]/, $href->{'author'});
		    if($aa) { 
			my $ee = getinfo($aa, 'email'); 
			if($ee){
			    $label = $::phr{'Mail2Author'};
			    $tgt = "target=_mailto";
			    $author="&toauthor=$ee";
			    $::calinfo{'pelastemail'} = $ee;
			}
		    };
		}
		my $url="$cginameurl?w=$who&c=fm2&v=$view&ls=$ls&t=$tag&k=$kind$author&d=$imth/$idy/$iyr$mg$::vmg";
		if($::calinfo{'dmode'} or $::calinfo{'inpopup'}){ $url="javascript:pdl('$url')";}
		$form= <<END;
<a $tgt href="$url"><font size=1 color="#9999cc"><span class="v4mailto">$label</span></font></a>
END
    ;
            } else {$form = "";}
            if($::d{'authResult'} == 4) {
		my $inpopup=""; if($::calinfo{'inpopup'}) { $inpopup="&inpopup=1";} 
                $edit = <<END;
<a href="$cginameurl?w=$who&c=ed&v=$view&ls=$ls&t=$tag&k=$kind&d=$imth/$idy/$iyr$mg$::vmg$inpopup"><font size=1 color="#9999cc"><span class="v4edit">$::phr{'EditThis'}</span></font></a>
END
    ;
            } else {$edit="";}
	    
            $msg .= "<tr><td colspan=2>$form <img src=\"$imgdirurl/spacer.gif\" width=30 height=20 border=0>
$edit
</td></tr>";
	}
     }
        #my $irepository = "$imgdirurl/$::o{'uploadsubdir'}";
        #$msg=~ s/\\?\^o\^\/([^\s]+?)\.(gif|jpg|png|jpeg|bmp)/ <img src=\"$irepository\/$1\.$2\" border=0 align=left valign=top> /ig;
        #$msg =~ s/(^|[^"'])(http:\/\/[^\s]+?)\.(gif|jpg|png|jpeg|bmp)/$1 <img src=\"$2\.$3\" border=0 align=left valign=top> /ig; #"
        #$msg =~ s/ptth:\/\//http:\/\//gi;
        #$msg =~ s/\n[ \t\r]*\n/<br clear="all">/g;
	$msg = substImages($msg);
	$msg = $tblheader . $msg . "</table>";
    } else {
        my $type;
        if($kind == 1) {  $type = "$::phr{'Appointment'}\n";}
	elsif($kind == 2) { $type = "$::phr{'Todo'}\n";}
	elsif($kind == 3) {  $type = "$::phr{'Meeting'}\n";} 
	else{ $type = "$::phr{'NoTimeEvent'}\n";}    
	
	$msg = "  " . $type;
        $msg .= fstr($::phr{'Date'}, $datestr );
        if($recur_str) { $msg .= fstr("  ", $recur_str); }
	$msg .= fstr($::phr{'Time'}, $timestr);
	$msg .= fstr($::phr{'What'}, $what);
	$msg .= fstr($::phr{'Details'}, $des);
    if($privacy > 2) {	
	if($href->{'attendants'}) {
	    if($href->{'rsvp'}) {  
		my ($status, $accepted, $declined, $other) = confirmMeeting($href, 0, 1);
		$msg .= fstr($::phr{'Participants'}, "===$::phr{'RequestRSVP'}==");
		if($accepted) { $msg .=  fstr($::phr{'invitationAccepted'}, $accepted);}
		if($declined) { $msg .=  fstr($::phr{'invitationDeclined'}, $declined);}
		if($other) { $msg .=  fstr($::phr{'Unconfirmed'}, $other);}
	    } else {
		my $tmp = $href->{'attendants'};
		my $mkey = $href->{'mkey'};
		if($mkey) {
		    $mkey =~ s/_eMe_\d+//g;
		    $tmp =~ s/[,; ]+/:/g;  $tmp =~ s/:$//g;
		    $tmp = expandMeetingGroups($mkey, $tmp);
		}
		$msg .= fstr($::phr{'Participants'}, $tmp);
	    }
	}
	if($href->{'room'}) {
	    my $tmp = $href->{'room'};
	    $msg .= fstr($::phr{'Location'}, $tmp);
	}
	if($href->{'pri'}) {
	    my $tmp = $href->{'pri'};
	    $msg .= fstr($::phr{'Priority'}, $tmp);
	}
	if($href->{'url'}) {
	    my $url = $href->{'url'};
	    my $fff = &getIUploaddirFullURL;
	    $url =~ s/\\?\^o\^\//$fff\//g;	    
	    $msg .= fstr("URL", $url);
	}
	if($href->{'cat'}) {
	    my $tmp = $href->{'cat'};
	    $msg .= fstr($::phr{'Category'}, $tmp);
	}
	if($href->{'spkr'}) {
	    my $tmp = $href->{'spkr'};
	    $msg .= fstr($::phr{'Speaker'}, $tmp);
        }
	if($href->{'ctp'}) {
	    my $tmp = $href->{'ctp'};
	    $msg .= fstr($::phr{'ContactP'}, $tmp);
	}
	if($href->{'ctm'}) {
	    my $tmp = $href->{'ctm'};
	    $msg .= fstr($::phr{'ContactE'}, $tmp);
	}
	if($href->{'author'}) {
	    my $tmp = expand_author_name($href->{'author'});
	    $msg .= fstr($::phr{'Author'}, $tmp);
	}
    }
        my $irepository = "$imgdirurl/$::o{'uploadsubdir'}";
        $msg =~ s/\\?\^o\^\/([^\s]+?)\.(gif|jpg|png|jpeg|bmp)/ $irepository\/$1\.$2 /ig;
    }
    return $msg;
}
#=====================================================================================================
sub fstr {
    my ($a, $b, $flen) = (@_);
    my ($len, $tmp, $msg);
    $len = length($a);  $flen = 12 if not $flen; 
    $tmp = $flen - $len;
    if($tmp > 0) { $msg = ' ' x $tmp ;} else { $msg = "";}
    $b =~ s/\n/\n           /g;
    $msg .= "$a: $b\n";
    return $msg;
}
#=====================================================================================================

sub dovcal {
    my ($cmd, $who, $view, $month, $day, $year, $hour, $min, $ls, $vcal, $tmp, $imsg, $amsg);
    $who = $::calinfo{'w'};    $view = $::calinfo{'v'};    $ls = $::calinfo{'ls'};
    $month= $::calinfo{'month'};  $day  = $::calinfo{'day'};  $year = $::calinfo{'year'};
    $hour = $::calinfo{'hour'};    $min  = $::calinfo{'min'};

    $cmd = (@_)[0];
    
    if($cmd == 0) { # display form
	&headers('Wcalendar import from Vcalendar', " ", undef,0,1,0,undef);
	my @alldata = listalldata($who);
	my $allcals = select_option("database", "data", @alldata);

	print <<END;
<center>
<Form action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value="doadmin">
<input type=hidden name=ac value="download">
<input type=hidden name=w value="$who">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=cft value="vcal">
<input type=hidden name=d value="$month/$day/$year/$hour/$min">
<table border=3 cellpadding=8 cellspacing=0  bgcolor=$webcalConfig::r{'dkbackground'} width="70%" class="exportvcal">
<tr><td class="exportvcal" width="100%" align=center><font color="#0000cc"><b><input type=submit value=" $::phr{'Export2Vcal'} " class="fmBtnSt"></b></font>&nbsp;&nbsp;&nbsp;$allcals</td></tr></table>
</table>
</form>
</center>
END
    ;
	
	print "<center><big><span class=\"miscTitle\"><b>&nbsp;$::phr{'Calendar'}:&nbsp;&nbsp;$who</b></big>&nbsp;&nbsp;<font color=#ff0000>$::phr{'ImportVcal'}</font></span></center>";
	if(($::d{'authResult'} | $::d{'ispublic'}) < 4 or $::d{'validuser'} == 0) {
	    print "<br><center><font color=#999900><b><span class=\"authWarn\">$::phr{'AuthRequired'}!</span></b></font></center>\n";
	}
	my $oltmp; if(defined $::calinfo{'ol'}) { $oltmp = $::calinfo{'ol'};} else {$oltmp = 0;} # 0 allow, 1 disallow
	my $overlap= input_radio("aol",$oltmp, @::boolList);
        my $overlapthing;
	if($oltmp < 2) {
	    $overlapthing = <<END;
<tr><td>&nbsp;</td><td colspan=4><font color="#cd3b3b" size=-1><b><span class="fmLabelS">$::phr{'AllowOverlap'}: &nbsp;</span> $overlap<br></td></tr>
END
    ;
	} else {$overlapthing="<input type=hidden name=\"aol\" value=2>";}
#<FORM ENCTYPE="multipart/form-data" ACTION="$::o{'cginame'}">
	print <<END;
<center><br>
<FORM ENCTYPE="multipart/form-data" ACTION="$::o{'cgiimport'}" method=POST name=webcalm>$::vmp
<input type=hidden name=c value="dvc">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$month/$day/$year/$hour/$min">
<input type=hidden name=w value="$who">
<table border=3 cellpadding=8 cellspacing=0 width="70%" bgcolor=$webcalConfig::r{'dkbackground'} class="importvcal">
<tr><td align=center><font size=+1><b><span class="miscTitleSmall">$::phr{'ImportFileTitle'}</span></b></font></td></tr>
<tr><td>
<table border=0 cellpadding=0 cellspacing=1>
<tr><td width=5%></td><td width=20%></td><td width=25%></td><td width=25%></td><td width=25%></td></tr>
<tr><td colspan=5><blockquote class="msg">$::phr{'ImportFileInstruction'}</blockquote></td></tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'File'}:</span></b></td><td colspan=4>
    <INPUT TYPE="FILE" NAME="file_to_upload" SIZE="40" class="fmFile"></td></tr>
$overlapthing
END
    {
	my ($attendants, $imgp, $mme, $rsvp) = ("","", 1, 0);
	&printAttPart($who, $attendants,$imgp,$mme, $rsvp, "#000000",'webcalm');
    }
	print <<END;
<tr><td colspan=5><hr></td></tr>
<tr><td align=center colspan=5><b><input type=submit name=action value="$::phr{'Submit'}" class="fmBtnSt">
&nbsp;&nbsp;&nbsp;&nbsp;<input type=button class="fmBtnSt" value="$::phr{'Cancel'}" onclick="javascript:history.go(-1)"></b></td></tr>
</table>
</td></tr></table>	
</FORM>
</center>
END

	print <<END;
<br>
<center>
<Form name=webcal action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value="dvc">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$month/$day/$year/$hour/$min">
<input type=hidden name=w value="$who">
<table border=3 cellpadding=8 cellspacing=0 width="70%" bgcolor=$webcalConfig::r{'dkbackground'} class="importvcal">
<tr><td>
<table border=0 cellpadding=0 cellspacing=1>
<tr><td width=5%></td><td width=20%></td><td width=25%></td><td width=25%></td><td width=25%></td></tr>
<tr><td colspan=5><blockquote class="msg">$::phr{'ImportVcalInstruction'}</blockquote></td></tr>
<tr><td>&nbsp;</td><td colspan=4><textarea name=vcc nowrap cols=38 rows=10 class="fmText"></textarea></td></tr>
$overlapthing
END
    {
	my ($attendants, $imgp, $mme, $rsvp) = ("","", 1, 0);
	&printAttPart($who, $attendants,$imgp,$mme, $rsvp, "#000000");
    }
	print <<END;	
<tr><td colspan=5><hr></td></tr>
<tr><td align=center colspan=5>
<b><input type=submit name=action value="$::phr{'Submit'}" class="fmBtnSt"> &nbsp;&nbsp;
<input type=button value="$::phr{'Cancel'}" onclick="javascript:history.go(-1)" class="fmBtnSt"></b></td></tr>
</table>
</td></tr></table>
</form>
</center>
END
     &trailer(0,0);
    } else { # import From VCALENDAR
	if($::d{'authResult'} ne 4) {
	    if($::d{'ispublic'}) {
		$::d{'authResult'} = 4;
		$::calinfo{'author'} = $::d{'remote_user'};
	    }
	}
	if($::d{'authResult'} ne 4) {calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who).");}
	# parse vcalendar and do insertion.
	$vcal = $::calinfo{'vcc'}; 
	my @event_array = parseVcal($who, $vcal);
	($amsg,$imsg) = importwork($who, \@event_array, 0);
	# acknowledge
        my $timeout = 10;  if($imsg) { $timeout=30;} 
        &headers($::phr{'Acknowledgement'},undef,"$timeout; URL=$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$month/$day/$year$::vmg",1);
	print "<br><br><center><table border=1><tr><td>";
	print "<font color=#00cc00>$amsg</font><br><br>";
        if($imsg) { 
	    print "</td></tr><tr><td>";
            print "<span class=\"warnMsg\"><b>$::phr{'AlreadyOnCalendar'}</b>";
            print "<br><font color=#000099>$imsg</font><br></span>";
        }
	print "</td></tr></table>\n<br><br>";
	print "<table border=2 bgcolor=$webcalConfig::r{'dkbackground'} cellpadding=2><tr><td><a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$month/$day/$year$::vmg\">$::phr{'BackToCalendar'}</a></tr></table>";
	&trailer(0,0);
    }
}
#===========================================================================================================
sub dovcard {
    my ($cmd, $who, $view, $month, $day, $year, $hour, $min, $ls, $vcal, $tmp, $imsg, $amsg);
    $who = $::calinfo{'w'};    $view = $::calinfo{'v'};    $ls = $::calinfo{'ls'};
    $month= $::calinfo{'month'};  $day  = $::calinfo{'day'};  $year = $::calinfo{'year'};


    $cmd = (@_)[0];

    if($cmd == 0) { # display form
	&headers('Wcalendar import from vCard',undef, undef,0,1,0,undef);
    print <<END;
<center>
<Form action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value="dabk">
<input type=hidden name=w value="$who">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=cft value="vcal">
<input type=hidden name=d value="$month/$day/$year">
<table border=3 cellpadding=8 cellspacing=0  bgcolor=$webcalConfig::r{'dkbackground'} width="70%">
<tr><td width="100%" align=center><font color="#0000cc"><b><input type=submit value=" $::phr{'Export2VCard'} " class="fmBtnSt"></b></font></td></tr></table>
</table>
</form>
</center>
END

	print "<center><big><span class=\"miscTitleSmall\"><b>&nbsp;$::phr{'Calendar'}:&nbsp;&nbsp;$who</b></big>&nbsp;&nbsp;<font color=#ff0000>$::phr{'ImportVcard'}</font></span></center>";
	if(($::d{'authResult'} | $::d{'ispublic'}) < 4 or $::d{'validuser'} == 0) {
	    print "<br><center><font color=#999900><b><span class=\"authWarn\">$::phr{'AuthRequired'}!</span></b></font></center>\n";
	}
    print <<END;
<center><br>
<FORM ENCTYPE="multipart/form-data" ACTION="$::o{'cgiimport'}" method=POST>$::vmp
<input type=hidden name=c value="dvcard">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$month/$day/$year">
<input type=hidden name=w value="$who">
<table border=3 cellpadding=8 cellspacing=0 width="70%" bgcolor=$webcalConfig::r{'dkbackground'}>
<tr><td align=center><font size=+1><b><span class="miscTitleSmall">$::phr{'ImportVcardTitle'}</span></b></font></td></tr>
<tr><td>
<table border=0 cellpadding=0 cellspacing=1>
<tr><td width=5%></td><td width=20%></td><td width=25%></td><td width=25%></td><td width=25%></td></tr>
<tr><td colspan=5><blockquote class="msg">$::phr{'ImportVcardFileInstruction'}</span><br><br></td></tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'File'}:</span></b></td><td colspan=4>
    <INPUT TYPE="FILE" NAME="file_to_upload" SIZE="40" class="fmFile"></td></tr>
END
	print <<END;
<tr><td colspan=5><hr></td></tr>
<tr><td align=center colspan=5><b><input type=submit name=action value="$::phr{'Submit'}" class="fmBtnSt">
&nbsp;&nbsp;&nbsp;&nbsp;<input type=button value="$::phr{'Cancel'}" class="fmBtnSt" onclick="javascript:history.go(-1)"></b></td></tr>
</table>
</td></tr></table>	
</FORM>
</center>
END

	print <<END;
<br>
<center>
<Form name=webcal action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value="dvcard">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$month/$day/$year">
<input type=hidden name=w value="$who">
<table border=3 cellpadding=8 cellspacing=0 width="70%" bgcolor=$webcalConfig::r{'dkbackground'}>
<tr><td>
<table border=0 cellpadding=0 cellspacing=1>
<tr><td width=5%></td><td width=20%></td><td width=25%></td><td width=25%></td><td width=25%></td></tr>
<tr><td colspan=5><blockquote class="msg">$::phr{'ImportVcardInstruction'}</blockquote></td></tr>
<tr><td>&nbsp;</td><td colspan=4><textarea name=vcard nowrap cols=38 rows=10 class="fmText"></textarea></td></tr>
END
	print <<END;	
<tr><td colspan=5><hr></td></tr>
<tr><td align=center colspan=5>
<b><input type=submit name=action value="$::phr{'Submit'}" class="fmBtnSt"> &nbsp;&nbsp;
<input type=button value="$::phr{'Cancel'}" onclick="javascript:history.go(-1)" class="fmBtnSt"></b></td></tr>
</table>
</td></tr></table>
</form>
</center>
END
     &trailer(0,0);
    } else { # import From VCARD
	if($::d{'authResult'} ne 4) {
	    if($::d{'ispublic'}) {
		$::d{'authResult'} = 4;
		$::calinfo{'author'} = $::d{'remote_user'};
	    }
	}
	if($::d{'authResult'} ne 4) {calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who).");}

        my $timeout = 5;  if($imsg) { $timeout=30;} 
        &headers($::phr{'Acknowledgement'},undef,"$timeout; URL=$::o{'cginame'}?c=ad&ls=$ls&w=$who&v=$view&d=$month/$day/$year$::vmg",1);
	# parse vcalendar and do insertion.
	my $vcard = $::calinfo{'vcard'}; 
	($amsg,$imsg) = importVcardWork($who, $vcard);
	# acknowledge
	print "<br><br><center><table border=1><tr><td><br>";
	print "<font color=#ff0000><span class=\"warnMsg\">$amsg</span></font><br><br>";
        if($imsg) { 
	    print "</td></tr><tr><td>";
            print "<span class=\"warnMsg\"><b>$::phr{'AlreadyInAddressbook'}</b><br>";
            print "<br><font color=#000099>$imsg</font><br></span>";
        }
	print "</td></tr></table>\n<br><br>";
	print "<table border=2 bgcolor=$webcalConfig::r{'dkbackground'} cellpadding=2><tr><td><a href=\"$::o{'cginame'}?c=ad&ls=$ls&w=$who&v=$view&d=$month/$day/$year$::vmg\">$::phr{'BackToCalendar'}</a></tr></table>";
	&trailer(0,0);
    }
}
sub exportAddressBook {
    my ($who, $calname, $fname);
    if($::d{'authResult'} != 4 and $::d{'ispublic'} == 0) {calerror("$::phr{'notAllowedToDownload'} $::d{'authResult'}");}
    $who = $::calinfo{'w'};
    $calname = "$::o{'spooldir'}/$who";
    print "Content-Type: text/plain\n\n";
    $fname="$calname/address";
    doReadFile("$fname");
    my $href;
    for $href (@::addressbook) { my $t = toVCard($href, $who, 3); print $t, "\015\012"; }
    myexit(0);
}
sub importVcardWork {
    my ($who, $vcard ) = (@_);
    my($afile, @addresses, $ncnt, $imsg, $acnt,$dcnt, $amsg, $dmsg, $href, $tmp);
    $afile = "$::o{'spooldir'}/$who/address";
    @addresses = parseVCard($who, $vcard);
    $ncnt = 0+@addresses;
    $amsg = $imsg = $dmsg = "";
    $acnt = 0;
    if( $ncnt > 0) {
	my ($cnt, $role, $mgp); 
	my $fhvc = gensym;
	if(sysopen($fhvc, "$afile", O_WRONLY | O_CREAT, 0644)) {	
	    &webcalLock::doflock( \*$fhvc, LOCK_EX, "$afile") or calerror("Cannot lock file '$afile': $!\n",1);
	    $cnt = do  "$afile"; $cnt++;

	    for $href (@addresses) {
		my $in = addressInAddressbook(\@::addressbook, $href);
		if($in) {  $href->{'in'} = $who; }
	    }
	    truncate($fhvc, 0);
	    print $fhvc "\@::addressbook = (\n";
	    for $href (@::addressbook) {
		if(! $href->{'outdated'}) {
		    $tmp = print1Address($href);
		    print $fhvc $tmp;
		} else {
		    my($f, $l, $e); 
		    if($href->{'fname'}){$f=$href->{'fname'};}else{$f="";}
		    if($href->{'lname'}){$l=$href->{'lname'};}else{$l="";}
		    if($href->{'email'}){$e=$href->{'email'};}else{$e="";}
		    my $tmsg = "<b>$f $l &lt;$e&gt;</b><br>";
		    $dmsg .= $tmsg;
		}
	    }
	    for $href (@addresses) { 
		if(exists $href->{'in'} and  $href->{'in'} eq $who) {
		    my($f, $l, $e); 
		    if($href->{'fname'}){$f=$href->{'fname'};}else{$f="";}
		    if($href->{'lname'}){$l=$href->{'lname'};}else{$l="";}
		    if($href->{'email'}){$e=$href->{'email'};}else{$e="";}
		    my $tmsg = "<b>$f $l &lt;$e&gt;</b><br>";
		    $imsg .= $tmsg;
		} else {
		    $acnt++;
		    delete $href->{'in'} if exists $href->{'in'};
		    $href->{'tag'}=$cnt; $cnt++;
		    $tmp = print1Address($href);
		    print $fhvc $tmp;		    
		}
	    }
	    print $fhvc ");\n$cnt;\n";
	    &webcalLock::doflock( \*$fhvc, LOCK_UN,"$afile") or calerror("Cannot unlock file '$afile': $!\n",1);
	    close $fhvc;	    
	} else { calerror("Cannot open '$afile': $!\n",1);  }
	$amsg = "$acnt entries has been added to addressbook $who<br>";
	if($dmsg) { 
	    $tmp = "<br><b>The following outdated entries have been updated.</b><br>";
	    $amsg .= $tmp;
	}
    } else {
	calerror("Your input does not include any VCARD entry. Your addressbook was not modified.", -1);
    }
    return ($amsg, $imsg);    
}
#=====================================================================================================
sub canonicalAtt {
    my ($s, $t);  my ($in)=(@_);  my %hh=(); my @members=();  my @tmp = split(/[:;,]/, $in);
    for $t (@tmp) {
	if($t =~ /.+\@.+/ and ! -d "$::o{'spooldir'}/$t") { $s = findWhoFromEmail($t); if($s) {$t=$s;}}
	if(! exists $hh{$t} ) {   push(@members, $t);  $hh{$t} = 1;}
    }
    $t = join(':', @members);
    return $t;
}
#=====================================================================================================
sub importwork {
    my ($who, $events_ary, $do_not_exit) = (@_);
    my($dfile, $ncnt, $imsg, $acnt, $amsg, $href, $tmp,$eatt, $att, @all, $mem, $cmsg, $pmsg, $toall);
    $who = untaintname($who);
    $dfile = "$::o{'spooldir'}/$who/data";
    $ncnt = 0+@$events_ary;
    $acnt = 0;
    $amsg = $imsg = $att = $eatt = $cmsg =  $pmsg = "";
    $toall = ismember($who, $::o{'corporate_calendar'});
    if( $ncnt > 0) {
	my ($cnt, $role, $mgp, $ckconflict); 
	if(!$toall) {
	    if($::calinfo{'mattendants'}) {  $att = $::calinfo{'mattendants'}; } else {$att="";}
	    if(defined $::calinfo{'smtgp'}) {$mgp = $::calinfo{'smtgp'};} else {$mgp="";}
	    if($mgp eq "$::phr{'none'}") { $mgp = "";}
	    if($att and $mgp) { $att .= ",". $mgp;}
	    else { $att = $att ? $att : $mgp;}
	    $att =~ s/\\//g; $att =~ s/\'//g; $att =~ s/[,; ]+/:/g; $att =~ s/:$//g; 
	    $att = canonicalAtt($att);
	    if($att) {
		if( ! ismember($who, $att) ) { $att .= ":$who";}
		my ($tmp);  $eatt = $att; $eatt = expandMeetingGroups($who, $eatt);
	    }
	    $::calinfo{'mattendants'} = $att;
	}
	if($::d{'remote_user'} eq 'anonymous' and $::calinfo{'aap'}) { $::calinfo{'mattendants'} = "";}
	# ==========================================	
	&get_moderated_calendars(); 
	my $moderated=0;
	if($::moderated{$who} and not isre($::d{'remote_user'}, $who, 'editors')) {$moderated=1;}
	# ========check for time conflict==========
	if($::calinfo{'aol'} or $eatt or ($::calinfo{'ol'} and $::calinfo{'ol'} >1)) {
	    my ($dock, $chme, @tmem, $mem, $atten, %hh, $force); 
	    $dock= $::calinfo{'aol'} || 0;
	    $atten = $eatt; $atten =~ s/[,; ]+/:/g; $atten =~ s/:$//g; (@tmem) = split(/:/, $atten);
	    $force = 0; if($::calinfo{'ol'} and $::calinfo{'ol'}>1) { $force=-1;} 
	    %hh=();
	    if(not ($dock || $force)) {
		for $mem (@tmem) {
		    next if $mem eq $who;
		    if(!exists $hh{$mem}) { $hh{$mem}=1; my $tmp = getinfo($mem, 'ol'); if($tmp and $tmp > 1) { $force=-1;} }
		}
	    }
	    $dock = $dock || $force;
	    if($dock) {
		doReadFile("$dfile");
		for $href (@$events_ary) {
		    if($href->{'kind'} & 1) { # check conflict for appointment and meeting ONLY
			my $timespec = &gettimespec($href);
			my $tmp = checkOverlap($timespec, $att, $who, $dock, $href->{'what'});
			if($tmp) { $cmsg .= "$tmp\n";}
		    }
		}
	    }
	    if($cmsg) {
		if($do_not_exit) {return(0, $cmsg);}
		handle_acknowledgement(10, $cmsg, 0, "");
		myexit(0);
	    }
	}
	# ========end of conflict checking==========	
	my $ii=0;
	my @vevents =();
	my $tauthor=$::d{'remote_user'}; if($tauthor eq 'anonymous') { $tauthor = 'ANONYMOUS';}
	for $href (@$events_ary) { 
	    $href->{'author'} = $tauthor;
	    if($toall) {
		if($href->{'seq'}) { $href->{'seq'} = "C" .  $href->{'seq'};}
		else { $href->{'seq'} = "C" . time . "_$ii"; $ii++;}
		delete $href->{'attendants'};
	    }
	}
	my $fhvcc = gensym;
	if(sysopen($fhvcc, "$dfile", O_WRONLY | O_CREAT, 0644)) {	
	    if( ! &webcalLock::doflock( \*$fhvcc, LOCK_EX, "$dfile")) {
		if($do_not_exit) { return(0, "Cannot lock file '$dfile': $!\n");}
		calerror("Cannot lock file '$dfile': $!\n",1);
	    }
	    $cnt = do  "$dfile"; $cnt++;

	    for $href (@$events_ary) {
		my $in = eventInCalendar(\@::caldata, $href);
		if($in) {  $href->{'in'} = $who; }
	    }
	
	    for $href (@$events_ary){ 
		$href->{'key'}=$cnt;
		if(!$toall) {
		    if($att){
			my $mk = $who . "_eMe_" . $cnt; $href->{'mkey'} = $mk; 
			if($href->{'attendants'}) {
			    my $tmp = $href->{'attendants'} .  ":$att"; 
			    my $smp = canonicalAtt($tmp);
			    $href->{'attendants'} = $smp;
			} else {$href->{'attendants'}=$att;}
		    } elsif($href->{'attendants'}) {
			my $tmp = $href->{'attendants'}; 
			my $smp = canonicalAtt($tmp);
			$href->{'attendants'} = $smp;		
		    }
		}
		$cnt++;
	    }
	
            truncate($fhvcc, 0);
	    print $fhvcc "\@::caldata = (\n";
	    for $href (@::caldata) {
		if( ! $href->{'end'} ) { my $enddate = findEndDateHref($href); if($enddate) { $href->{'end'} = $enddate;}}
		$tmp = print1Entry($href);
		print $fhvcc $tmp;
	    }
	    for $href (@$events_ary) { 
		if(exists $href->{'in'} and  $href->{'in'} eq $who) {
		    my ($da, $st, $td,$tm,$ty, $th, $tmn, $dstr, $tstr, $what, $kind, $clr);
		    $da = $href->{'date'}; ($tm, $td, $ty) = split(/\//, $da); $tm--;  $dstr = mdy_string($tm, $td, $ty);
		    $st = $href->{'start'}; ($th, $tmn) =split(/:/, $st);  $tstr=hm_string($th, $tmn);
		    $what = $href->{'what'};
		    if($href->{'kind'} == 1) {$clr="$::o{'tclra'}";}
		    elsif($href->{'kind'}==2){$clr="$::o{'tclrt'}";}
		    elsif($href->{'kind'}==3){$clr="$::o{'tclrm'}";}
		    else {$clr="$::o{'tclrs'}";}
		    my $tmsg = "<font color=$clr>$dstr $tstr</font> &nbsp; &nbsp;<b>$what</b><br>";
		    $imsg .= $tmsg;
		} else {
		    $acnt++;
		    if( ! $href->{'end'} ) { my $enddate = findEndDateHref($href); if($enddate) { $href->{'end'} = $enddate;}}
		    if($moderated) {
			$href->{'pnd'}=1;  &markHasPending("$::o{'spooldir'}/$who/pnd");
		    }
		    $tmp = print1Entry($href);
		    if($moderated) {delete $href->{'pnd'};}
		    print $fhvcc $tmp;		    
		    if($toall) { push @vevents, $href;}
		}
	    }
	    print $fhvcc ");\n$cnt;\n";
	    if(not &webcalLock::doflock( \*$fhvcc, LOCK_UN,"$dfile")) {
		if($do_not_exit) { return(0,"Cannot unlock file '$who/data': $!\n");}
		calerror("Cannot unlock file '$who/data': $!\n",1);
	    }
	    close $fhvcc;	    
	    if($toall) {insert_to_all(\@vevents, $who);}
	} else {
	    if($do_not_exit) { return(0,"Cannot open '$who/data': $!\n");}
	    calerror("Cannot open '$who/data': $!\n",1);  
	}

	$amsg = "$acnt event(s) has been added to calendar $who<br>";	
	if($imsg and $eatt) { $imsg = "<b>====== On calendar \"$who\" ======</b><br>" . $imsg;}
	
	# modify other calendars
	if($eatt) {
	    $eatt =~ s/[,; ]+/:/g;
	    $eatt =~ s/:$//g;
	    my(@all) = split(/:/, $eatt);
	    my (@mem, $s, $tcnt, $zmsg);
	    @mem = ();
	    foreach $s (@all) { if($s ne $who and ( -d "$::o{'spooldir'}/$s")) { push(@mem, $s);}}
#=======================
	    my $ok_2_write = &read_permission_table(); 
#=======================
	    foreach $s (@mem) {
		$tcnt = 0;
		$zmsg = "";
		$s = untaintname($s);
		$dfile = "$::o{'spooldir'}/$s/data";
		if( -f $dfile) {
#=======================
		    if(!($ok_2_write or is_authorized_author($::d{'remote_user'}, $s))) { $pmsg .= "$s, "; next;}
#=======================		    
		    @::caldata=();
		    my $fhvvc = gensym;
		    if(sysopen($fhvvc, "$dfile", O_WRONLY | O_CREAT, 0644 )) {
			if(not &webcalLock::doflock( \*$fhvvc, LOCK_EX,"$dfile")) {
			    if($do_not_exit) { return(0, "Cannot open '$who/data': $!\n");}
			    calerror("Cannot lock file '$who/data': $!\n",1);
			}
			$cnt = do "$dfile"; $cnt++;
			for $href (@$events_ary){ $href->{'key'}=$cnt; $cnt++;}
			for $href (@$events_ary) {
			    my $in = eventInCalendar(\@::caldata, $href);
			    if( $in) {  $href->{'in'} = $s;}
			}
			truncate($fhvvc,0);
			print $fhvvc "\@::caldata = (\n";
			for $href (@::caldata) {
			    if( ! $href->{'end'}){my $enddate=findEndDateHref($href); if($enddate){$href->{'end'}=$enddate;}}
			    $tmp = print1Entry($href);
			    print $fhvvc $tmp;
			}
			# new events
			my $moderated=0;
			if($::moderated{$s} and not isre($::d{'remote_user'}, $s, 'editors')) {$moderated=1;}			
			for $href (@$events_ary) { 
			    if(exists $href->{'in'} and  $href->{'in'} eq $s ) {
				my ($da, $st, $td,$tm,$ty, $th, $tmn, $dstr, $tstr, $what, $kind, $clr);
				$da = $href->{'date'}; ($tm, $td, $ty) = split(/\//, $da); $tm--; 
				$dstr = mdy_string($tm, $td, $ty);
				$st = $href->{'start'}; ($th, $tmn) =split(/:/, $st);  $tstr=hm_string($th, $tmn);
				$what = $href->{'what'};
				if($href->{'kind'} == 1) {$clr="$::o{'tclra'}";}
				elsif($href->{'kind'}==2){$clr="$::o{'tclrt'}";}
				elsif($href->{'kind'}==3){$clr="$::o{'tclrm'}";}
				else {$clr="$::o{'tclrs'}";}
				my $tmsg = "<font color=$clr>$dstr $tstr</font> &nbsp; &nbsp;<b>$what</b><br>";
				$zmsg .= $tmsg;
			    } else {
				$tcnt++;
				if(! $href->{'end'}){my $enddate=findEndDateHref($href);if($enddate){$href->{'end'} = $enddate;}}
				if($moderated){
				    $href->{'pnd'}=1;  &markHasPending("$::o{'spooldir'}/$who/pnd");
				}
				$tmp = print1Entry($href);
				if($moderated){delete $href->{'pnd'};}
				print $fhvvc $tmp;		    
			    }
			}
			print $fhvvc ");\n$cnt;\n";
			if(not &webcalLock::doflock( \*$fhvvc, LOCK_UN,"$dfile")) {
			    if($do_not_exit) {return(0,"Cannot unlock file '$who/data': $!\n");}
			    calerror("Cannot unlock file '$who/data': $!\n",1);
			}
			close $fhvvc;	    			
			if($zmsg) {  $imsg .= "<br><b>====== On calendar \"$s\" ======</b><br>" . $zmsg; }
			$amsg .= "<br> $tcnt event(s) has been added to calendar $s";
		    }
		}
	    }
	}
    } else {
	if($do_not_exit) { return(0, "Data contains no EVENTS");}
	calerror("Your input does not include any EVENTS.",-1);
    }
    if($do_not_exit) {
	$amsg =~ s#<b>|</b>##g; $amsg =~ s/<br>/   \n/g;   
	$imsg =~ s#<b>|</b>##g; $imsg =~ s/<br>/   \n/g;   
	if($pmsg) { $amsg .= "You are not authorized to write to the following calendars:\n  $pmsg";}
	return(1, "\n   $amsg\n$imsg");
    } 
    if($pmsg) { $pmsg = "You are not authorized to write to the following calendars:<br> $pmsg";}
    return ($amsg . $pmsg, $imsg);
}
#=====================================================================================================
sub getIUploaddirFullURL {
    my $imgurl = "$::o{'fimgdirurl'}/$::o{'uploadsubdir'}";
    if( $imgurl !~ /^http:/) {
	my $tmp = $::o{'fcginame'};
	if($tmp =~ /(http:\/\/[^\/]+)\//i) { $imgurl = $1 . $imgurl;}
    }
    return $imgurl;
}
#=====================================================================================================
sub toVcal {
    my ($href, $who, $privacy)=(@_);
    my (@gm, $msg, $kind, $month, $day, $year, $tim, $smn, $shr, $emn, $ehr, $duration,$tz, $jnk, $event, $pri, $etz);
    my ($emonth, $eday, $eyear, $dtstart, $dtend, $summary, $desc, $attendee, $utmp, $uid, $room, $url, $due);
    my ($cat, $icat, $ctd, $class, $rule, $aalarm, $dalarm, $malarm, $utime, $exdate, $sshr, $ssmn, $xtend);

    $etz = getinfo($who, 'tzone'); 
    # convert start date/time to UTC
    ($month, $day, $year) = split(/\//, $href->{'date'}); $month -= 1;
    $kind = $href->{'kind'};
    $tim = $href->{'start'};
    ($sshr, $ssmn) = ($shr,$smn)=split(/:/,$tim);
    $tz = getinfo($who, 'tzone');
    @gm = localToUTC(0, $smn, $shr, $day, $month, $year - 1900, $tz);
    ($jnk, $smn, $shr, $day, $month, $year, $tz)=(@gm); $year += 1900;

    # deal with reminders
    $aalarm= $dalarm= $malarm = $xtend = ""; 
    my ( $reminder, $mail, $mailu, $maili, $maily, $popup, $popupi, $popupu, $popupy, $flash, $flashi, $flashu, $flashy,
	 $chime, $chimei, $chimeu, $chimey, $junk, $mailT, $popupT, $chimeT, @pws, @mailT, @popupT, @chimeT, $ta, $gm7);
    $reminder = $href->{'rem'};
    ($flash,$mail,$popup, $chime)=split(/,/, $reminder);
    (undef, $maily, $maili,$mailu) = split(/:/, $mail);
    (undef, $popupy, $popupi,$popupu) = split(/:/, $popup);
    (undef, $chimey, $chimei,$chimeu) = split(/:/, $chime);
    (undef, $flashy, $flashi,$flashu) = split(/:/, $flash);
    @mailT=(); @popupT=(); @chimeT=();
    if($maily eq 'y') {
	@pws = split(/;/,$maili);
	foreach $ta (@pws) { push @mailT, warntime($ta, $mailu);}
    } 
    if($popupy eq 'y'){
	@pws = split(/;/,$popupi);
	foreach $ta (@pws) { push @popupT, warntime($ta, $popupu);}
    } elsif($flashy eq 'y') {
	@pws = split(/;/,$flashi);
	foreach $ta (@pws) { push @popupT, warntime($ta, $flashu);}
    }
    if($chimey eq 'y'){
	@pws = split(/;/,$chimei);
	foreach $ta (@pws) { push @chimeT, warntime($ta, $chimeu);}
    }
    $gm7=$gm[7];
    # end remender

    $room=""; $pri=""; $dtend = ""; $due="";
    $kind = $href->{'kind'};
    $utmp= $href->{'key'};
    $uid="$who-$kind-$utmp";
    if($href->{'privacy'}) {$utmp=$href->{'privacy'};} else {$utmp="";}
    if($utmp ne "ostxti") { $class = "PRIVATE";} else {$class ="";}

    my ($endmonth, $endday, $endyear,$enddate);
    $enddate = $href->{'end'}; if(!$enddate) {$enddate= findEndDateHref($href);}
    ($endmonth, $endday, $endyear) = split(/\//, $enddate); $endmonth -= 1;
    my @ggm = localToUTC(0, $ssmn, $sshr, $endday, $endmonth, $endyear - 1900, $tz);
    ($jnk, $jnk, $jnk, $endday, $endmonth, $endyear, $jnk)=(@ggm); $endyear += 1900;   
    
    if($kind == 2) {
	$event="VTODO";
	if($href->{'ctd'}) {
	    my ($cmn, $cdy, $cyr, $chr, $cmi) = split(/\//, $href->{'ctd'});
	    $cmn -= 1; $cyr -= 1900;
	    ($jnk,$cmi, $chr, $cdy, $cmn, $cyr) = localToUTC(0, $cmi, $chr, $cdy, $cmn, $cyr, $tz);
	    $ctd = sprintf "%4d%02d%02dT%02d%02d00Z", $cyr+1900, $cmn+1, $cdy, $chr, $cmi;
	}
	if($href->{'pri'}) { $pri = $href->{'pri'};}
	$due = sprintf "%4d%02d%02dT%02d%02d00Z", $year, $month+1, $day, $shr, $smn;
	my $zd; if($href->{'bdate'}) { $zd = $href->{'bdate'};} else {$zd = $href->{'date'};}
	my($smo, $sdy, $syr) = split(/\//, $zd); $syr -= 1900; $smo -= 1;
	@gm = localToUTC(0, $sshr, $ssmn, $sdy, $smo, $syr, $tz);
	my($ahr, $amn);
	($jnk, $ahr, $amn, $sdy, $smo, $syr, $jnk) =(@gm);
	$dtstart = sprintf "%4d%02d%02dT%02d%02d00Z", $syr+1900, $smo+1, $sdy, $ahr, $amn;
	$xtend = sprintf "%4d%02d%02dT%02d%02d00Z", $endyear, $endmonth+1, $endday, $shr, $smn;
    } else {
	$event="VEVENT"; 
	if( $kind != 4) {
	    if($href->{'duration'}) { $duration = $href->{'duration'};} else {$duration = 0;}
	    $utmp=$smn+$duration;
	    $ehr=$shr + int($utmp/60);
	    if($ehr >= 24) {
		$ehr -= 24;
		($emonth, $eday, $eyear) = canDate($endmonth, $endday + 1, $endyear);
	    } else {
		($emonth, $eday, $eyear) = ($endmonth, $endday, $endyear);
	    }
	    $emn = $utmp % 60;
	    $xtend = sprintf "%4d%02d%02dT%02d%02d00Z", $eyear, $emonth+1, $eday, $ehr, $emn;
	} 
	$dtstart = sprintf "%4d%02d%02dT%02d%02d00Z", $year, $month+1, $day, $shr, $smn;
    }
    if($href->{'repeat'} and $href->{'repeat'} > 1) {
	$rule = vrule($href);
	$exdate = exdates($who, $href);
	if(($kind & 1)) {
	    if($href->{'duration'}) { $duration = $href->{'duration'};} else {$duration = 0;}
	    $utmp=$smn+$duration;  $ehr=$shr + int($utmp/60);
	    my ($tm, $td, $ty);
	    if($ehr >= 24) { $ehr -= 24; ($tm, $td, $ty) = canDate($month, $day + 1, $year);}
	    else { ($tm, $td, $ty) = ($month, $day, $year);}
	    $emn = $utmp % 60;
	    $dtend = sprintf "%4d%02d%02dT%02d%02d00Z", $ty, $tm+1, $td, $ehr, $emn;
	}
    } else { $rule =""; $exdate=""; $dtend = $xtend;}

    my $imgurl = &getIUploaddirFullURL; 
    $desc="";
    if($privacy > 1) {
	$summary = $href->{'what'}; $summary="" if ! $summary;
	$summary =~ s/\\?\^o\^\//$imgurl\//g;
    } else {
	$summary = $::phr{'Protected'};
    }  if(!$summary) { $summary = "";}
    $summary =~ s/\n\s*$//g;
    $summary =~ s/\n/=0D=0A=\n/g;
    $attendee = "";

    if($privacy > 2) {
	if($href->{'detail'}) {
	    $desc = $href->{'detail'};
	    $desc =~ s/\n\s*$//g;
	    $desc =~ s/\n/=0D=0A=\n/g;
	    $desc =~ s/\\?\^o\^\//$imgurl\//g;
	}
	if($href->{'room'}) { $room = $href->{'room'};}
	if($href->{'cat'}) { $icat = ";$href->{'cat'}";} else { $icat="";}
	if($kind == 1) { $cat = "APPOINTMENT$icat";}
	elsif($kind == 3) {$cat = "MEETING$icat";}
	elsif($kind == 4) {$cat = "SPECIAL OCCASION$icat";}
	else { if($href->{'cat'}) {$cat = $href->{'cat'}; } else {$cat = "";}}

	my ($att, @members, %rhash, $name, $tmp, $others, $mkey);
	if($href->{'attendants'}) {$att = $href->{'attendants'};} else {$att="";}
	$att =~ s/[,; ]+/:/g;
	$mkey = $href->{'mkey'}; if(!$mkey) { $mkey = "";}
        $mkey =~ s/_eMe_\d+//g;
	if(!$mkey) { $mkey = $who;}
	$others=expandMeetingGroups($mkey, $att);
	(@members) = split(/:/, $others); 
	%rhash = ();
	for $name (@members) {
	    if (! exists $rhash{$name}) {
		$_ = $name;
		$tmp ="";
		if(/.+\@.+/) { $tmp = $name;}
		else { $tmp = getinfo($name, 'email');}
		if(! $tmp) { $tmp = $name;}
		$rhash{$name} = $tmp;
	    }
	}
	for $name (@members) {
	    if($name) {$attendee .= "ATTENDEE:mailto:$rhash{$name}\n";}
	}
	$url = $href->{'url'} if $href->{'url'};
    }
    $msg = "BEGIN:$event\n";
    if($etz) { $msg .= "TZ:$etz\n";}
    $msg .= "DTSTART:$dtstart\n";
    if($dtend) { $msg .= "DTEND:$dtend\n";}
    if($xtend) { $msg .= "X-DTEND:$xtend\n";}
    if($due) { $msg .= "DUE:$due\n";}
    if($rule) {$msg .= "RRULE:$rule\n";}
    if($summary) { $msg .= "SUMMARY;ENCODING=QUOTED-PRINTABLE:$summary\n";}
    if($desc) { $msg .= "DESCRIPTION;ENCODING=QUOTED-PRINTABLE:$desc\n";}
    if($attendee) {$msg .= "$attendee";}
    if($room) {$msg .= "LOCATION:$room\n";}
    if($cat) { $msg .= "CATEGORIES:$cat\n";}
    if($ctd) { $msg .= "COMPELETED: $ctd\n";}
    if($pri) { $msg .= "PRIORITY: $pri\n";}
    if($exdate) { $msg .= "EXDATE: $exdate\n";}

    if($privacy > 2) {
	if(scalar(@popupT) > 0) {
	    foreach $popupT (@popupT) {
		my @z = gmtime($gm7-$popupT);
		$dalarm=sprintf "%4d%02d%02dT%02d%02d00Z", $z[5]+1900,$z[4]+1,$z[3],$z[2],$z[1];
		$msg .= "DALARM:$dalarm; ; ;\n";
	    }
	}
	if(scalar(@mailT)>0) {
	    my $addr = getinfo($who, 'email');
	    foreach $mailT (@mailT) {
		my @z = gmtime($gm7-$mailT);
		$malarm=sprintf "%4d%02d%02dT%02d%02d00Z", $z[5]+1900,$z[4]+1,$z[3],$z[2],$z[1];	
		$msg .= "MALARM:$malarm; ; ;$addr;\n";
	    }
	}
	if(scalar(@chimeT)>0) {
	    my $addr = "$::o{'fimgdirurl'}/chimes.au";
	    foreach $chimeT (@chimeT) {
		my @z = gmtime($gm7-$chimeT);
		$aalarm=sprintf "%4d%02d%02dT%02d%02d00Z", $z[5]+1900,$z[4]+1,$z[3],$z[2],$z[1];	
		$msg .= "AALARM;VALUE=URL:$aalarm; ; ;$addr\n";
	    }
	}

	if($url) { $msg .= "URL:$url\n";}
	if($class) { $msg .= "CLASS:$class\n";}
	$msg .= "UID:$uid\n";
	if($href->{'ctp'}) {
	    my $tmp = $href->{'ctp'};
	    $msg .= "X-CONTACT-PERSON:$tmp\n";
	}
	if($href->{'ctm'}) {
	    my $tmp = $href->{'ctm'};
	    $msg .= "X-CONTACT-EMAIL:$tmp\n";
	}
	if($href->{'spkr'}) {
	    my $tmp = $href->{'spkr'};
	    $msg .= "X-SPEAKER:$tmp\n";	
	}
    }

    $msg .= "END:$event";    
    $msg =~ s/\\?\^o\^\//$imgurl\//g;	
    $msg =~ s/\n/\015\012/g;
    return "$msg";
}
#=====================================================================================================
sub exdates {
    my ($who, $href) =(@_);
    my ($exception, $elength, $i, $j, $k, $start, $shr, $smn, $tim, $tz, @gm, $jnk, $month, $day, $year, $date, $ans,$tmp);
    my ($sshr, $ssmn);
    $tim = $href->{'start'};
    ($shr,$smn)=split(/:/,$tim);
    $tz = getinfo($who, 'tzone');
    $exception = $href->{'exception'};
    $ans="";
    if($exception) {
	my $edate = $href->{'date'};
	my ($emn, $edy, $eyr) = split(/\//, $edate); $emn--;
        my @alldates = getAllDates($emn, $edy, $eyr, $href->{'occurs'}, $href->{'repeat'});

        $elength = $#$exception;
	$k = 0;
        for $i (0.. $elength) {
            $j = abs($exception->[$i]);
            $date = $alldates[$j-1];
            ($month, $day, $year) = split(/\//, $date);  #month is in 1--12
            if($day) {
		$month--;
		$k++;
                @gm = localToUTC(0, $smn, $shr, $day, $month, $year - 1900, $tz);
                ($jnk, $ssmn, $sshr, $day, $month, $year, $tz)=(@gm); $year += 1900;
                $tmp = sprintf "%4d%02d%02dT%02d%02d00Z;", $year, $month+1, $day, $sshr, $ssmn;
		if($k > 3) { $k = 0; $ans .= "=0D=0A=\n";}
                $ans .= $tmp;
            }
        }
    }
    return $ans;
}
#=====================================================================================================
sub vrule {
    use integer;
    my ($href) = (@_);
    my($occurs, $repeat, $rule, $mn, $dy, $yr, $tmp);
    $occurs = $href->{'occurs'};
    $repeat = $href->{'repeat'};
    if ($occurs eq "Daily") {
	$rule = "D1 \#$repeat"; 
    } elsif ( $occurs eq "Weekly") {
	$rule = "W1 \#$repeat"; 
    } elsif ($occurs eq "Every2Weeks") {
	$rule = "W2 \#$repeat"; 
    } elsif ($occurs eq "MonthlyByDate") {
	$tmp = $href->{'date'};
	($mn, $dy, $yr) = split(/\//, $tmp);
	$rule = "MD1 $dy \#$repeat";
    } elsif ($occurs eq "MonthlyByWeekday") {
	$tmp = $href->{'date'};
	($mn, $dy, $yr) = split(/\//, $tmp);   $mn -= 1;
	my $wday = wday($mn, $dy, $yr); $tmp = $::swd[$wday];
	my $nth = whichWeekday($mn, $dy,$yr);
	$rule = "MP1 $nth+ $tmp \#$repeat"; 
    } elsif ($occurs eq "Yearly") {
	$tmp = $href->{'date'};
	($mn, $dy, $yr) = split(/\//, $tmp); 
	$rule = "YM1 $mn \#$repeat"; 	
    } elsif ($occurs eq "YearlyByMonthWeekday") {
	$tmp = $href->{'date'};
	($mn, $dy, $yr) = split(/\//, $tmp);   $mn -= 1;
	my $wday = wday($mn, $dy, $yr); $tmp = $::swd[$wday];
	my $nth = whichWeekday($mn, $dy,$yr);
	$rule = "MP12 $nth+ $tmp \#$repeat"; 
    } elsif ($occurs eq "MTWThF") {
	$rule = "W1 $::swd[1] $::swd[2] $::swd[3] $::swd[4] $::swd[5] \#$repeat";
    } elsif ($occurs eq "MWF") {
	$rule = "W1 $::swd[1] $::swd[3] $::swd[5] \#$repeat";
    } elsif ($occurs eq "TTh") {
	$rule = "W1 $::swd[2] $::swd[4] \#$repeat";
    } elsif ($occurs eq "EveryOtherDay") {
	$rule = "D2 \#$repeat";
    } elsif ($occurs eq "Every3rdDay") {
	$rule = "D3 \#$repeat";
    } elsif ($occurs eq "Every4thDay") {
	$rule = "D4 \#$repeat";
    } elsif ($occurs eq "Every5thDay") {
	$rule = "D5 \#$repeat";
    } elsif ($occurs eq "Every6thDay") {
	$rule = "D6 \#$repeat";
    } elsif(substr($occurs,0,1) eq 'Z' and $occurs =~ /^Z(.+),(\d+),(\d*)/ ) {
	my ($word, $c1, $c2) =($1, $2, $3);
	if($word eq 'D') { 
	    $rule = "D$c1 \#$repeat";	    
	} elsif($word eq 'MD') {
	    $tmp = $href->{'date'};
	    ($mn, $dy, $yr) = split(/\//, $tmp);
	    $rule = "MD$c1 $dy \#$repeat";
	} elsif($word eq 'MWD') {
	    $tmp = $href->{'date'};
	    ($mn, $dy, $yr) = split(/\//, $tmp);   $mn -= 1;
	    my $wday = wday($mn, $dy, $yr); $tmp = $::swd[$wday];
	    my $nth = whichWeekday($mn, $dy,$yr);
	    $rule = "MP$c1 $nth+ $tmp \#$repeat"; 
	} elsif($word eq 'MND') {
	    $tmp = $href->{'date'};
	    ($mn, $dy, $yr) = split(/\//, $tmp);
	    my $mxdays = ndays_in_month($mn, $yr);
	    my $off = $mxdays - $dy + 1;
	    $rule = "MD$c1 $off- \#$repeat";
	} elsif($word eq 'MNW') {
	    $tmp = $href->{'date'};
	    ($mn, $dy, $yr) = split(/\//, $tmp);   $mn -= 1;
	    my $wday = wday($mn, $dy, $yr);	$tmp = $::swd[$wday];
	    my $mxdays = ndays_in_month($mn, $yr);
	    my $nth =  1 + ($mxdays-$dy)/7;	# the nth weekday, counting backwards
	    $rule = "MP$c1 $nth- $tmp \#$repeat"; 
	} elsif($word eq 'W') {
	    my ($i, $s, $t); $s="";
	    for($i = 0; $i < 7; $i++) { if($c2 & (1<<$i)) {$t = $::swd[$i]; $s .= " $t";}}
	    $rule = "W$c1 $s \#$repeat";
	} elsif($word eq 'X') {
	    my ($i, $s, $t); $s="";
	    $rule = "WD$c1 \#$repeat $c2";
	}
    }    
    return $rule;
}
		  
#=====================================================================================================
# convert from local to UTC 
sub localToUTC {
    my ($sec, $min,$hour,$mday, $mon, $year, $tzone) = (@_);
    my ($then, $now, @now, @then, $t1, $t2);
    delete $ENV{TZ};   $ENV{TZ} =$tzone if $tzone;

    $t1 = timeLocal($sec, $min,$hour,$mday, $mon, $year+1900, $tzone);
    $now = time;
    @now = localtime($now);          # now to a-fixed-date in seconds
    $now[5] += 1900;
    $t2 = timeLocal(@now); 
    if( $now[8]) {$t2 -= 3600;}      # daylight saving time adjustment
    $then = $now - $t2 + $t1;        # time of then
    @then = localtime($then);
    if( $then[8]) {$then -= 3600;}   # daylight saving time adjustment

    my @gm = gmtime($then);
    return( ($gm[0], $gm[1], $gm[2], $gm[3], $gm[4], $gm[5], $tzone, $then));
}

# convert from UTC to local  
sub UTCToLocal {
    my ($sec, $min,$hour,$mday, $mon, $year, $tzone) = (@_);
    my ($then, $now, @now, @then, $t1, $t2, $delta);
    $t1 = timeLocal($sec, $min,$hour,$mday, $mon, $year+1900, $tzone);
    $now = time;
    @now = gmtime($now);             # now to a-fixed-date in seconds
    $now[5] += 1900;
    $t2 = timeLocal(@now); 
    $then = $now - $t2 + $t1;        # time of then
    delete $ENV{TZ};   $ENV{TZ} =$tzone if $tzone;

    my @lm = localtime($then);    
    return( ($lm[0], $lm[1], $lm[2], $lm[3], $lm[4], $lm[5],$tzone, $then));
}
#=====================================================================================================
sub rfc2822_datetime {
    my $zone = strftime "%z", localtime;
    my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time);
    my @mons  = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
    my @wdays = qw(Sun Mon Tue Wed Thu Fri Sat);
    $mon = $mons[$mon];
    $wday = $wdays[$wday];
    $year +=  1900; $mday = sprintf("%02d", $mday);
    my $time = sprintf("%02d:%02d:%02d", $hour,$min,$sec);
    return "$wday, $mday $mon $year $time $zone";
}
#=====================================================================================================
sub parseVcal {
    use integer;
    my ($who, $des) = (@_);
    my ($a, @f, $n, $p, $v, $b, @ves, $hash, %thash, @events, $tz, $etz, $remote_user);
    $tz = getinfo($who, 'tzone'); if(!$tz) { $tz = undef;} $etz = undef;
    my %events = ();
    if($::d{'remote_user'}) {$remote_user = $::d{'remote_user'};} else {$remote_user=$who;}
    $des =~ s/\r\n/\n/g;
    $des =~ s/\r/\n/g;
    $des =~ s/=0D=0A=?\n/ /g;    
    $des =~ s/\n\W*:/:/g;
#    $des =~ s/\n\s+/\n/g;
    $des =~ s/\n\s//g;

    @ves = (); @events = ();
    $_ = $des;
    # separate vevents
    while(/(END:\s*VEVENT)|(END:\s*VTODO)/i) {	push @ves, "$`$&";	$_=$';    }
    # parse events
    for $b (@ves) {
	@f = split(/\n/, $b);
	%thash = ();
	my ($todo, $meeting, $appointment, $special) = (0, 0, 0, 0);
	my @attendee = ();
	for $a (@f) {
	    ($n, $v) = split(/:/, $a, 2); 
	    next if not $n or not $v;
	    ($n, $p) = split(/;/, $n, 2); 
	    $n=~ s/^\s+//g; $n=~ s/\s+$//g; #;
	    $v=~ s/^\s+//g; $v=~ s/\s+$//g; #;
	    $n = uc($n);
	    if($n eq 'BEGIN') {	
		if( $v =~ m/VTODO/i) { $todo = 1;}   
	    } elsif($n eq 'DTSTART') {
		$thash{$n} = $v;
	    } elsif($n eq 'DTEND') {
		$thash{$n} = $v;
	    } elsif($n eq 'X-DTEND') {
		$thash{$n} = $v;
	    } elsif($n eq 'DUE') {
		$thash{$n} = $v;
	    } elsif($n eq 'TZ') {
                $etz = $v;
	    } elsif($n eq 'CATEGORIES') {
		if($v =~ /APPOINTMENT/) { $appointment = 1;}
		elsif($v =~ /MEETING/) { $meeting = 1;}
 		elsif($v =~ /SPECIAL\s*OCCASION/) { $special = 1;}
 		elsif($v =~ /VACATION/) { $special = 1;}
 		elsif($v =~ /SICK\s*DAY/) { $special = 1;}
 		elsif($v =~ /HOLIDAY/) { $special = 1;}
		my ($a,$b)= split(/;/, $v, 2);
		if($b) { $thash{$n} = $b;}
	    } elsif($n eq 'SUMMARY') {
		$thash{$n} = $v;
	    } elsif($n eq 'DESCRIPTION') {
		$thash{$n} = $v;
	    } elsif($n eq 'ATTENDEE') {
		if( $v =~ /mailto:/) { push(@attendee, $');}
	    } elsif($n eq 'AALARM') {
		my ($tm, $jnk) = split(/;/,$v,2);
		if(!$thash{$n}) {$thash{$n} = $tm; } else {$thash{$n} .= ",$tm";}
	    } elsif($n eq 'DALARM') {
		my ($tm, $jnk) = split(/;/,$v,2);
		if(!$thash{$n}) {$thash{$n} = $tm; } else {$thash{$n} .= ",$tm";}
	    } elsif($n eq 'MALARM') {
		my ($tm, $jnk) = split(/;/,$v,2);
		if(!$thash{$n}) {$thash{$n} = $tm; } else {$thash{$n} .= ",$tm";}
	    } elsif($n eq 'CLASS') {	
		$thash{$n} = $v;	
	    } elsif($n eq 'LOCATION') {	
		$thash{$n} = $v;	
	    } elsif($n eq 'RRULE') {	
		$thash{$n} = $v;	
	    } elsif($n eq 'EXDATE') {	
		$thash{$n} = $v;	
	    } elsif($n eq 'PRIORITY') {	
		$thash{$n} = $v;	
	    } elsif($n eq 'URL') {	
		$thash{$n} = $v;	
	    } elsif($n eq 'COMPLETED') {	
		$thash{$n} = $v;	
	    } elsif($n eq 'X-CONTACT-PERSON') {	
		$thash{$n} = $v;	
	    } elsif($n eq 'X-CONTACT-EMAIL') {	
		$thash{$n} = $v;	
	    } elsif($n eq 'X-SPEAKER') {	
		$thash{$n} = $v;	
	    } else {
		; #ignore
	    }
	}
	# convert to webCalendar event
	my ($fr, $mr, $pr, $cr)=('rf:n:5:m','rm:n:5:m','rp:n:5:m','rc:n:5:m');
	$hash = {};
	if($todo) { $hash->{'kind'} = 2;}
	elsif($meeting) { $hash->{'kind'} = 3;}
 	elsif($special) { $hash->{'kind'} = 4;}
	elsif($thash{'DTSTART'}) {$hash->{'kind'} = 1;}
	else { $hash->{'kind'} = 4;}
	if($thash{'DTSTART'}) {
	    my($date, $time, $start, $edate, $etime, $end);
	    ($date, $time, $start) = vtime($thash{'DTSTART'}, $tz, $etz);
	    $hash->{'date'} = $date;
	    $hash->{'start'} = $time;
	    $hash->{'duration'} = 0;
	    $hash->{'author'} = $remote_user . ',vCalendar';
	    if($todo) { $hash->{'bdate'} = $date;}
	    if($thash{'DTEND'}) {
		($edate, $etime, $end) = vtime($thash{'DTEND'}, $tz, $etz);
		my $tmp = ($end - $start)/60; if($tmp < 0) { $tmp = 0;}
		$hash->{'duration'} = $tmp;
	    }
	    if($thash{'DUE'}) {
		($edate, $etime, $end) = vtime($thash{'DUE'}, $tz, $etz);
		$hash->{'date'} = $edate;
		$hash->{'start'} = $etime;
	    }
	    if($thash{'SUMMARY'}) {
		my $tmp = $thash{'SUMMARY'}; $tmp =~ s/\n(\r*\n\s*)+/\n\n/g;
		$hash->{'what'} = $tmp;
	    }
	    if($thash{'DESCRIPTION'}) {
		my $tmp = $thash{'DESCRIPTION'};
		$hash->{'detail'} = $tmp;
	    }	  
	    if($thash{'CATEGORIES'}) { $hash->{'cat'} = $thash{'CATEGORIES'};}
	    if($thash{'COMPLETED'} and $todo) { $hash->{'done'} = 1;}
	    if($thash{'LOCATION'}) { $hash->{'room'} = $thash{'LOCATION'};}
	    if($thash{'URL'}) { $hash->{'url'} = $thash{'URL'};}
	    if($thash{'CLASS'}) {
		my $tmp = $thash{'CLASS'};
		if( $tmp =~ /PRIVATE/i) { $hash->{'privacy'} = 'osn';}
	    }
	    if($thash{'AALARM'}) {
		my ($tms, @list, $a);
		@list = split(/,/, $thash{'AALARM'});
		$tms="";
		foreach $a (@list) {
		    my($ad, $at, $aa) = vtime($a, $tz, $etz);
		    my $tmp = valarm($start - $aa);
		    if(!$tms){ $tms=$tmp;} else { $tms .=";$tmp";}
		}
		$cr="rc:y:$tms:m";
	    }
	    if($thash{'DALARM'}) {
		my ($tms, @list, $a);
		@list = split(/,/, $thash{'DALARM'});
		$tms="";
		foreach $a (@list) {
		    my($ad, $at, $aa) = vtime($a, $tz, $etz);
		    my $tmp = valarm($start - $aa);
		    if(!$tms){ $tms=$tmp;} else { $tms .=";$tmp";}
		}
		$pr="rp:y:$tms:m";
	    }
	    if($thash{'MALARM'}) {
		my ($tms, @list, $a);
		@list = split(/,/, $thash{'MALARM'});
		$tms="";
		foreach $a (@list) {
		    my($ad, $at, $aa) = vtime($a, $tz, $etz);
		    my $tmp = valarm($start - $aa);
		    if(!$tms){ $tms=$tmp;} else { $tms .=";$tmp";}
		}
		$mr="rm:y:$tms:m";
	    }
	    if(0+@attendee > 0) {
		$hash->{'attendants'} = join(',', @attendee);
	    }
	    if($thash{'PRIORITY'}) {	    
		$hash->{'pri'} = $thash{'PRIORITY'};
	    }
	    if($thash{'X-CONTACT-PERSON'}) {	    
		$hash->{'ctp'} = $thash{'X-CONTACT-PERSON'};
	    }
	    if($thash{'X-CONTACT-EMAIL'}) {	    
		$hash->{'email'} = $thash{'X-CONTACT-EMAIL'};
	    }
	    if($thash{'X-SPEAKER'}) {	    
		$hash->{'spkr'} = $thash{'X-CONTACT-EMAIL'};
	    }
	    if($thash{'RRULE'}) {
		my ($repeat, $occurs) = pvrule($thash{'RRULE'});
		if($repeat > 0) {
		    $hash->{'repeat'} = $repeat;
		    $hash->{'occurs'} = $occurs;
		    if($thash{'EXDATE'}) {  
			my $sdate;
			if($hash->{'kind'} == 2) { $sdate = $thash{'DUE'};} else { $sdate =$thash{'DTSTART'};}
			if($sdate) {
			    my $tmp = vexception($sdate,  $thash{'EXDATE'}, $tz, $occurs, $repeat, $etz);
			    if($tmp) { $hash->{'exception'} = eval($tmp);}
			}
		    }
		}
	    } else { $hash->{'repeat'} = 0; $hash->{'occurs'} = "OneTime";}
	    $hash->{'rem'} = "$fr,$mr,$pr,$cr";
	    push(@events, $hash);
	}
    }
    return(@events);
}
#=====================================================================================================
sub vexception {
    my($start, $excepts, $tz, $occurs, $repeat, $etz) =(@_);
    $excepts =~ s/ //g; $excepts =~ s/;$//g;
    my @alldates = split(/;/, $excepts);
    my($date, $time, $edate, $etime, $estart, $tmp, $smp);
    ($date, $time, $smp) = vtime($start, $tz, $etz);
    my $ans = "";
    foreach $tmp (@alldates) {	
	($edate, $etime, $estart) = vtime($tmp, $tz, $etz);
	$smp = calmatch($edate, $date, $occurs, $repeat, undef, 0);
	if($smp) {   if($ans) { $ans .= ", $smp";} else {$ans = $smp;} }
    }
    if($ans) { return "[$ans]";}
    return "";
}
#=====================================================================================================
sub pvrule {
    $_ = (@_)[0];
    my($repeat, $occurs)=(0, "");
    if(/D1\s+\#(\d+)/) { $repeat =$1; $occurs = "Daily";}
    elsif(/D2\s+\#(\d+)/) { $repeat =$1; $occurs = "EveryOtherDay";}
    elsif(/D3\s+\#(\d+)/) { $repeat =$1; $occurs = "Every3rdDay";}
    elsif(/D4\s+\#(\d+)/) { $repeat =$1; $occurs = "Every4thDay";}
    elsif(/D5\s+\#(\d+)/) { $repeat =$1; $occurs = "Every5thDay";}
    elsif(/D6\s+\#(\d+)/) { $repeat =$1; $occurs = "Every6thDay";}
    elsif(/W1\s+\#(\d+)/) { $repeat =$1; $occurs = "Weekly";}
    elsif(/W2\s+\#(\d+)/) { $repeat =$1; $occurs = "Every2Weeks";}
    elsif(/MD1\s+\#(\d+)/) { $repeat =$1; $occurs = "MonthlyByDate";}
    elsif(/MP1\s+(\d+)\+\s+\S+\s+\#(\d+)/) { $repeat =$2; $occurs = "MonthlyByWeekday";}
    elsif(/YM1\s+(\d+)\s+\#(\d+)/) { $repeat =$2; $occurs = "Yearly";}
    elsif(/MP12\s+(\d+)\+\s+\S+\s+\#(\d+)/) { $repeat =$2; $occurs = "YearlyByMonthWeekday";}
    elsif(/W1\s+$::swd[1]\s+$::swd[2]\s+$::swd[3]\s+$::swd[4]\s+$::swd[5]\s+\#(\d+)/) {$repeat =$1; $occurs="MTWThF";}
    elsif(/W1\s+$::swd[1]\s+$::swd[3]\s+$::swd[5]\s+\#(\d+)/) {$repeat =$1; $occurs="MWF";}
    elsif(/W1\s+$::swd[2]\s+$::swd[4]\s+\#(\d+)/) {$repeat =$1; $occurs="TTh";}
    elsif(/D(\d+)\s+\#(\d+)/) { $repeat =$2; $occurs = "ZD,$1,0";}
    elsif(/MD(\d+)\s+\#(\d+)/) { $repeat =$2; $occurs = "ZMD,$1,0";}
    elsif(/MP(\d+)\s+\#(\d+)/) { $repeat =$2; $occurs = "ZMWD,$1,0";}
    elsif(/MD(\d+)\s+(\d+)\s+\#(\d+)/) { $repeat =$3; $occurs = "ZMD,$1,0";}
    elsif(/MP(\d+)\s+(\d+)[^\#]+\#(\d+)/) { $repeat =$3; $occurs = "ZMWD,$1,0";}
    elsif(/MD(\d+)\s+(\d+)\-[^\#]+\#(\d+)/) { $repeat =$3; $occurs = "ZMND,$1,0";}
    elsif(/MP(\d+)\s+(\d+)\-[^\#]+\#(\d+)/) { $repeat =$3; $occurs = "ZMNW,$1,0";}
    elsif(/WD(\d+)\s+\#(\d+)\s+(\d+)/) { $repeat =$2; $occurs = "ZX,$1,$3";}
    elsif(/W(\d+)([^\#]+)\#(\d+)/) {
	my ($wds, $bits, $i, $p, $nn); $nn=$1, $wds=$2; $bits=0; $repeat =$3;
	for($i=0; $i<7; $i++) { $p=$::swd[$i]; if($wds =~ /\s+$p\s+/){ $bits |= (1<<$i);}}
	 $occurs="ZW,$nn,$bits";
    }
    return( $repeat, $occurs);
}
#=====================================================================================================
sub valarm {
    use integer;
    my ($sec) = (@_);
    my $tmp = $sec/60;
    return  $tmp;
}
#=====================================================================================================
sub vtime {
    my ($in, $tzone, $etzone) = (@_);
    my($date, $time, $utime, $year, $mon, $mday, $hour, $min, $sec, $isutc);
    if( $in =~ m/(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)(Z?)/ or
	$in =~ m/(\d{4})\-(\d\d)\-(\d\d)T(\d\d):(\d\d):(\d\d)(Z?)/ )  {
	$year = $1; $mon = $2; $mday = $3;
	$hour =$4; $min = $5; $sec = $6;
	$isutc = $7;
	if($isutc) {
	    ($sec, $min,$hour,$mday, $mon, $year, $tzone, $utime) = 
		UTCToLocal($sec, $min,$hour,$mday, $mon -1, $year -1900, $tzone);
	    $year += 1900; $mon += 1; $mday += 0;
	    $date = "$mon/$mday/$year";
	    $time =  sprintf "%02d:%02d", $hour,$min;
	    return($date, $time, $utime);
	} else {
	    $year = $1; $mon = $2; $mday = $3;
	    $hour =$4; $min = $5; $sec = $6;
	    #if($etzone and $etzone ne $tzone) { # the event contains a timezone, should we convert ?
	    #    my ($lsec, $lmin,$lhour,$lmday, $lmon, $lyear, $ltzone, $lutime);
	    #        localToUTC($sec, $min,$hour,$mday, $mon -1, $year-1900, $etzone);
	    #    ($sec, $min,$hour,$mday, $mon, $year, $etzone) =
	    #        UTCToLocal($lsec, $lmin,$lhour,$lmday, $lmon, $lyear, $tzone);
	    #    $year += 1900; $mon += 1;
	    #}
	    $mon += 0; $mday += 0; $year += 0;
	    $date = "$mon/$mday/$year";
	    $time =  sprintf "%02d:%02d", $hour,$min;
	    $utime = timeLocal($sec, $min, $hour, $mday, $mon -1, $year);
	    return($date, $time, $utime);	
	}
    } elsif($in =~ m/(\d{4})(\d\d)(\d\d)/ or $in =~ m/(\d{4})\-(\d\d)\-(\d\d)/ )  { #date only
	$year = $1; $mon = $2; $mday = $3; $hour =12; $min = 0; $sec = 0;	
	$mon += 0; $mday += 0; $year += 0;
	$date = "$mon/$mday/$year";
	$time =  sprintf "%02d:%02d", $hour,$min;
	$utime = timeLocal($sec, $min, $hour, $mday, $mon -1, $year);
	return($date, $time, $utime);		
    }
}
#=====================================================================================================
sub parseVjournal {
    use integer;
    my ($who, $des) = (@_);
    my ($a, @f, $n, $p, $v, $b, @ves, @events, $remote_user);
    if($::d{'remote_user'}) {$remote_user = $::d{'remote_user'};} else {$remote_user=$who;}
    $des =~ s/\r\n/\n/g;
    $des =~ s/\r/\n/g;
    $des =~ s/=0D=0A=?\n/ /g;    
    $des =~ s/\n\W*:/:/g;
#    $des =~ s/\n\s+/\n/g;
    $des =~ s/\n\s//g;
    @ves = (); @events = ();
    $_ = $des;
    # separate vjournal entries
    while(/(END:\s*VJOURNAL)/i) {	push @ves, "$`$&";	$_=$';    }
    # parse one by one ' " '"
    for $b (@ves) {
	@f = split(/\n/, $b);
	my $doit = 0;
	my ($summary, $content, $date, $category, $misc) = ("", "","","", ""); 
	for $a (@f) {
	    ($n, $v) = split(/:/, $a, 2); 
	    next if not $n or not $v;
	    ($n, $p) = split(/;/, $n, 2); 
	    $n=~ s/^\s+//g; $n=~ s/\s+$//g; #;
	    $v=~ s/^\s+//g; $v=~ s/\s+$//g; #;
	    $n = uc($n);
	    if($n eq 'BEGIN') {	if( $v =~ m/VJOURNAL/i) { $doit = 1;} }
	    elsif($n eq 'END') { if( $v =~ m/VJOURNAL/i) { $doit++;} }
	    elsif($n eq 'DTSTART') { my ($edate, $time, $start) = vtime($v, undef, undef); $date = $edate;}
	    elsif($n eq 'SUMMARY') { $summary = $v; }
	    elsif($n eq 'CATEGORIES') { $category = $v; }
	    elsif($n eq 'DESCRIPTION') { $content .= $v;}
	    else { my $tmp = "\015\012$n: $v\015\012"; $misc .= $tmp;}
	}
	# convert to webCalendar 	
	if($doit and $date and ($content or $misc or $summary)) {
	    my $hash={};
	    $hash->{'date'} = $date;
	    $hash->{'summary'} = $summary;
	    $hash->{'content'} = $content;
	    $hash->{'category'} = $category;
	    $hash->{'misc'} = $misc;
	    push(@events, $hash);
	}
    }
    return(@events);
}

sub toVjournal {
    my ($href, $who, $privacy)=(@_);
    my ($dtstart, $tmp, $msg);
    return "" if $privacy < 2;
    my ($month, $day, $year) = split(/\//, $href->{'date'}); if($year < 1900) { $year += 1900;}
    $dtstart = sprintf "%4d%02d%02d", $year, $month, $day;
    $msg = "BEGIN:VJOURNAL\nDTSTART;VALUE=DATE:$dtstart\n";
    if($href->{'timestamp'}) {$msg .= "TIMESTAMP: $href->{'timestamp'}\n";}

    my $imgurl = &getIUploaddirFullURL;

    if($href->{'category'}){
	my $cat = $href->{'category'};
	$cat =~ s/\\?\^o\^\//$imgurl\//g;
	$tmp = "CATEGORIES: $cat\n";
	$msg .= $tmp;
    }
    if($href->{'summary'}){
	my $summary = $href->{'summary'};
	$summary =~ s/\\?\^o\^\//$imgurl\//g;
	$tmp = "SUMMARY: $summary\n";
	$msg .= $tmp;
    }
    if($href->{'description'}){ 
	my  $desc = $href->{'description'};
	$desc =~ s/\n\s*$//g;
	$desc =~ s/\n/=0D=0A=\n/g;
	$desc =~ s/\\?\^o\^\//$imgurl\//g;
	$tmp = "DESCRIPTION: $desc\n";
	$msg .= $tmp;	
    }
    $msg .= "END:VJOURNAL\n";
    $msg =~ s/\n/\015\012/g;
    return $msg;
}
#=====================================================================================================
sub match_search_words {
    my ($href, $eprivacy) =(@_);
    my ($text);
    return 0 if not $eprivacy;
    $text = $href->{'what'};
    if($eprivacy >= 3) {
	if($::o{'search_filter'} > 1) {
	    $text .= "$href->{'kwd'} " if $href->{'kwd'};
	    $text .= "$href->{'detail'} " if $href->{'detail'}; 
	    if($::o{'search_filter'} > 2) {
		$text .= "$href->{'room'} " if $href->{'room'};
		$text .= "$href->{'cat'} " if $href->{'cat'};
		$text .= "$href->{'spkr'} " if $href->{'spkr'};
		$text .= "$href->{'ctp'} " if $href->{'ctp'};
		$text .= "$href->{'ctm'} " if $href->{'ctm'};
	    }
	}
    }
    return matchSrchExpr($text);
}
#=====================================================================================================
sub gettasks {
    my ($tmp, $smp, $tim, $key, $who, $view,$edate, $href, $mg, $author,$whoami, $edit, $ed,
	$gprivacy, $ls, $eprivacy, $URL, $detail, $tc, $bg, $junk, $rurl, $cached, $ttt);

    $who = $::calinfo{'w'};
    $view = $::calinfo{'v'};
    $ls = $::calinfo{'ls'};
    $whoami = $::d{'remote_user'};

    $cached = 0;
    if($::calinfo{'mattendants'}) { # MegaCal uses event based privacy.
	&getMegaCalendarData;	
        $gprivacy=2;
	$mg="&mg=$::d{'megaCal'}"; 
        $edit=0;
        $cached = 1;
    } else {
      $mg="";
      my ($cal, $df, $cdir, $cache);
      $cal = untaintname($who,$::phr{'Invalidusername'});
      $df ="$::o{'spooldir'}/$cal/data";
      $cdir ="$::o{'spooldir'}/$cal/cache";      
      $cache = "$cdir/tasks";
      if(-f "$df") {
          if( -f $cache) {
	      $ = time;
              my $ct = -M "$cache";
              my $dt = -M "$df";
              if($ct <= $dt) { 
                  @::tasks=(); doReadFile("$cache"); 
                  @::caldata = @::tasks;
                  $cached = 1; 
              }
          }
          if($cached == 0) {
              doReadFile("$df");
          }
      }
      ($gprivacy, $tmp) = getPrivacy(0);
      $edit = $::d{'authResult'};
    }
    %::ctasks=(); %::ctasksDetails=();
    %::ptasks=(); %::ptasksDetails=();

    use integer;
    for $href (@::caldata) {
	my $done = 0;
	if($href->{'kind'} == 2) {
	    if($gprivacy > 3) { $eprivacy = 3;}
	    else {
		if(defined $href->{'e'} or (defined $href->{'w'} and $href->{'w'} eq $::d{'remote_user'})) { $eprivacy = 3;} #for megaCalendar
		elsif( $href->{'privacy'}) {
		    $eprivacy = $::privacyTable{$href->{'privacy'}} - 1;
		} else { $eprivacy = $gprivacy; }
	    }
	    next if $eprivacy == 0;
	    next if not &$::catfiltersub($href->{'cat'});
	    if($::srchftrptn) { next if not match_search_words($href,$eprivacy);}
	    if($href->{'done'} && $href->{'done'} eq 'y') { $done=1; }
            my ($tclr, $repeat, $overdue);
	    $URL = ""; $overdue="";
	    $detail="";
	    if($href->{'fg'}){$tclr=$tc = $href->{'fg'};} else { $tclr=$tc ="";}
	    if($href->{'bg'}){$bg = $href->{'bg'};} else {$bg="";}
	    my $bdate = $href->{'bdate'}; $bdate=$href->{'date'} if not $bdate;
	    my $class=""; if($href->{'cs'}) {$class="class=\"$href->{'cs'}\""; $tc=$tclr;} else {$class="class=\"zet2\"";}
	    my ($month, $day, $year) = split(/\//, $bdate); $month--; 
            $bdate = sprintf "/%02d/%02d/%04d", $month, $day, $year;	    
	    ($month, $day, $year) = split(/\//, $href->{'date'}); $month--; 
	    $edate = sprintf "%02d/%02d/%04d", $month, $day, $year;
	    $edate .= $bdate;

	    $junk = $href->{'start'}; $junk =~ s/:/\//g;
	    $key = $href->{'key'};
	    $tim = "$edate/$junk:$key";  $ttt = "$junk:$key"; 
	    if($bg) { $tim .= ":$bg"; $ttt .= ":$bg"; }
	    elsif($::d{'ispublic'}) {
	      my ($name, $cnt, $clr);
	      $name=$href->{'author'}; if(!$name) {$name='nobody';}
	      if(! exists $::namehash{$name}) { $cnt = ($::d{'namecounter'}++)%16; $::namehash{$name} = $cnt;}
	      $cnt = $::namehash{$name};
	      $clr=$webcalConfig::r{'usrColors'}->[$cnt];
	      $tim .= ":$clr";
	      $ttt .= ":$clr";
           } else { $tim .= ":"; $ttt .= ":";}

	    if($mg eq "") {
                my ($mkey, $hasmme, $themme, $ted, $repeat, $isauthor, $isoauthor, $others);
                $others=$href->{'attendants'};
                $ted = 0; $isoauthor=0;
                $hasmme = $themme = 0;
                $isauthor = ismember($whoami, $href->{'author'});
                $isoauthor =1 if $isauthor == 1;
		if(isadmin($::d{'remote_user'}) or isvgadmin($::d{'remote_user'}, $who)){ $isauthor=$isoauthor = 1;}
                if(!$others) { # personal event
                    if($edit == 4 or $isauthor) { $ted = 4;}
                } else { # group event
                    if($isoauthor) { $ted = 4;} # original author has all editing priviledges
                    elsif($href->{'mkey'}) {
                        my $tmk;
                        $tmk= $mkey = $href->{'mkey'}; 
                        $tmk =~ s/_eMe_\d+//g;
                        my $att = $others; $att =~ s/[,; ]+/:/g;
                        $att = expandMeetingGroups($tmk, $att);
                        $themme = $href->{'mme'} if defined $href->{'mme'};
                        if(isre($whoami,$tmk,'editors')) { $ted = 4;}
                        elsif(ismember($whoami, $att) and $themme > 0) { $ted = $themme + $themme;}
                    }
                }
                $tim .= ":$ted"; $ttt .= ":$ted";
            } else { $tim .= ":0"; $ttt .= ":0";}

            my ($cfm, $cfmd) = ("", "");
	    if($eprivacy >= 3) {
                ($cfm, $cfmd) = confirmMeeting($href, 0);
                if($cfmd) { $cfmd = "<br><br>$cfmd";}
		$smp = $href->{'what'};
		$smp = 'no subject' unless $smp;
		if(defined $href->{'detail'} and $href->{'detail'} ne "") { $detail = "$href->{'detail'}";} else {$detail ="";}
		$smp= &substImages($smp);
		$detail= &substImages($detail);
		if(defined $href->{'room'} and $href->{'room'} ne "") { 
		    if($detail) { $detail .= "<br>";}
		    $detail .= "<b>$::phr{'Location'}:</b> $href->{'room'}";
		}
		if(defined $href->{'cat'} and $href->{'cat'} ne "") {
		    if($detail) { $detail .= " <br>";}
		    my $tcat = $href->{'cat'};
		    $detail .= "<b>$::phr{'Category'}:</b> $tcat";
		}
		if(defined $href->{'pri'} and $href->{'pri'} ne "") {
		    if($detail) { $detail .= "<br>";}
		    $detail .= "<b>$::phr{'Priority'}:</b> $href->{'pri'}";
		}
		if($href->{'ctp'}) {
		    if($detail) {$detail .="<br>";} 
		    $detail .= "<b>$::phr{'ContactP'}:</b> $href->{'ctp'}";
		}
		if($href->{'ctm'}) {
		    if($detail) {$detail .="<br>";} 
		    $detail .= "<b>$::phr{'ContactE'}:</b> $href->{'ctm'}";
		}
		$URL="";
		$rurl= $href->{'url'};
		if($rurl) {
		    my $irepository = "$::o{'imgdirurl'}/$::o{'uploadsubdir'}";
		    my (@urls, $a, $b); @urls = split(/\s+/, $rurl); 
		    foreach $a (@urls) {
			my $icon = select_url_icon($a);
			$a =~ s/\\?\^o\^\//$irepository\//g;
			$URL .="<A HREF=\"$a\" target=i><img src=\"$::o{'imgdirurl'}/$icon\" width=20 height=9 border=0></A> ";
		    }
		} 
 	    } else {
		if($::d{'megaCal'} ne "") { 
		    if(defined $href->{'w'}) {
			$smp = "<FoNt CoLoR=#0000Ff>" . $href->{'w'} . ":</FoNt> " . ": $::phr{'Protected'}"; 
		    } else { $smp =  $::phr{'Protected'};}
		}
		else {$smp = "$::phr{'Protected'}";}
	    }
	    my ($parta, $partb, $owner, $zz);
	    if($::d{'megaCal'} ne "") {
                $owner = $href->{'w'};
		$zz = $owner; $zz =~ s/[^A-Za-z0-9]//g;
                $edate = "$month/$day/$year";
		if($tc) {
		    $parta =  "<a href=\"$::o{'cginame'}?w=$owner&c=ed&v=$view&ls=$ls&sk=1&t=$key&k=2&d=";
		    $partb = "$mg$::vmg\" $class><font color=$tc>$smp</font></a>";
		} else {
		    $parta = "<a href=\"$::o{'cginame'}?w=$owner&c=ed&v=$view&ls=$ls&sk=1&t=$key&k=2&d=";
		    $partb = "$mg$::vmg\" $class>$smp</a>";
		}
	    } else {
                $owner = $who;
		$zz="";
		if($tc) {
		    $parta = "<a href=\"$::o{'cginame'}?w=$who&c=ed&v=$view&ls=$ls&sk=1&t=$key&k=2&d=";
		    $partb = "$::vmg\" $class><font color=$tc>$smp</font></a>";
		} else {
		    $parta = "<a href=\"$::o{'cginame'}?w=$who&c=ed&v=$view&ls=$ls&sk=1&t=$key&k=2&d=";
		    $partb = "$::vmg\" $class>$smp</a>";
		}
	    }
            my $fdate = "$month/$day/$year";
            if($cfm eq 'a')  {
		my $tpid = add2tip("$key$zz", "<font color=#ff0000><b>$::phr{'invitationAccepted'}</b></font>$cfmd");
                $cfm = "<a href=\"$::o{'cginame'}?w=$owner&c=cfm&cfm=a&v=$view&ls=$ls&t=$key&d=$fdate$mg$::vmg\" onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"><img src=\"$::o{'imgdirurl'}/ai.gif\" border=0 width=10 height=8></a>";
            } elsif ($cfm eq 'd') {
		my $tpid = add2tip("$key$zz", "<font color=#ff0000><b>$::phr{'invitationDeclined'}</b></font>$cfmd");
                $cfm = "<a href=\"$::o{'cginame'}?w=$owner&c=cfm&cfm=d&v=$view&ls=$ls&t=$key&d=$fdate$mg$::vmg\" onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"><img src=\"$::o{'imgdirurl'}/di.gif\" border=0 width=10 height=8></a>";	
            } elsif($cfm eq 'r') {
		my $tpid = add2tip("$key$zz","<font color=#ff0000><b>$::phr{'RequestRSVP'}</b></font>$cfmd");
                $cfm = "<a href=\"$::o{'cginame'}?w=$owner&c=cfm&cfm=r&v=$view&ls=$ls&t=$key&d=$edate$mg$::vmg\" onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"><img src=\"$::o{'imgdirurl'}/ri.gif\" border=0 width=10 height=8></a>";
            } else { $cfm ="";}
            
	    if($done) {
		if(mdyAafterB($month, $day, $year, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'}) and
		   mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$month, $day, $year)) {
		    my ($tmp, $jk1) = getCompletionInfo($href, 0);
		    if($tmp) { if($detail) { $detail .= "<br>$tmp"; } else { $detail = $tmp;}}
		    $::ctasksDetails{$tim} = $detail;
		    $edate = "$month/$day/$year";
		    $::ctasks{$tim} =  $URL . $parta . $edate . $partb;
		}
	    }
	    else {
		my($nowM, $nowD, $nowY, $nowH, $nowN) =
		    ($::now{'month'},$::now{'day'},$::now{'year'}, $::now{'hour'}, $::now{'min'});
		my (@overdue) = ("", $overdue=" <iMg src=\"$::o{'imgdirurl'}/larr.gif\" width=14 height=10 border=0 alt=\"\"> <b><font color=#ff0000>$::phr{'Overdue'}</font></b>"); 
		if( !$href->{'repeat'} or $href->{'repeat'} < 2 or !$href->{'occurs'} or $href->{'occurs'} eq 'OneTime') {
                    my ($tmp, $jk1) = getCompletionInfo($href, 0);
                    if($tmp) { $::ptasksDetails{$tim} = $detail . "<br>$tmp";}
		    else {$::ptasksDetails{$tim} = $detail;}
		    my $before=mdyAafterB($nowM, $nowD, $nowY,$month,$day,$year);
		    my $pz =0; 
		    if($before == 1) { 
			my ($tm, $hr,$mn);
			$tm=$href->{'start'};  ($hr,$mn)=split(/:/,$tm);
			if($nowH > $hr or $nowH == $hr and $nowN > $mn) { $before =2;}
		    }
		    $pz = 1 if($before > 1);
		    if($pz or (mdyAafterB($month, $day, $year, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'}) and
			       mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$month, $day, $year))) {
			$edate = "$month/$day/$year";
			$::ptasks{$tim} =  $URL . $cfm . $parta . $edate . $partb . $overdue[$pz];
		    }
		} else { # this is a total mess !
		    my ($sme, $sde, $sye, $i,$j, $repeat, $occurs, $exception, $elength, $edate, $k, $kk, $ddd, $wday, $code, $x, $y);
		    my ($endM,$endD,$endY)=("","","");
		    if($href->{'end'}) { ($endM,$endD,$endY)=split(/\//,$href->{'end'}); $endM--;}
		    my ($osme, $osde, $osye, $bbb, $pz, $hr, $mn, $before); ($hr, $mn) = split(/:/,$href->{'start'});
		    my ($a0, $b1);
		    $repeat = $href->{'repeat'};
		    $occurs = $href->{'occurs'};
		    $exception = $href->{'exception'};
		    $edate = $href->{'date'};
		    #my ($month, $day, $year) = split(/\//, $href->{'bdate'}); $month--; 
		    #my $bdate = sprintf "%02d/%02d/%04d", $month, $day, $year;	    
		    if($exception) { $elength = $#$exception;} else {$elength = -1;}
		    if ($occurs eq "Daily") {
			($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0; 
			    $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
			    $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
			    $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
			    last if (not $before and not $b1);
			    for $j (0 .. $elength) {if(abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
			    if($k == 0) {
				$ddd="$sme/$sde/$sye"; $kk= "$ddd/$ddd/$ttt:$i";
				if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				if($pz or ($a0 and $b1)) {
				    $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
				    if($detail) {$::ptasksDetails{$kk} = $detail;}
				}
			    } elsif($k < 0) {
				if($a0 and $b1) {
				    $ddd="$sme/$sde/$sye"; $kk= "$ddd/$ddd/$ttt:$i";
				    $::ctasks{$kk} =  $URL . $parta . $ddd . $partb;
				    my ($tmp, $jk1) = getCompletionInfo($href, $k);
				    if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
				    elsif($detail){ $::ctasksDetails{$kk} = $detail;}
				}
			    }
			    ($sme, $sde, $sye) = canDate($sme, $sde + 1, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "Weekly") {
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			($osme, $osde, $osye) = ($sme,$sde,$sye);
			$wday = wday($sme, $sde, $sye);	# weekday of event
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) { if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;} }
			    $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
			    $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
			    $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
			    last if (not $before and not $b1);
			    if($k == 0) {
				$ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye";$kk= "$ddd/$bbb/$ttt:$i";
				if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				if($pz or ($a0 and $b1)) {
				    $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
				    if($detail) {$::ptasksDetails{$kk} = $detail;}
				}
			    } elsif($k < 0) {
				if($a0 and $b1) {
				    $ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				    $::ctasks{$kk} =  $URL . $parta . $ddd . $partb;
				    my ($tmp,$jk1) = getCompletionInfo($href, $k);
				    if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
				    elsif($detail) {$::ctasksDetails{$kk} = $detail;}
				}
			    }
			    ($osme, $osde, $osye) = ($sme,$sde,$sye);
			    ($sme, $sde, $sye) = canDate($sme, $sde + 7, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "Every2Weeks") {
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			($osme, $osde, $osye) = ($sme,$sde,$sye);
			$wday = wday($sme, $sde, $sye);	# weekday of event
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) { if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
			    $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
			    $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
			    $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
			    last if (not $before and not $b1);
			    if($k == 0) {
				$ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				if($pz or ($a0 and $b1)) {
				    $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
				    if($detail) {$::ptasksDetails{$kk} = $detail;}
				}
			    } elsif($k < 0) {
				if($a0 and $b1) {
				    $ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				    $::ctasks{$kk} =  $URL . $parta . $ddd . $partb;
				    my ($tmp,$jk1) = getCompletionInfo($href, $k);
				    if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
				    elsif($detail) {$::ctasksDetails{$kk} = $detail;}
				}
			    }				
			    ($osme, $osde, $osye) = ($sme,$sde,$sye);
			    ($sme, $sde, $sye) = canDate($sme, $sde + 14, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "MonthlyByDate") {
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			($osme, $osde, $osye) = ($sme,$sde,$sye);
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) { if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
			    $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
			    $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
			    $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
			    last if (not $before and not $b1);
			    if($k == 0) {
				$ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				$before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
				if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				if($pz or ($a0 and $b1)) {
				    $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
				    if($detail) {$::ptasksDetails{$kk} = $detail;}
				}
			    } elsif($k < 0) {
				if($a0 and $b1) {
				    $ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				    $::ctasks{$kk} =  $URL . $parta . $ddd . $partb;
				    my ($tmp,$jk1) = getCompletionInfo($href, $k);
				    if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
				    elsif($detail) {$::ctasksDetails{$kk} = $detail;}
				}
			    } 
			    ($osme, $osde, $osye) = ($sme,$sde,$sye);
			    ($sme, $sde, $sye) = canDate($sme+1, $sde, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "MonthlyByWeekday") {
			my ($nth, $nnm);
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			($osme, $osde, $osye) = ($sme,$sde,$sye);
			$wday = wday($sme, $sde, $sye);	# weekday of event
			$code =  $sde - ($sde/7) * 7; if($code==0) { $code += 7;}	# the first wday
			$nth =  ($sde-$code)/7;	# the nth week
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {  if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
			    $x= wday($sme, $sde, $sye);	# weekday of event
			    $sde += $wday -$x;	#to the correct weekday
			    if($sde <= 0) { $sde += 7;}
			    $code =  $sde - ($sde / 7) *7; if($code<=0) { $code = 7;}	# the first wday
			    $sde = $nth * 7 + $code;	# the nth wday
			    my ($mxdays, $ok);
			    $ok=1;
			    if($sde > 28) {
				if($sme != 1) { $mxdays = $::mdays[$sme];}
				else { if(isleap($sye)) { $mxdays = 29;} else {$mxdays = 28;}}
				if($sde > $mxdays) { $ok=1;}
			    }
			    $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
			    $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
			    $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
			    last if (not $before and not $b1);
			    if($ok) {
				$ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				if($k == 0) {
				    if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				    if($pz or ($a0 and $b1)) {
					$::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
					if($detail) {$::ptasksDetails{$kk} = $detail;}
				    }
				} elsif($k < 0) {
				    if($a0 and $b1) {
					$::ctasks{$kk} =  $URL . $parta . $ddd . $partb;
					my ($tmp,$jk1) = getCompletionInfo($href, $k);
					if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
					elsif($detail) {$::ctasksDetails{$kk} = $detail;}
				    }
				} 
			    }
			    ($osme, $osde, $osye) = ($sme,$sde,$sye);
			    ($nnm, $sde, $sye) = canDate($sme+1, $sde, $sye);
			    if($nnm != $sme+1 and $nnm != $sme-11) { $i++;}
			    $sme = $nnm;
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "Yearly") {
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			($osme, $osde, $osye) = ($sme,$sde,$sye);
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {  if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;} }
			    $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
			    $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
			    $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
			    last if (not $before and not $b1);
			    if($k == 0) {
				$ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				if($pz or ($a0 and $b1)) {
				    $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
				    if($detail) {$::ptasksDetails{$kk} = $detail;}
				}
			    } elsif($k < 0) {
				if($a0 and $b1) {
				    $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				    $::ctasks{$kk} =  $URL . $parta . $ddd . $partb;
				    my ($tmp,$jk1) = getCompletionInfo($href, $k);
				    if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
				    elsif($detail) {$::ctasksDetails{$kk} = $detail;}
				}
			    }
			    ($osme, $osde, $osye) = ($sme,$sde,$sye);
			    ($sme, $sde, $sye) = canDate($sme, $sde, $sye+1);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		     } elsif ($occurs eq "YearlyByMonthWeekday") {
			my ($nth, $nnm);
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			($osme, $osde, $osye) = ($sme,$sde,$sye);
			$wday = wday($sme, $sde, $sye);	# weekday of event
			$code =  $sde - ($sde/7) * 7; if($code==0) { $code += 7;}	# the first wday
			$nth =  ($sde-$code)/7;	# the nth week
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) { if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
			    if($k <= 0) {
				$x = wday($sme, $sde, $sye);	# weekday of event
				$sde += $wday -$x;	#to the correct weekday
				if($sde <= 0) { $sde += 7;}
				$code =  $sde - ($sde / 7) *7; if($code<=0) { $code = 7;}	# the first wday
				$sde = $nth * 7 + $code;	# the nth wday
				my ($mxdays, $ok);
				$ok=1;
				if($sde > 28) {
				    if($sme != 1) { $mxdays = $::mdays[$sme];}
				    else { if(isleap($sye)) { $mxdays = 29;} else {$mxdays = 28;}}
				    if($sde > $mxdays) { $sde=$mxdays-2; $ok=0;}
				}
				$a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
				$b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
				$before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
				last if (not $before and not $b1);
				if($ok) {
				    $ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				    if($k == 0) {
					if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
					if($pz or ($a0 and $b1)) {
					    $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
					    if($detail) {$::ptasksDetails{$kk} = $detail;}
					}
				    } elsif($k < 0) {
					if($a0 and $b1) {
					    $::ctasks{$kk} =  $URL . $parta . $ddd . $partb;
					    my ($tmp,$jk1) = getCompletionInfo($href, $k);
					    if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
					    elsif($detail) {$::ctasksDetails{$kk} = $detail;}
					}
				    }
				}
			    }
			    ($osme, $osde, $osye) = ($sme,$sde,$sye);
			    ($nnm, $sde, $sye) = canDate($sme, $sde, $sye+1);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "MTWThF") {
			my ($x, $y, $err);
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			($osme, $osde, $osye) = ($sme,$sde,$sye);
			$wday = wday($sme, $sde, $sye);	# weekday of event
			for($i = 0; $i < $repeat; $i += 5, $wday=0) {
			    for($x=$wday; $x <7; $x++) {
				$err=wday($sme, $sde, $sye);
				$y = $i+$err;
				if($err and $err != 6 and $y <= $repeat) {
				    $k = 0; $y = $i+$err;
				    for $j (0 .. $elength) { if( abs($exception->[$j]) == $y) { $k = $exception->[$j]; last;}}
				    $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
				    $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
				    $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
				    last if (not $before and not $b1);
				    if($k == 0) {
					$ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$y";
					if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
					if($pz or ($a0 and $b1)) {
					    $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
					    if($detail) {$::ptasksDetails{$kk} = $detail;}
					}
				    } elsif($k < 0) {
					if($a0 and $b1) {
					    $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$y";
					    $::ctasks{$kk} = $parta . $ddd . $partb;
					    my ($tmp,$jk1) = getCompletionInfo($href, $k);
					    if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
					    elsif($detail) {$::ctasksDetails{$kk} = $detail;}
					}
				    }
				}
				($osme, $osde, $osye) = ($sme,$sde,$sye);
				($sme, $sde, $sye)=canDate($sme, $sde+1, $sye);
				last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			    }
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "MWF") {
			my ($x, $y,  $err);
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			($osme, $osde, $osye) = ($sme,$sde,$sye);
			$wday = wday($sme, $sde, $sye);	# weekday of event
			for($i = 0; $i < $repeat; $i += 3,$wday=0) {
			    for($x=$wday; $x <7; $x++) {
				$err=wday($sme, $sde, $sye);
				$y = $i+(($err+1)>>1);
				if(($err & 1) and  $y <= $repeat) {
				    $k = 0; 
				    for $j (0 .. $elength) {if( abs($exception->[$j]) == $y) { $k = $exception->[$j]; last;}}
				    $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
				    $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
				    $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
				    last if (not $before and not $b1);
				    if($k == 0) {
					$ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$y";
					if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
					if($pz or ($a0 and $b1)) {
					    $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
					    if($detail) {$::ptasksDetails{$kk} = $detail;}
					}
				    } elsif($k < 0) {
					if($a0 and $b1) {
					    $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$y";
					    $::ctasks{$kk} = $parta . $ddd . $partb;
					    my ($tmp,$jk1) = getCompletionInfo($href, $k);
					    if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
					    elsif($detail) {$::ctasksDetails{$kk} = $detail;}
					}
				    }
				}
				($osme, $osde, $osye) = ($sme,$sde,$sye);
				($sme, $sde, $sye)=canDate($sme, $sde+1, $sye);
				last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			    }
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "TTh") {
			my ($x, $y, $err);
			($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			($osme, $osde, $osye) = ($sme,$sde,$sye);
			$wday = wday($sme, $sde, $sye);	# weekday of event
			for($i = 0; $i < $repeat; $i += 2, $wday=0) {
			    for($x=$wday; $x <7; $x++) {
				$err=wday($sme, $sde, $sye);
				$y = $i+($err>>1);
				if($err == 2 or $err == 4 and $y <= $repeat) {
				    $k = 0;
				    for $j (0 .. $elength) { if( abs($exception->[$j]) == $y) { $k = $exception->[$j]; last;} }
				    $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
				    $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
				    $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
				    last if (not $before and not $b1);
				    if($k == 0) {
					$ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$y";
					if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
					if($pz or ($a0 and $b1)) {
					    $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
					    if($detail) {$::ptasksDetails{$kk} = $detail;}
					}
				    } elsif($k < 0) {
					if($a0 and $b1) {
					    $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$y";
					    $::ctasks{$kk} = $parta . $ddd . $partb;
					    my ($tmp,$jk1) = getCompletionInfo($href, $k);
					    if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
					    elsif($detail) {$::ctasksDetails{$kk} = $detail;}
					}
				    }
				}
				($osme, $osde, $osye) = ($sme,$sde,$sye);
				($sme, $sde, $sye)=canDate($sme, $sde+1, $sye);
				last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			    }
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "EveryOtherDay") {
			($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			($osme, $osde, $osye) = ($sme,$sde,$sye);
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
			    $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
			    $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
			    $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
			    last if (not $before and not $b1);
			    if($k == 0) {
				$ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				if($pz or ($a0 and $b1)) {
				    $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
				    if($detail) {$::ptasksDetails{$kk} = $detail;}
				}
			    } elsif($k < 0) {
				if($a0 and $b1) {
				    $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				    $::ctasks{$kk} = $parta . $ddd . $partb;
				    my ($tmp,$jk1) = getCompletionInfo($href, $k);
				    if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
				    elsif($detail) {$::ctasksDetails{$kk} = $detail;}
				}
			    }
			    ($osme, $osde, $osye) = ($sme,$sde,$sye);
			    ($sme, $sde, $sye) = canDate($sme, $sde + 2, $sye);
			  }
		    } elsif ($occurs eq "Every3rdDay") {
			($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			($osme, $osde, $osye) = ($sme,$sde,$sye);
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
			    $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
			    $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
			    $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
			    last if (not $before and not $b1);
			    if($k == 0) {
				$ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				if($pz or ($a0 and $b1)) {
				    $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
				    if($detail) {$::ptasksDetails{$kk} = $detail;}
				}
			    } elsif($k < 0) {
				if($a0 and $b1) {
				    $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				    $::ctasks{$kk} = $parta . $ddd . $partb;
				    my ($tmp,$jk1) = getCompletionInfo($href, $k);
				    if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
				    elsif($detail) {$::ctasksDetails{$kk} = $detail;}
				}
			    }
			    ($osme, $osde, $osye) = ($sme,$sde,$sye);
			    ($sme, $sde, $sye) = canDate($sme, $sde + 3, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		    } elsif ($occurs eq "Every4thDay") {
			($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			($osme, $osde, $osye) = ($sme,$sde,$sye);
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
			    $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
			    $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
			    $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
			    last if (not $before and not $b1);
			    if($k == 0) {
				$ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				if($pz or ($a0 and $b1)) {
				    $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
				    if($detail) {$::ptasksDetails{$kk} = $detail;}
				}
			    } elsif($k < 0) {
				if($a0 and $b1) {
				    $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				    $::ctasks{$kk} = $parta . $ddd . $partb;
				    my ($tmp,$jk1) = getCompletionInfo($href, $k);
				    if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
				    elsif($detail) {$::ctasksDetails{$kk} = $detail;}
				}
			    }
			    ($osme, $osde, $osye) = ($sme,$sde,$sye);
			    ($sme, $sde, $sye) = canDate($sme, $sde + 4, $sye);
			  }
		      } elsif ($occurs eq "Every5thDay") {
			($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			($osme, $osde, $osye) = ($sme,$sde,$sye);
			for($i = 1; $i <= $repeat; $i++) {
			    $k = 0;
			    for $j (0 .. $elength) {if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
			    $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
			    $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
			    $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
			    last if (not $before and not $b1);
			    if($k == 0) {
				$ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				if($pz or ($a0 and $b1)) {
				    $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
				    if($detail) {$::ptasksDetails{$kk} = $detail;}
				}
			    } elsif($k < 0) {
				if($a0 and $b1) {				
				    $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				    $::ctasks{$kk} = $parta . $ddd . $partb;
				    my ($tmp,$jk1) = getCompletionInfo($href, $k);
				    if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
				    elsif($detail) {$::ctasksDetails{$kk} = $detail;}
				}
			    }
			    ($osme, $osde, $osye) = ($sme,$sde,$sye);
			    ($sme, $sde, $sye) = canDate($sme, $sde + 5, $sye);
			    last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			}
		      } elsif ($occurs eq "Every6thDay") {
			  ($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			  ($osme, $osde, $osye) = ($sme,$sde,$sye);
			  for($i = 1; $i <= $repeat; $i++) {
			      $k = 0;
			      for $j (0 .. $elength) {if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
			      $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
			      $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
			      $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
			      last if (not $before and not $b1);
			      if($k == 0) {
				  $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				  if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				  if($pz or ($a0 and $b1)) {
				      $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
				      if($detail) {$::ptasksDetails{$kk} = $detail;}
				  }
			      } elsif($k < 0) {
				  if($a0 and $b1) {				
				      $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				      $::ctasks{$kk} = $parta . $ddd . $partb;
				      my ($tmp,$jk1) = getCompletionInfo($href, $k);
				      if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
				      elsif($detail) {$::ctasksDetails{$kk} = $detail;}
				  }
			      }
			      ($osme, $osde, $osye) = ($sme,$sde,$sye);
			      ($sme, $sde, $sye) = canDate($sme, $sde + 6, $sye);
			      last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			  }
		      } elsif( substr($occurs,0,1) eq 'Z' and $occurs =~ /^Z(.+),(\d+),(\d*)/) {
			  my ($word, $c1, $c2) =($1, $2, $3);
			  if($word eq 'D') { 
			      ($sme, $sde, $sye) = split(/\//,$edate); $sme--;
			      ($osme, $osde, $osye) = ($sme,$sde,$sye);
			      for($i = 1; $i <= $repeat; $i++) {
				  $k = 0;
				  for $j (0 .. $elength) {if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
				  $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
				  $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
				  $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
				  last if (not $before and not $b1);
				  if($k == 0) {
				      $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				      if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				      if($pz or ($a0 and $b1)) {
					  $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
					  if($detail) {$::ptasksDetails{$kk} = $detail;}
				      }
				  } elsif($k < 0) {
				      if($a0 and $b1) {				
					  $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
					  $::ctasks{$kk} = $parta . $ddd . $partb;
					  my ($tmp,$jk1) = getCompletionInfo($href, $k);
					  if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
					  elsif($detail) {$::ctasksDetails{$kk} = $detail;}
				      }
				  }
				  ($osme, $osde, $osye) = ($sme,$sde,$sye);
				  ($sme, $sde, $sye) = canDate($sme, $sde + $c1, $sye);
				  last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			      }
			  } elsif($word eq 'MD') {
			      ($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			      ($osme, $osde, $osye) = ($sme,$sde,$sye);
			      for($i = 1; $i <= $repeat; $i++) {
				  $k = 0;
				  for $j (0 .. $elength) { if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
				  $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
				  $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
				  $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
				  last if (not $before and not $b1);
				  if($k == 0) {
				      $ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				      if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				      if($pz or ($a0 and $b1)) {
					  $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
					  if($detail) {$::ptasksDetails{$kk} = $detail;}
				      }
				  } elsif($k < 0) {
				      if($a0 and $b1) {				
					  $ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
					  $::ctasks{$kk} =  $URL . $parta . $ddd . $partb;
					  my ($tmp,$jk1) = getCompletionInfo($href, $k);
					  if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
					  elsif($detail) {$::ctasksDetails{$kk} = $detail;}
				      }
				  } 
				  ($osme, $osde, $osye) = ($sme,$sde,$sye);
				  ($sme, $sde, $sye) = canDate($sme+$c1, $sde, $sye);
				  last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			      }
			  } elsif($word eq 'MWD') {
			      my ($nth, $nnm);
			      ($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			      ($osme, $osde, $osye) = ($sme,$sde,$sye);
			      $wday = wday($sme, $sde, $sye);	# weekday of event
			      $code =  $sde - ($sde/7) * 7; if($code==0) { $code += 7;}	# the first wday
			      $nth =  ($sde-$code)/7;	# the nth week
			      for($i = 1; $i <= $repeat; $i++) {
				  $k = 0;
				  for $j (0 .. $elength) {  if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
				  $x= wday($sme, $sde, $sye);	# weekday of event
				  $sde += $wday -$x;	#to the correct weekday
				  if($sde <= 0) { $sde += 7;}
				  $code =  $sde - ($sde / 7) *7; if($code<=0) { $code = 7;}	# the first wday
				  $sde = $nth * 7 + $code;	# the nth wday
				  my ($mxdays, $ok);
				  $ok=1;
				  if($sde > 28) {
				      if($sme != 1) { $mxdays = $::mdays[$sme];}
				      else { if(isleap($sye)) { $mxdays = 29;} else {$mxdays = 28;}}
				      if($sde > $mxdays) { $ok=0;}
				  }
				  $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
				  $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
				  $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
				  last if (not $before and not $b1);
				  if($ok) {
				      $ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				      if($k == 0) {
					  if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
					  if($pz or ($a0 and $b1)) {
					      $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
					      if($detail) {$::ptasksDetails{$kk} = $detail;}
					  }
				      } elsif($k < 0) {
					  if($a0 and $b1) {				
					      $::ctasks{$kk} =  $URL . $parta . $ddd . $partb;
					      my ($tmp,$jk1) = getCompletionInfo($href, $k);
					      if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
					      elsif($detail) {$::ctasksDetails{$kk} = $detail;}
					  }
				      } 
				  }
				  ($osme, $osde, $osye) = ($sme,$sde,$sye);
				  ($nnm, $sde, $sye) = canDate($sme+$c1, $sde, $sye);
				  if($nnm != ($sme+ $c1)%12) { $i++;}
				  $sme = $nnm;
				  last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			      }
			  } elsif($word eq 'MND') {
			      ($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			      my ($mxdays, $ndb); $mxdays= ndays_in_month($sme, $sye); $ndb = $mxdays - $sde;
			      ($osme, $osde, $osye) = ($sme,$sde,$sye);
			      for($i = 1; $i <= $repeat; $i++) {
				  if($sde > 0) {
				      $k = 0;
				      for $j (0 .. $elength) { if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
				      $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
				      $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
				      $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
				      last if (not $before and not $b1);
				      if($k == 0) {
					  $ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
					  if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
					  if($pz or ($a0 and $b1)) {
					      $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
					      if($detail) {$::ptasksDetails{$kk} = $detail;}
					  }
				      } elsif($k < 0) {
					  if($a0 and $b1) {				
					      $ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
					      $::ctasks{$kk} =  $URL . $parta . $ddd . $partb;
					      my ($tmp,$jk1) = getCompletionInfo($href, $k);
					      if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
					      elsif($detail) {$::ctasksDetails{$kk} = $detail;}
					  }
				      } 
				      ($osme, $osde, $osye) = ($sme,$sde,$sye);
				  }
				  ($sme, $sde, $sye) = canDate($sme+$c1, 10, $sye);
				  last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
				  $mxdays = ndays_in_month($sme, $sye); $sde = $mxdays - $ndb;
			      }
			  } elsif($word eq 'MNW') {
			      my ($nth, $nnm, $nwb, $mxdays, $offset, $fit);
			      ($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			      $wday = wday($sme, $sde, $sye);	# weekday of event
			      $mxdays = ndays_in_month($sme, $sye);
			      $nth =  1 + ($mxdays-$sde)/7;	# the nth weekday, counting backwards
			      ($osme, $osde, $osye) = ($sme,$sde,$sye);
			      for($i = 1; $i <= $repeat; $i++) {
				  $k = 0;
				  for $j (0 .. $elength) {  if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
				  $mxdays = ndays_in_month($sme, $sye);
				  $x= wday($sme, $mxdays, $sye);	
				  if($x > $wday) { $offset = ($wday - $x) + ($nth -1 )* 7;}
				  else { $offset = 7 + $x - $wday + ($nth -1) * 7;}
				  $sde = $mxdays - $offset; #to the correct weekday
				  if($sde <= 0) { $fit = 0;} else {$fit = 1;}				  
				  if($fit) {
				      $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
				      $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
				      $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
				      last if (not $before and not $b1);
				      $ddd="$sme/$sde/$sye"; $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				      if($k == 0) {
					  if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
					  if($pz or ($a0 and $b1)) {					  
					      $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
					      if($detail) {$::ptasksDetails{$kk} = $detail;}
					  }
				      } elsif($k < 0) {
					  if($a0 and $b1) {				
					      $::ctasks{$kk} =  $URL . $parta . $ddd . $partb;
					      my ($tmp,$jk1) = getCompletionInfo($href, $k);
					      if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
					      elsif($detail) {$::ctasksDetails{$kk} = $detail;}
					  }
				      } 
				      ($osme, $osde, $osye) = ($sme,$sde,$sye);
				  }
				  ($nnm, $sde, $sye) = canDate($sme+$c1, 10, $sye);
				  $sme = $nnm;
				  last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			      }
			  } elsif($word eq 'W') {
			      my ($x, $y, $err, $adv, $nbits, $jj);
			      ($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			      ($osme, $osde, $osye) = ($sme,$sde,$sye);
			      $nbits = unpack "%8b*", pack("C", $c2);
			      $adv = ($c1 -1) * 7;
			      $wday = wday($sme, $sde, $sye);	# weekday of event
			      for($i = 0; $i < $repeat; $i += $nbits, $wday=0) {
				  $err=wday($sme, $sde, $sye);
				  $jj=0;
				  for($x=$wday; $x <7; $x++) {
				      if( ($c2 & (1<<$err))) {
					  $y = $i +$jj; $jj++;
					  if($y < $repeat) {
					      $k = 0;
					      for $j (0 .. $elength) { if( abs($exception->[$j]) == $y) { $k = $exception->[$j]; last;}}
					      $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
					      $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
					      $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
					      last if (not $before and not $b1);
					      if($k == 0) {
						  $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$y";
						  if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
						  if($pz or ($a0 and $b1)) {					  
						      $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
						      if($detail) {$::ptasksDetails{$kk} = $detail;}
						  }
					      } elsif($k < 0) {
						  if($a0 and $b1) {				
						      $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$y";
						      $::ctasks{$kk} = $parta . $ddd . $partb;
						      my ($tmp,$jk1) = getCompletionInfo($href, $k);
						      if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
						      elsif($detail) {$::ctasksDetails{$kk} = $detail;}
						  }
					      }
					  }
				      }
				      $err += 1;
				      ($osme, $osde, $osye) = ($sme,$sde,$sye);
				      ($sme, $sde, $sye)=canDate($sme, $sde+1, $sye);
				      last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
				  }
				  ($sme, $sde, $sye)=canDate($sme, $sde+$adv, $sye);			
				  last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));	  
			      }
			  } elsif($word eq 'X') {
			      my ($x, $y, $err, $adv, $jj);
			      my $nwks = int($c1/5);  my $mod = $c1%5;
			      my $ndays = $nwks * 7 + $mod;
			      ($sme, $sde, $sye) = split(/\//,$edate);  $sme--;
			      ($osme, $osde, $osye) = ($sme,$sde,$sye);
			      for($i = 1; $i <= $repeat; $i++) {
				  $k = 0;
				  for $j (0 .. $elength) {if( abs($exception->[$j]) == $i) { $k = $exception->[$j]; last;}}
				  $a0=mdyAafterB($sme, $sde, $sye, $::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
				  $b1=mdyAafterB($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'},$sme, $sde, $sye);
				  $before=mdyAafterB($nowM, $nowD, $nowY,$sme,$sde,$sye);
				  last if (not $before and not $b1);
				  if($k == 0) {
				      $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
				      if($before > 1 or ($before==1 and ($nowH>$hr or($nowH==$hr and $nowN >$mn)))){$pz=1;}else{$pz=0;}
				      if($pz or ($a0 and $b1)) {
					  $::ptasks{$kk} =  $URL . $cfm . $parta . $ddd . $partb . $overdue[$pz];
					  if($detail) {$::ptasksDetails{$kk} = $detail;}
				      }
				  } elsif($k < 0) {
				      if($a0 and $b1) {				
					  $ddd="$sme/$sde/$sye";  $bbb="$osme/$osde/$osye"; $kk= "$ddd/$bbb/$ttt:$i";
					  $::ctasks{$kk} = $parta . $ddd . $partb;
					  my ($tmp,$jk1) = getCompletionInfo($href, $k);
					  if($tmp) { $::ctasksDetails{$kk} = $detail . "<br>$tmp";}
					  elsif($detail) {$::ctasksDetails{$kk} = $detail;}
				      }
				  }
				  ($osme, $osde, $osye) = ($sme,$sde,$sye);
				  my $start =wday($sme, $sde, $sye);  my $tmp=0;
				  $start += $mod; if($start > 5) { $tmp = 2; $start -= 5;}
				  ($sme, $sde, $sye) = canDate($sme, $sde + $ndays+$tmp, $sye);	    
				  last if($endY and mdyAafterB($sme,$sde,$sye,$endM,$endD,$endY));
			      }
			  }			  
		      }
		}
	    }
	}
    }
    return $cached;
}
#=====================================================================================================
sub completionString {
    my ($input) = (@_);
    my ($zm, $zd, $zy, $zhr, $zmn, $doer) = split(/\//, $input);
    my $dat = mdy_nstring($zm, $zd, $zy);
    my $tim; if(! defined $zhr ) { $tim ="0:00";} else { $tim = hm_string($zhr, $zmn);}
    if(! $doer) { $doer = $::calinfo{'w'};}
    my $rname = getinfo($doer, 'name'); $rname = "" if ! $rname;
    $doer = "$rname ($doer)";
    my $tmp = sprintf $::phr{'taskDoneFormat'}, $doer, $dat,  $tim;
    my $smp = sprintf $::phr{'DoneOn'}, "<font color=#0000cc>$dat</font>", "<font color=#000099>$rname</font>";
    return ("<font size=1 color=#ff6600><span class=\"taskDoneA\">$tmp</span></font>", 
	    "<font size=1 color=#993300><span class=\"taskDoneB\">$smp</span></font>")
}
sub getCompletionInfo {
    my ($href, $which, $month, $day, $year) = (@_);
    if($which == 0) {
	if($href->{'ctd'}) { 
	    return (completionString($href->{'ctd'}));
	} elsif($href->{'ctds'} and $day and $href->{'repeat'} and $href->{'repeat'} > 1) { #month: 0--11
            my $tm = $month+1; 
            my $tdate = "$tm/$day/$year";
	    my $occ = calmatch($tdate, $href->{'date'}, $href->{'occurs'}, $href->{'repeat'}, undef, 0);
            if($occ) {
                my @list = split(/\|/, $href->{'ctds'});
                my $tmp;
                $which = "-$occ";
                foreach $tmp (@list) {
                    my ($k, $v) = split(/=/, $tmp, 2);
                    if($k and $k eq $which) {
                        return (completionString($v));
                        last;
                    }
                }
            }
	}
    } elsif($which < 0) {
	if($href->{'ctds'}) {
	    my @list = split(/\|/, $href->{'ctds'});
	    my $tmp;
	    foreach $tmp (@list) {
		my ($k, $v) = split(/=/, $tmp, 2);
		if($k and $k eq $which) {
		    return (completionString($v));
		    last;
		}
	    }
	}
    }
    return ("","");
}
#=====================================================================================================
sub tasks {
    my ($bscript, $script, $body) = ("", "", "");
    my $cached = 0;
    #if($::d{'remote_user'} eq 'anonymous') {$::o{'listAllCals'} = 1;}
    ($bscript, $script) = &getClockScript();
    my $pnt = $::calinfo{'pnt'}; 
    if($pnt) {
	$body = " onLoad=\"window.print()\"";
	&headers("$::phr{'Tasks'}","",0,0,1,$body);
    } else {
	$body = $bscript;
	&headers("$::phr{'Calendar'}", $script, $webcalConfig::r{'refreshInterval'}, 1, 1, $body);    
    }
    my ($w, $v, $ls, $mn, $sdate,$tmp,$memb, $owner, @mlist, $zzz, $stmp, $mg, $count, $tkind);
    $w = $::calinfo{'w'}; $v = $::calinfo{'v'};$ls = $::calinfo{'ls'};
    $sdate = "$::calinfo{'month'}/$::calinfo{'day'}/$::calinfo{'year'}/11/0";
    if($v == 1) {
	$::o{'td0'} = $::calinfo{'day'}; $::o{'tm0'} = $::calinfo{'month'}; $::o{'ty0'} = $::calinfo{'year'};
	($::o{'tm1'}, $::o{'td1'}, $::o{'ty1'}) = ($::o{'tm0'}, $::o{'td0'}, $::o{'ty0'});
    } elsif($v == 2) {
	my $wcode = wday($::calinfo{'month'},$::calinfo{'day'}, $::calinfo{'year'});
	if($wcode == 0 && $::o{'weekstart'}) {$wcode = 7;}
	($::o{'tm0'}, $::o{'td0'},$::o{'ty0'}) = canDate($::calinfo{'month'},$::calinfo{'day'}-$wcode,$::calinfo{'year'});
	($::o{'tm1'}, $::o{'td1'},$::o{'ty1'}) = canDate($::o{'tm0'},$::o{'td0'}+7,$::o{'ty0'});
    } elsif($v == 3) {
	($::o{'tm0'}, $::o{'td0'},$::o{'ty0'}) = ($::calinfo{'month'},1,$::calinfo{'year'});	
	($::o{'tm1'}, $::o{'td1'},$::o{'ty1'}) = ($::calinfo{'month'},31,$::calinfo{'year'});	
    } else {
	($::o{'tm0'}, $::o{'td0'},$::o{'ty0'}) = (1,1,$::calinfo{'year'});		
	($::o{'tm1'}, $::o{'td1'},$::o{'ty1'}) = (12,31,$::calinfo{'year'});		
    }
    $cached = &gettasks();
    
    if($pnt) {
	$::o{'tw'} = 100; my $cn = "";
	my $name = $::calinfo{'dname'}; $name = $::calinfo{'name'} unless $name;  $name = $w unless $name;
	if($::d{'megaCal'} ne "") {
	    my ($memb, @mlist);
	    @mlist = split(',',$::d{'megaCal'});
	    $cn="$::phr{'CombinedCalendar'}<br>";
	    for $memb (@mlist) {
		$memb =~ s/[ ]+//g;
		my $tmp = getinfo($memb, 'name');
		$cn .= "<span class=\"memberInTitle\">$tmp, </span> ";
	    }
	    $cn =~ s/, $//g;
        } else {$cn = "<span class=\"calendarTitle\">$name</span>";}
        print "<center><h2>$cn</h2></center>";
    } else {
	my $headerForm=&newHeader('task', 1);
	print $headerForm;
	if(!($::vm & 0x8) and $v > 0) {
	    print "<table width=\"$::o{'tw'}%\" border=0 cellpadding=0 cellspacing=0 bgcolor=\"#ffcc66\" class=\"dnbar\">";
	    print "<tr>";
	    print "<td align=center noWrap width=\"80%\" class=\"dnbarTd\" height=16><font size=-2>";
	    my $cmd="task"; if($::calinfo{'tkind'} and $::calinfo{'tkind'} eq 'c') { $cmd="task&tkind=1";}
	    if($::d{'megaCal'} ne "") {$mg="&mg=$::d{'megaCal'}"; } else {$mg="";}
	    &ndbar($cmd, $::calinfo{'month'}, $::calinfo{'day'}, $::calinfo{'year'},  $w, $v, $ls, $mg);
	    print <<END;
</font></td></tr>
<tr><td colspan=16 bgcolor=#666633><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=1 border=0></td></tr>
</table>
END
    ;
	    $|=1; print "\n"; $|=0;
	}
    }
    print "<br>";
    if($::calinfo{'tkind'} and $::calinfo{'tkind'} eq 'c') {
	$count = dpyTasks(\%::ctasks, \%::ctasksDetails, 0);
	$::calinfo{'exf'} = '&tkind=c';
    } else {
	$count = dpyTasks(\%::ptasks, \%::ptasksDetails, 1);
    }

    if($count == 0) {
	print "<center><h3>&nbsp;&nbsp;$::phr{'NoEvents'}</h3></center>";
#	print "<form>&nbsp;&nbsp;<b><input type=button value=\"$::phr{'GoBack'}\" onclick=\"history.go(-1)\"></b></form>";
    }
    &trailer(1, 1);
    
    if($cached == 0 and $::d{'megaCal'} eq "") {
        my $who = untaintname($::calinfo{'w'},$::phr{'Invalidusername'});
        my $cdir="$::o{'spooldir'}/$who/cache";
        if(! -d "$cdir") { mkdir("$cdir", 0711);} 
        my $file =  "$cdir/tasks";
	my $fhtf = gensym;
        if(sysopen($fhtf, "$file", O_WRONLY | O_CREAT, 0644 ) and &webcalLock::doflock(\*$fhtf, LOCK_EX, "$file")) {
            truncate($fhtf, 0);
            print $fhtf '@::tasks=(';
            my $href;
            for $href (@::caldata) {
                if($href->{'kind'} == 2) { my $tmp = print1Entry($href); print $fhtf $tmp;}
            }
            print $fhtf ");1;\n";
            &webcalLock::doflock(\*$fhtf, LOCK_UN, "$file");
            close($fhtf);
        }
    }
}
#=====================================================================================================
sub dpyTasks {
    my($tasks, $tasksDetails,$new) = (@_);
    my (@keys, $key, $count, $jj, $dateinfo, $month, $day, $year, $hr, $mn,$tag, $color, $smp, $edit, $ok, $author,$occ);
    my ($tim, $tmp, $detail, $tcolor, $tdcolor, $href, $who, $view, $ls, $sdate, $mg, $lvheader, $checked, $ed, $ecnt);
    my ($tkind, $extra, $sdateinfo);
    my ($form, $ef, $add) =("","", "");

    @keys = sort sortDateTime (keys %$tasks);
    $count = scalar @keys;
    #if($count == 0) {return 0;}
    $who = $::calinfo{'w'};
    $view = $::calinfo{'v'};
    $ls = $::calinfo{'ls'};
    $sdate = "$::calinfo{'month'}/$::calinfo{'day'}/$::calinfo{'year'}";
    $ecnt = 0;
    my $tbclr=$webcalConfig::r{'bluebar'}; 

    if($::d{'megaCal'} ne "") { $mg="&mg=$::d{'megaCal'}"; $edit = 0; }
    else { 
	if(!$new) {$extra='<input type=hidden name=tkind value=c>';} else {$extra="";}
        $edit = 1; $mg="";
        $ef = "<td bgcolor=$tbclr class=\"taskRow1Td\"><font size=1>&nbsp;</font></td>";
        print <<END;
<form action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value=etsk>
<input type=hidden name=v value=$view>
<input type=hidden name=sk value=1>
<input type=hidden name=ls value=$ls>
<input type=hidden name=w value="$who">
<input type=hidden name=d value="$sdate">
$extra
END
    ;
    }
    my $pnt = $::calinfo{'pnt'}; if($pnt) {$edit =0;}
    my ($nextc, $prevc, $datestr, $cmd);
    if(1) {
	$cmd = "task"; if($::calinfo{'tkind'} and $::calinfo{'tkind'} eq 'c') { $cmd ="task&tkind=c";}
	$month = $::calinfo{'month'}; $year = $::calinfo{'year'}; $day = $::calinfo{'day'}; 
	if($view == 3) {
	    $datestr="<span class=\"mvTitle\">$::mname[$month] $year</span>";
	    $prevc = printDate0( $month-1, 1, $year); $nextc = printDate0( $month+1, 1, $year); 
	} elsif($view ==2) {
	    my $wcode= wday($month, $day, $year);
	    if($wcode == 0 && $::o{'weekstart'}) {$wcode = 7;}
	    my $tday = $day = $day - $wcode;
	    my ($tm, $td, $ty) = canDate($month, $tday, $year);
	    $datestr = "<span class=\"wvTitle\">$::phr{'Week_starts_on'} ".mdy_string($tm,$td,$ty) . "</span>";
	    $prevc = printDate0( $month, $day -7, $year); $nextc = printDate0( $month, $day +7, $year); 
	} elsif($view ==1) {
	    $datestr = mdy_wstring($month,$day,$year);
	    $datestr = "<span class=\"dvTitle\">$datestr</span>";  
	    $prevc = printDate0( $month, $day -1, $year); $nextc = printDate0( $month, $day +1, $year); 
	} else {
	    $prevc = printDate0( $month, 1, $year-1); $nextc = printDate0( $month, 1, $year+1); 
	    $datestr = "<span class=\"yvTitle\">$year</span>"; 
	}
	$::o{'previousc'} = $prevc; $::o{'nextc'} = $nextc;	
	if(!$pnt) {
	    $nextc = "<img src=\"$::o{'imgdirurl'}/spacer.gif\" width=4 height=1 border=0><a href=\"$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=$view&d=$::o{'nextc'}/9/0$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/rright.gif\" width=10 height=12 border=0></a>";
	    $prevc = "<a href=\"$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=$view&d=$::o{'previousc'}/9/0$mg$::vmg\"><img src=\"$::o{'imgdirurl'}/rleft.gif\" width=10 height=12 border=0></a><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=4 height=1 border=0>";
	} else {$nextc=$prevc="";}
    }
    if($new) {
	print <<END;
<table border=0 cellpadding=0 cellspacing=0 class="taskTab">
<tr><td class="taskTabSpacer" width=40><br></td>
<td class="taskTabTdActive" nowrap>
<img src="$::o{'imgdirurl'}/lright.gif" width=11 height=11 border=0><font color=#999999><b><span class="taskLabel">$::phr{'PendingTasks'}</span></b></font></td>
END
    ;
	if(!$pnt) {
	    print <<END;
<td class="taskTabSpacer"><img src="$::o{'imgdirurl'}/spacer.gif" width=32 height=1 border=0></td> 
<td class="taskTabTd" nowrap>
<img src="$::o{'imgdirurl'}/barrow.gif" width=11 height=11 border=0><a href="$::o{'cginame'}?c=task&tkind=c&ls=$ls&w=$who&v=$view&d=$sdate&$mg$::vmg"><b><span class="taskLabel">$::phr{'CompletedTasks'}</span></b></a></td>
END
    ;
	}
	print <<END;
<td><img src="$::o{'imgdirurl'}/spacer.gif" width=100 height=4></td>
<td align=center><font color=red>$prevc $datestr $nextc </font></td>
</tr></table>
END
    ;
    } else {
	print <<END;
<table border=0 cellpadding=0 cellspacing=0 class="taskTab">
<tr><td width=40 class="taskTabSpacer"><br></td>
END
    ;
	if(!$pnt){
	    print <<END;
<td class="taskTabTd" nowrap>
<img src="$::o{'imgdirurl'}/barrow.gif" width=11 height=11 border=0><a href="$::o{'cginame'}?c=task&ls=$ls&w=$who&v=$view&d=$sdate&$mg$::vmg"><b><span class="taskLabel">$::phr{'PendingTasks'}</span></b></a></td>
<td><img src="$::o{'imgdirurl'}/spacer.gif" width=32 height=1 border=0></td> 
END
    ;
	}
	print <<END;
<td class="taskTabTdActive" nowrap>
<img src="$::o{'imgdirurl'}/lright.gif" width=11 height=11 border=0><font color=#999999><b><span class="taskLabel">$::phr{'CompletedTasks'}</span></b></font></td>
<td><img src="$::o{'imgdirurl'}/spacer.gif" width=100 height=4></td>
<td align=center><font color=red>$prevc $datestr $nextc </font></td>
</tr></table>
END
    ;
    }

    my $uwidth = $::o{'tw'} - 5;
    my $border = 0; if($pnt) {$border = 1;} 
    print <<END;
<center>
<table border=$border cellpadding=0 cellspacing=0 width="$uwidth%" bgcolor="#006690" class="backtbltask">
<tr><td width="100%"  bgcolor="#006690" class="backtbltask">
<table border=$border cellpadding=2 cellspacing=1 width="100%" class="tasktbl">
<tr>$ef<td width="5%" noWrap bgcolor=$tbclr class="taskRow1Td"><font color="#cccc99" size=1>
<span class="taskRow1Txt">$::phr{'StartDate'}</span></font></td>
<td width="5%" noWrap bgcolor=$tbclr class="taskRow1Td">
<font color="#cccc99" size=1><span class="taskRow1Txt">$::phr{'DueDate'}</span></font></td>
<td width="5%" noWrap bgcolor=$tbclr class="taskRow1Td"><font color="#cccc99" size=1>
<span class="taskRow1Txt">$::phr{'DueTime'}</span></font></td>
<td width="40%" bgcolor=$tbclr class="taskRow1Td"><font color="#cccc99" size=1>
<span class="taskRow1Txt">&nbsp;&nbsp;&nbsp;&nbsp;$::phr{'What'}</span></font></td>
<td width="45%" bgcolor=$tbclr class="taskRow1Td"><font color="#cccc99" size=1>
<span class="taskRow1Txt">$::phr{'Details'}</span></font></td></tr>
END
    ;
    $jj = 0;
    my $jc=0;
    if($count > 0 ) {
	for $key (@keys) {
	    ($dateinfo, $tag, $color, $ed, $occ)=split(/:/, $key);
	    if(! defined $occ) {$occ = "";} else {$occ =":$occ";}
	    my ($bm, $bd, $by);
	    ($month, $day, $year, $bm, $bd, $by, $hr, $mn) = split(/\//, $dateinfo); # month: 0--11
	    my $wcode= wday($bm, $bd, $by);
	    $sdateinfo = "$::swd[$wcode] " .  mdy_nstring($bm+1, $bd, $by);	    
	    $wcode= wday($month, $day, $year);
	    $dateinfo = "$::swd[$wcode] " .  mdy_nstring($month+1, $day, $year);
	    
	    $tim = hm_string($hr,$mn);
	    $tmp = $tasks->{$key};
	    $detail = $tasksDetails->{$key};
	    $detail = "<br>" unless $detail;
	    if($color) { $tdcolor="bgcolor=$color" }
	    else {
		my $clr = $webcalConfig::r{'rowColors'}->[($jj&1)];
		$tdcolor="bgcolor=$clr";
	    }
	    $href = $tmp;
	    if($href =~ m/<a (href="[^"]*").*/) {$href = $1;} else {$href="";} #")
	    $href =~ s/(c=ed)|(c=cfm)/c=m2/s;
	    $tcolor="$::o{'tclrt'}";
            $smp="";
	    $jc = ($jc? 0: 1);
            if($edit) {
                if($ed) {
                    if($new) {
			if($ed != 4) {
			    $smp = "<td class=\"taskckbox$jc\" $tdcolor><input type=checkbox class=\"fmRadio\" name=t$jj value=$tag$occ style=\"background-color:#cccc00\"></td>"; $ecnt++;
			    print "<input type=hidden name=td$tag value=1>";
			} else {
			    $smp = "<td class=\"taskckbox$jc\" $tdcolor><input type=checkbox class=\"fmRadio\" name=t$jj value=$tag$occ></td>"; $ecnt++;
			}
                    } elsif($ed == 4) {
                        $smp = "<td class=\"taskckbox$jc\" $tdcolor><input type=checkbox class=\"fmRadio\" name=t$jj value=$tag$occ></td>"; $ecnt++;
                    }
                }
                if($smp eq ""){ $smp = "<td class=\"taskckbox$jc\" $tdcolor>&nbsp;</td>";}
            }
	    print <<END;
<tr>$smp<td width="5%" noWrap $tdcolor class="taskSdate$jc"><font color=$tcolor size=1><span class="taskSdate">$sdateinfo</span></font></td> 
<td width="5%" noWrap $tdcolor class="taskDdate$jc"><font color=$tcolor size=1><span class="taskDdate">$dateinfo</span></font></td>
<td width="5%" $tdcolor class="taskDtime$jc"><a $href><font size=-1><b><span class="taskDtime">$tim</span></b></font></a></td>
<td width="40%" $tdcolor class="taskTitle$jc"><font size=-1><span class="taskTitle">$tmp</span></font></td>
<td width="45%" $tdcolor class="taskDetail$jc"><font size=-1><span class="taskDetail">$detail</span></font></td></tr>
END
    ;
	    $jj++;
	}
    }
    print "</table>\n";
    print "</tr></td></table>\n";
    if($edit) {
	print "<input type=hidden name=total value=$jj>";
        print "<table border=0><tr><td><b>&nbsp;";
        if($ecnt > 0) {
            if($new) { print "<input type=submit name=action value=\"$::phr{'MarkComplete'}\" class=\"fmBtnSt\">&nbsp;&nbsp;";}
            print "<input type=submit name=action value=\"$::phr{'DeleteChecked'}\" class=\"fmBtnSt\">&nbsp;&nbsp;";
        }
        print "</b></td></tr></table></form>";
    }    
    print "</center>";
    return $count;
}
#=====================================================================================================
sub copyTask {
    my ($href) = (@_);
    my $hash={};
    my ($k);
    for $k (keys %$href) { $hash->{$k} = $href->{$k};}
    return $hash;
}
#=====================================================================================================

sub etask {
    my ($who, $i, $count, $total, @list, %events, $hash, $today, $href, $tag, @savedata, $action, $rtag, $occ, %ohash, %chash, $key);
    $who = $::calinfo{'w'};
    if( $::calinfo{'action'} eq "$::phr{'MarkComplete'}") { $action = 2;} # mark complete
    elsif( $::calinfo{'action'} eq "$::phr{'DeleteChecked'}") { $action = 1;}
    else { calerror("unknown command $action, should never happen!",1); myexit(0);}

    $total = $::calinfo{'total'}; if($total > 500) { $total = 500;}   @list = (); 
    for($i=0; $i<$total; $i++) { my $a="t$i"; if($::calinfo{$a}) { push(@list, $::calinfo{$a});} }
    $count = 0+ @list;
    if($count == 0) { calerror("No tasks were selected",1);}
    $today = printDate( $::now{'month'}, $::now{'day'}, $::now{'year'}) . "/$::now{'hour'}/$::now{'min'}/" . $::d{'remote_user'};
    #save events
    %events =(); %ohash=(); %chash=(); 
    my $username =  untaintname($who,$::phr{'Invalidusername'});
    my $calname="$::o{'spooldir'}/$username";
    my $fhfv = gensym;
    if( -d $calname and -f "$calname/data" and sysopen($fhfv, "$calname/data", O_WRONLY | O_CREAT, 0644) ) {
        &webcalLock::doflock( \*$fhfv, LOCK_EX, "$calname/data") or calerror("Cannot lock file '$calname/data': $!\n",1);     
        do "$calname/data";
        
        for $rtag (@list) {
            ($tag, $occ) = split(/:/,$rtag);
            for $href (@::caldata) {
                if( $href->{'key'} == $tag) {
                    if($action == 2) { # mark complete
                        if(!$occ) {
                            $href->{'ctd'} = $today; $href->{'done'} = 'y'; 
                            $events{$tag} = copyTask($href);
                        } else {
                            if($href->{'ctds'}) { my $z=$href->{'ctds'}; $href->{'ctds'} ="-$occ=$today\|$z";}
                            else { $href->{'ctds'} ="-$occ=$today";}
                            if(! $ohash{$tag}) {
                                $events{$tag} = copyTask($href);
                                $ohash{$tag} ="-$occ"; 
                            } else {
                                $ohash{$tag} .=", -$occ";
                                my $zz = $events{$tag}; $zz->{'ctds'} = $href->{'ctds'};
                            }
                        }
                    } 
                    else { # delete, check permission
                        my ($a, $tmp);  $a = "td$tag"; $tmp =$::calinfo{$a};
                        if(! $tmp) {
                            if(!$occ) {
                                $href->{'deleted'} = 1; 
                                $events{$tag} = copyTask($href);
                            } else {
                                if(! $ohash{$tag}) {
                                    $events{$tag} = copyTask($href);
                                    $ohash{$tag} ="$occ";
                                } else {
                                    $ohash{$tag} .=", $occ";
                                }
                            }
                        }
                    }
                    last;
                }
            }
        }
        if( scalar(keys %events) == 0) { 
            &webcalLock::doflock( \*$fhfv, LOCK_UN, "$calname/data") or calerror("Cannot unlock file '$calname/data': $!\n",1);
            close $fhfv;
            calerror("Cannot delete selected tasks, permission denied!",1);
        }
        for $key (keys %ohash) {
            my ($a, $b, $c, $d, $v, $tmp, $old, $deleted, $ctds);
            $v = $ohash{$key}; $v = "[ $v ]"; $tmp = eval $v;
            $href= $events{$key};
            $deleted = 0;
            if($action == 2) { # mark complete
                $ctds = $href->{'ctds'};
                if ($ctds) { $chash{$key} = $ctds;}
            }
            if( $href->{'exception'}) {
                $old = $href->{'exception'};
                foreach $b (@$old) {
                    $c = 1;
                    foreach $d (@$tmp) { if($b == -$d) { $c = 0; last;}}
                    if($c) { push @$tmp, $b;}
                }
                $old = $tmp;
            } else {
                $old = $tmp;
            }     
            $href->{'exception'} = $old;
            $c = 0; foreach $d (@$old) { if($d>0) {$c++;}}
            if($c >= $href->{'repeat'}) { $deleted = 1; $href->{'deleted'} = 1;}
            for $a (@::caldata) {
                if($a->{'key'} == $key) {
                    $a->{'exception'} = $old;
                    if($deleted) { $a->{'deleted'} = 1;}
                    last;
                }
            }
            $tmp = join(',', @$old); $tmp =~ s /[, ]*$//g;
            $ohash{$key} = "[ $tmp ]";
        }
        (@savedata)= (@::caldata); @::caldata =(); # save !
        my ($okmsg, $nokmsg) = ("", "");
        for $key (keys %events) {
            $href = $events{$key};
            (@::caldata) = (@savedata);
            my ($t, $s, $ccc);
            if($chash{$key}) { $ccc= $chash{$key}; } else { $ccc= "";}
            if($ohash{$key}) {
                ($t, $s) = editTask($href, 2, $ohash{$key}, $ccc); 
            } else {
                ($t, $s) = editTask($href, $action, "", $ccc); 
            }
            $okmsg .= $t; $nokmsg .= $s;
        }
        # update calendar $who
        (@::caldata) = (@savedata); 
        $::d{'eventCounter'} = 1;
        my $username =  untaintname($who,$::phr{'Invalidusername'});
        my $calname="$::o{'spooldir'}/$username";
        # if( -d $calname && -f "$calname/data" ) {
        #    if (sysopen($fhfv, "$calname/data", O_WRONLY | O_CREAT, 0644 ) ) {
        #        &webcalLock::doflock( \*$fhfv, LOCK_EX, "$calname/data") or calerror("Cannot lock file '$calname/data': $!\n",1);

        truncate($fhfv, 0);
        print $fhfv "\@::caldata = (\n";
        for $href (@::caldata) {
            next if $href->{'deleted'};    
            my $tmp = $href->{'key'};
            if($tmp > $::d{'eventCounter'}) { $::d{'eventCounter'} = $tmp;}
            $tmp = print1Entry($href);
            print $fhfv $tmp;
        }
        $::d{'eventCounter'}++;
        print $fhfv ");\n$::d{'eventCounter'};\n";
        &webcalLock::doflock( \*$fhfv, LOCK_UN, "$calname/data") or calerror("Cannot unlock file '$calname/data': $!\n",1);
        close $fhfv;
        #    }
        #}

        my $msg = "$::phr{'UpdatedOK'}: $who<br>";
        if($okmsg) {$msg .= "$::phr{'Updated_calendars'}: $okmsg<br>";}
        if($nokmsg){ $msg .= "$::phr{'errorPerm'}: $nokmsg<br>";}
        my $ls = $::calinfo{'ls'}; my $view=$::calinfo{'v'}; my $d=$::calinfo{'d'};
        my $refresh = "1; URL=$::o{'cginame'}?c=task&ls=$ls&w=$who&v=$view&d=$d$::vmg";
        &headers($::phr{'Acknowledgement'},undef,$refresh, 1);
        print "<br>&nbsp;<br>&nbsp;<br><center>";
        print "<p><font color=#ff0000><b><span class=\"warnMsg\">$msg</span></b></font>";
        print "<p><table bgcolor=$webcalConfig::r{'dkbackground'} border=2 cellpadding=2><tr><td><a href=\"$::o{'cginame'}?c=task&ls=$ls&w=$who&v=$view&d=$d$::vmg\">$::phr{'BackToCalendar'}</a></tr></table>";
        print "</center>\n";    
        &trailer(0,0);    
        myexit(0);
    } else { calerror($::phr{'openFailed'},1);}
}

#=====================================================================================================
sub getPermission {
    my ($task) = (@_);
    my ($tag, $href, $mkey, $others, $hasmme, $themme, $auth, $isauthor, $isoauthor);
    $mkey = ""; $others="";
    $hasmme=$themme=$isauthor=0; $isoauthor=0;
    $auth= $::d{'authResult'};
    if($task) {
	if($auth == 4) {
	    $tag = $task->{'key'};
	    for $href (@::caldata) {
		if( $href->{'key'} == $tag) {
		    $isauthor = ismember($::d{'remote_user'}, $href->{'author'});
		    if(exists $href->{'mkey'}) { 
			$mkey = $::calinfo{'mkey'} = $href->{'mkey'};
			$isoauthor = 1 if $isauthor == 1  ;
		    }
		    if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
		    $others=$href->{'attendants'};
		    if(isadmin($::d{'remote_user'}) or isvgadmin($::d{'remote_user'},$::calinfo{'w'})){ $isauthor=$isoauthor = 1;}
		    last; 
		}
	    }
	} else {
	    $tag = $task->{'key'};
	    if( $::d{'ispublic'} ) {
		for $href (@::caldata) {
		    if( $href->{'key'} == $tag) {
			$isauthor = ismember($::d{'remote_user'}, $href->{'author'});
			if($isauthor ) { $auth = 4;}
			if(exists $href->{'mkey'}) {
			    $mkey = $::calinfo{'mkey'} = $href->{'mkey'};
                            $isoauthor = 1 if $isauthor == 1  ;
			}
			if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
			$others=$href->{'attendants'};
			last;
		    }
		}
	    }
	    if($auth != 4) {
		for $href (@::caldata) {
		    if( $href->{'key'} == $tag) {
			$isauthor = ismember($::d{'remote_user'}, $href->{'author'});
			if($isauthor) { $auth = 4; }
                        $isoauthor = 1 if $isauthor == 1  ;
			if(exists $href->{'mkey'}) {
			    $mkey = $::calinfo{'mkey'} = $href->{'mkey'};
			}
			if(exists $href->{'mme'}) { $themme = $href->{'mme'}; $hasmme = 1;}
			$others=$href->{'attendants'};
			last;
		    }
		}
		# allow deletion if
		# 1) remote_user is author or
		# 2) the event is taged editable by participants and remote_user is a member
		my $tkey= $mkey;
		$tkey =~ s/_eMe_\d+//g;
		if(isre($::d{'remote_user'}, $tkey,'editors') or $isauthor) { $auth = 4;}
		elsif ($hasmme) {
		    if($themme) {	# allow to edit
			my $att = $others;
			$att =~ s/[,; ]+/:/g;
			$att =~ s/:$//g;
			$att = expandMeetingGroups($tkey, $att);
			if(ismember($::d{'remote_user'}, $att)) { $auth = 4;}
		    }
		}
	    }
	}
    }
    return ($auth, $mkey, $others, $hasmme, $themme, $isauthor, $isoauthor);
}
#=====================================================================================================
sub editTask {
    my ($task, $cmd, $estr, $cstr) = (@_);
    my ($who, $mkey, $others, $hasmme, $themme, $auth, $isauthor,$isoauthor);
    my ($okmsg, $nokmsg)=("", "");
    $who = $::calinfo{'w'};
    ($auth, $mkey, $others, $hasmme, $themme, $isauthor, $isoauthor) = getPermission($task);
    if( $auth != 4) {  calerror("Permission problem, should never happen.",1); }
    else {
	if($mkey && $others) {
	    my ($tmk);
	    my $att = $others;
	    $att =~ s/[,; ]+/:/g;
	    $tmk = $mkey;
	    $tmk =~ s/_eMe_\d+//g;
	    $att = expandMeetingGroups($tmk, $att);
	    if($tmk eq "$::d{'remote_user'}" or $isoauthor or (ismember($::d{'remote_user'}, $att) and ($themme > 1 or ($cmd == 2 and $themme > 0)))) {
		$att =~ s/$who//g;
		$att =~ s/:+/, /g;
		$att =~ s/^,//g;
		$att =~ s/, $//g;
		$themme += $isoauthor;
		$okmsg = "$att<br>";
	    } else  {
		$att =~ s/$who//g;
		$att =~ s/:+/, /g;
		$att =~ s/^,//g;
		$att =~ s/, $//g;
		$nokmsg = "$att<br>";
	    }
	}
	if($mkey && $others) {
	    my ($ir0, $sr0) = &fixMeetingEntry($mkey, $themme, $others, $cmd, -1, $estr, "", "", $cstr);
	    if($ir0) { calerror( $sr0,1);}
	}
    }
    return($okmsg, $nokmsg);
}
#=====================================================================================================
sub cfmInvitation {
    my ($task, $tag, $who, $href, $mkey, $kind, $debug, $msg, $jnk, $cmsg, $und, $es, $color);
    $who = $::calinfo{'w'};
    $tag = $::calinfo{'t'};
    $task = undef;
    if(! isre($::d{'remote_user'}, $who, 'editors') ) {
	calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToModify'} ($who).");
    }
    for $href (@::caldata) {if($href->{'key'} == $tag) {$task = $href; last;}}
    $kind = $task->{'kind'}; $mkey =  $task->{'mkey'}; $mkey =~ s/_eMe_\d+//g;
    if($kind == 1){$color="$::o{'tclra'}";}elsif($kind==2){$color="$::o{'tclrt'}";}elsif($kind==3){$color="$::o{'tclrm'}";}else{$color="$::o{'tclrs'}";}
    my ($date, $time,$m,$d,$y, $hr,$mn,$ehr,$emn,$tmp, $duration, $location, $author);
    $date=$task->{'date'}; ($m,$d,$y)=split(/\//,$date); $date=mdy_wstring($m-1,$d,$y);
    if($task->{'start'}) {
	$time=$task->{'start'};
	($hr,$mn)=split(/:/,$time);
	if($task->{'duration'}) {
	    $duration = $task->{'duration'};
	    $tmp=$mn+$duration;  $ehr= int($tmp/60);
	    $ehr += $hr if ($hr ne "");
	    $emn = $tmp % 60; 
	    $time = hm_hm_string($hr,$mn,$ehr,$emn);
	} else { $time = hm_string($hr, $mn);}
	$time = "<br><font color=$color><b>$::phr{'Time'}:</b></font> $time";
    } else {$time="";}
    my ($miscInfo, $troom, $tspkr, $tcat, $trest)  = getMiscInfo($task);
    $author="";
    if($task->{'author'}) {
	my @aa=split(/[,: ]/, $task->{'author'});
	$m = shift @aa; 
	if($m) {
	    $mn = getinfo($m, 'name');
	    if($mn) { $author = "<br><font color=$color><b>$::phr{'Author'}:</b></font> $mn ($m)";}
	    else { $author = "<br><font color=$color><b>$::phr{'Author'}:</b></font> $m";}
	}
    }
    my $ztmp = $task->{'what'};
    $es= "<table border=0><tr><td><font size=-1><font color=$color><b>$::phr{'Event'}:</b></font> $ztmp <br><font color=$color><b>$::phr{'Date'}:</b></font> $date $time $author $miscInfo </td></tr></table>";

    ($jnk, $cmsg) = confirmMeeting($task, 1);
    # post confirmation form
    &headers($::phr{'AttendanceConfirmation'},"",undef);    
    my($view, $ls, $cfm, $mg, $acc, $dec, $dec_delete);
    $view = $::calinfo{'v'};
    $ls = $::calinfo{'ls'};
    $cfm = $::calinfo{'cfm'};
    $date = printDate0($::calinfo{'month'}, $::calinfo{'day'},$::calinfo{'year'});
    if(defined $::calinfo{'mg'} and $::calinfo{'mg'} ne "") {
	$mg="<input type=hidden name=mg value=\"$::calinfo{'mg'}\">";
    } else {$mg="";}
    $acc = $dec = $und = "";
    if($cfm eq 'a') { $acc = "checked"; $cfm = 1;  $msg = "$::phr{'invitationAccepted'}.";}
    elsif($cfm eq 'd') { $dec = "checked"; $cfm = 0; $msg = "$::phr{'invitationDeclined'}.";}
    else {$cfm = 2;  $msg = ""; $und="checked"; }

    if($mkey ne $who) {
	$dec_delete =<<END_OF_LINE;
<input type=radio class="fmRadio" name=scfm value="-1">&nbsp; <b> <font color=red><span class="fmLabel">$::phr{'DeclineInvitation'} & $::phr{'Delete'}</span></font></b>
<br>
END_OF_LINE
    ;
    } else { $dec_delete = "";}
    
    print <<END;
<Form name=webcal action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value=docfm>
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=t value=$tag>
<input type=hidden name=d value="$date">
<input type=hidden name=w value="$who">
<input type=hidden name=cfm value=$cfm>
$mg
<center>
<br><font size=+1><b><span class="miscTitle">$::phr{'AttendanceConfirmation'}</span></b></font><br><br>
<p><font color=#ff0000><b><span class="warnMsg">$msg</span></b></font><br>
<table bgcolor=$webcalConfig::r{'dkbackground'} border=0 width=60%><tr><td align=center>
<br>
<table><tr><td>
<br>
<input type=radio class="fmRadio" name=scfm value=2 $und><span class="fmLabel">&nbsp; <b>$::phr{'DeferConfirmation'}</span></b>
<br>
<input type=radio class="fmRadio" name=scfm value=1 $acc><span class="fmLabel">&nbsp; <b>$::phr{'AcceptInvitation'}</span></b>
<br>
<input type=radio class="fmRadio" name=scfm value=0 $dec><span class="fmLabel">&nbsp; <b>$::phr{'DeclineInvitation'}</span></b>
<br>
$dec_delete
</td></tr></table>
<br>
</td></tr>
<tr><td align=center>
<input type=submit name=action value="$::phr{'Submit'}" class="fmBtnSt">
&nbsp;&nbsp;&nbsp;<input type=button value="  $::phr{'Cancel'}  " class="fmBtnSt" onclick="javascript:history.go(-1)">
</td></tr></table>
</form>
</center>
<center>
<br>
<table bgcolor=$webcalConfig::r{'dkbackground'} border=0 cellspacing=0 width=60%>
<tr><td>$es</td></tr>
<tr><td><hr></td></tr>
<tr><td><font size=+1><b><span class="miscTitleSmall">$::phr{'Participants'}</span></b></font></td></tr>
<tr><td>
<font size=-1 color=#0000cc><br><span class="fmLabelS">$cmsg</span><br></font>
</td></tr></table>
</center>
END
    &trailer(0,0);   
    myexit(0);
}
#============================================================================================================
sub docfmInvitation {
    my ($task, $tag, $who, $href, $mkey, $kind, $others, $hasmme, $themme, $auth, $isauthor, $isoauthor, $calname, $author);
    $who = $::calinfo{'w'};
    $tag = $::calinfo{'t'};
    $task = undef;
    $who = untaintname($who,$::phr{'Invalidusername'});	
    $calname="$::o{'spooldir'}/$who";
    my $fhtx = gensym;
    if(sysopen($fhtx, "$calname/data", O_WRONLY | O_CREAT, 0644 ) ) {
        &webcalLock::doflock( \*$fhtx, LOCK_EX, "$calname/data") or calerror("Cannot lock file '$calname/data': $!\n",1);
        do "$calname/data";
    
        for $href (@::caldata) {if($href->{'key'} == $tag) {$task = $href; last;}}
        ($auth, $mkey, $others, $hasmme, $themme, $isauthor, $isoauthor) = getPermission($task);
        if( $auth != 4) {
            &webcalLock::doflock( \*$fhtx, LOCK_UN, "$calname/data") or calerror("Cannot lock file '$calname/data': $!\n",1);
            close $fhtx;
            calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToModify'} ($mkey).");
        }

        my ($view, $ls, $cfm, $date, $mg, $acc, $dec, $scfm, $msg);
        $view = $::calinfo{'v'};
        $ls = $::calinfo{'ls'};
        $cfm = $::calinfo{'cfm'};
	$author=$mkey; $author =~ s/_eMe_\d+//g;
        if(defined  $::calinfo{'scfm'}) {$scfm = $::calinfo{'scfm'};} else { $scfm = 2;}
        $msg="";
        $acc= $dec =""; 
        $href=$task;
        $date = printDate0($::calinfo{'month'}, $::calinfo{'day'},$::calinfo{'year'});
        if(defined $::calinfo{'mg'} and $::calinfo{'mg'} ne "") {$mg="&mg=$::calinfo{'mg'}";} else {$mg="";}
        if($cfm != $scfm) { #status changed
            my (@list, $m, $name, $tmp, $w, $cfmd, $decd);
            if($scfm == 1) {
                $cfmd = $href->{'acc'};
                if($cfmd) {	$acc = "$cfmd" . ",$who";} else {$acc = "$who";}
                $decd = $href->{'dec'};	    
                if($decd) {
                    $decd =~ s/[,; ]+/:/g;
                    @list = split(/:/, $decd);
                    foreach $m (@list) {if($m ne $who) {if($dec) {$dec .= ",$m";} else {$dec = "$m";}} }
                }
            } elsif($scfm <= 0) {
                $decd = $href->{'dec'};
                if($decd) {	$dec = "$decd" . ",$who";} else {$dec = "$who";}
                $cfmd = $href->{'acc'};
                $cfmd =~ s/[,; ]+/:/g;
                @list = split(/:/, $cfmd);
                foreach $m (@list) {if($m ne $who) {if($acc) {$acc .= ",$m";} else {$acc = "$m";}} }
		if($scfm < 0 and $author ne $who) { $href->{'deleted'} = 1;}
            } else {
                $cfmd = $href->{'acc'};
                if($cfmd) {
                    $cfmd =~ s/[,; ]+/:/g;
                    @list = split(/:/, $cfmd);
                    foreach $m (@list) {if($m ne $who) {if($acc) {$acc .= ",$m";} else {$acc = "$m";}} }
                }
                $decd = $href->{'dec'};	    
                if($decd) {
                    $decd =~ s/[,; ]+/:/g;
                    @list = split(/:/, $decd);
                    foreach $m (@list) {if($m ne $who) {if($dec) {$dec .= ",$m";} else {$dec = "$m";}} }
                }
            }
            $href->{'acc'} = $acc; 	$href->{'dec'} = $dec;

            my $counter=1;

            # if(sysopen($fhtx, "$calname/data", O_WRONLY | O_CREAT, 0644 ) ) {
            #      &webcalLock::doflock( \*$fhtx, LOCK_EX, "$calname/data") or calerror("Cannot lock file '$calname/data': $!\n",1);

            truncate($fhtx, 0);
            print $fhtx "\@::caldata = (\n";
            for $href (@::caldata) {
                if($href->{'key'} > $counter) {$counter = $href->{'key'};}
		if(! $href->{'deleted'}) {
		    $tmp = print1Entry($href);
		    print $fhtx $tmp;
		}
            }
            $counter += 1;
            print $fhtx ");\n$counter;\n";
            &webcalLock::doflock( \*$fhtx, LOCK_UN, "$calname/data") or calerror("Cannot unlock file '$calname/data': $!\n",1);
            close $fhtx;
            my($ir0, $sr0) = &fixMeetingEntry($mkey, $themme, $others, 3, -1, "", $acc, $dec);
	    if($ir0) { calerror($sr0,1);}
        } else {
            &webcalLock::doflock( \*$fhtx, LOCK_UN, "$calname/data") or calerror("Cannot unlock file '$calname/data': $!\n",1);
            close $fhtx;
        }	
        if($scfm == 1) { $msg = "$::phr{'invitationAccepted'}.";}
        elsif($scfm == 0) { $msg = "$::phr{'invitationDeclined'}.";} 
        my $refresh = "1; URL=$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$date$mg$::vmg";    
        &headers($::phr{'AttendanceConfirmation'},"",$refresh);    
        print "<br>&nbsp;<br>&nbsp;<br><center>";
        print "<p><font color=#ff0000><b>$::phr{'UpdatedOK'}</b></font>";
        print "<p><font color=#006600><b>$msg</b></font>";
        print "<p><table bgcolor=$webcalConfig::r{'dkbackground'} border=2 cellpadding=2><tr><td><a href=\"$::o{'cginame'}?c=get&ls=$ls&w=$who&v=$view&d=$date$::vmg\">$::phr{'BackToCalendar'}</a></tr></table>";
        print "</center>\n";    
        &trailer(0,0);   
        myexit(0);
    } else { calerror($::phr{'openFailed'},1);}
}
#============================================================================================================


sub selectCalendars {
    my $pcnt = $::calinfo{'n'};
    my $ok = 0;
    if( $pcnt and $pcnt > 0) {
        my ($total, $i, $name, $mg, $first);
        $total=0; $mg=""; $first = "";
        for($i=0; $i < $pcnt; $i++) {
            $name="c$i";
            if($::calinfo{$name} and $::calinfo{$name} ne "") {
                if(! $first) {$first = $::calinfo{$name};}
                $mg .= "$::calinfo{$name},";
                $total++;
            }
        }
        if($total == 0) { 
            $ok = 0;
        } elsif($total == 1) {
            $::calinfo{'w'} = $first;
            $ok = 1;
        } else {
            $mg =~ s/,$//g;
            $::calinfo{'w'} = $first;
            $::calinfo{'mg'} = $mg;
            $::calinfo{'mattendants'} = $mg;
            $ok = 2;
        }
        if($ok) { $::calinfo{'c'} = 'get';}
    }
    if($ok == 0) {
	my $nhref = &get_name_list;
        my @allcals  = &listcals;
        my @pcals=();
        my ($name, $type, $fname, $i, $j);
        for $name (@allcals) {
	    $fname = getinfo($name,'name');
	    push @pcals, $name;
	    if($fname) { push @pcals, $fname;} else { push @pcals, $name;}
        }
        my $cnt = 0 + @pcals;
        if($cnt > 0) {
            &headers("$::phr{'Calendar'}");    
            print <<END;
<center>
<br>
<form action="$::o{'cginame'}" method=GET>$::vmp
<input type=hidden name=c value="v">
<input type=hidden name=selectCal value="1">
<input type=hidden name=anonymous value=1>
<table border=0 cellspacing=0><tr><td colspan=2 align=center class="listCal">
<font color=#ff0000 size=+1><b><span class="miscTitle">$::phr{'PleaseSelectACalendar'}</span></b></font></td></tr>
<tr><td colspan=2 align=center>&nbsp;</td></tr>
END
          for($i =0, $j=0; $i < $cnt; $i += 2, $j++) {
              $name = shift @pcals; $fname = shift @pcals;
	      my $type = getinfo($name, 'ctype');
	      if($type) {
                  if($type eq 'public') {$type = $::phr{'PublicOpen'};}
                  elsif($type eq 'public_m') {$type = $::phr{'PublicModerated'};}
                  else {$type = $::phr{'Private'};}
              } else { $type = $::phr{'Private'};}
	      my $des = $nhref->{$name} || "";
              if( ($j & 1) == 0) {
                  print "<tr class=\"listCalTR0\"><td><input type=checkbox class=\"fmRadio\" name=c$j value=\"$name\"><span class=\"fmLabel\"><b>&nbsp;&nbsp;$fname &nbsp;&nbsp;</b>$des</span> <span class=\"fmLabelS\">&nbsp;($type)&nbsp;&nbsp;</span></td>";
              } else {
                  print "<td class=\"listCalTR0\">&nbsp;&nbsp;&nbsp;<input type=checkbox  class=\"fmRadio\" name=c$j value=\"$name\"><span class=\"fmLabel\">&nbsp;&nbsp;<b>$fname</b>&nbsp;&nbsp;$des</span> <span clas\"fmLabelS\">&nbsp;($type)</span></td></tr>";
              }
          }
            if( ($j & 1) == 0) { print "<td>&nbsp;</d></tr>";}
            print "<input type=hidden name=n value=$j>";
            print "<tr><td colspan=2 align=center><font color=#ff0000><b><input type=submit value=\"$::phr{'Submit'}\" class=\"fmBtnSt\"></b></font></td></tr>";
            print "</table></form></center>";
            if($::calinfo{'listcalnbar'}) {
                print "<br><center>$::calinfo{'listcalnbar'}</center>";
                delete $::calinfo{'listcalnbar'};
            }
        } else {
            &greeting("$::phr{'Couldnotfindcalendar'} \'anonymous\'");
        }
        myexit(0);
    }
}
#=====================================================================================================
sub quickadd {
    my ($who, $view, $ls, $month, $day, $year, $scal, $stime, $etime, $dprivacy, $ov, $privacy, @elist, $elist, $udate,$adrm);
    $who = $::calinfo{'w'}; $view = $::calinfo{'v'};  $ls = $::calinfo{'ls'};
    $month= $::calinfo{'month'};  $day  = $::calinfo{'day'}; $year = $::calinfo{'year'};
    $privacy = $::calinfo{'privacy'};
    $stime = select_time("s",$::now{'hour'},0); $etime = select_time("e",1+$::now{'hour'},0);
    $dprivacy= select_value("eprivacy",$privacy,@::privacyList);
    $scal=linkSmallCal("webcal.sdate",$who,$month,$year);
    @elist =($::phr{'Appointment'}, 1, $::phr{'ToDo'}, 2, $::phr{'Meeting'}, 3, $::phr{'Special'},4);
    $elist = select_valueV('k', 1, "onChange=\"activatetime($::o{'hourformat'})\"", @elist);
    my $catlist = build_catlist($who, 'cats', -1, ""); my $hidden="";
    if(!$catlist){$catlist="<input type=text size=20 maxlength=60 name=cat value=\"\" class=\"fmEntry\">";}
    else {$hidden="<input type=hidden name=cat value=\"\">";}
    my $oltmp; if(defined $::calinfo{'ol'}) { $oltmp = $::calinfo{'ol'};} else {$oltmp = 0;}
    $ov = input_radio("aol",$oltmp, @::boolList); 
    $adrm = input_radio("adrm",1, @::switchList); 
    my $overlapthing;
    if($oltmp < 2) { $overlapthing="$::phr{'AllowOverlap'}: $ov";}
    else {$overlapthing="<input type=hidden name=\"aol\" value=2>";}
    $oltmp = $month+1;  $udate = to_native_date("$oltmp/$day/$year");
    &headers(undef," ");
    my $whol= "<span class=\"fmLabel\">$who<input type=hidden name=\"w\" value=\"$who\"></span>";
    if(not $webcalConfig::r{'disable_cal_menu_in_editor'} and ($::calinfo{'mg'} or $::calinfo{'clist'})
       and ! $::calinfo{'nextnew'}) {
	my $nwhol = cal_menu_in_editor('newevent', $who, $who);
	if($nwhol) { $whol = $nwhol;}
    } 

    print <<END;
<br><center>
<Form name=webcal action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value=doedit>
<input type=hidden name=fromqadd value=1>
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=aq value=1>
<input type=hidden name=inpopup value=1>
<input type=hidden name=d value="$month/$day/$year/">
$hidden
<table border=0 cellspacing=1 cellpadding=0>
<tr><td colspan=8 align=center><font size=+1 color="#009900"><b><span class="miscTitleSmall">$::phr{'QuickAdd'}&nbsp;&nbsp;</span> $whol</b></font></td></tr>
<tr><td>&nbsp;</td></tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'Event'}:</span></b></td><td><small>$elist</small></td>
 <td align=right><b><span class="fmLabel">$::phr{'Start'}:</span></b></td><td nowrap><small>$stime</small></td></tr>
<tr> <td align=right><b><span class="fmLabel">$::phr{'Date'}:</span></b></td>
  <td><small><input type=text size=12 maxlength=20 name=sdate value=$udate class="fmEntryS">$scal</small></td>
 <td align=right><b><span class="fmLabel">$::phr{'End'}:</span></b></td><td nowrap><small>$etime</small></td></tr>
<tr><td align=right><span class="fmLabel"><b>$::phr{'What'}:</span></b></td><td rowspan=2><small><textarea wrap=virtual name=description cols=24 rows=2 class="fmTextS"></textarea></small></td>
<td colspan=2 align=center><font color="#cd3b3b" size=-1><span class="fmLabel">&nbsp;$overlapthing</span></font></td></tr>
<tr><td><br></td><td align=right><b><span class="fmLabel">&nbsp;&nbsp;$::phr{'Privacy'}:</span></b></td><td><small>$dprivacy</small></td>
</tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'Category'}:</span></b></td>
<td>$catlist</td><td><b><span class="fmLabel">$::phr{'Location'}:</span></b></td><td>
<input type=text size=20 maxlength=60 name=sroom value="" class="fmEntry"></td>
</tr>
<tr><td colspan=4>
<font color="#cd3b3b"><span class="fmLabelS">&nbsp;$::phr{'applyReminders'}&nbsp;&nbsp;$adrm<span></font></td></tr>
<tr><td colspan=4 height=4></td></tr>
<tr bgcolor="#cccccc"><td colspan=4 align=center>
<b><font color="#ff0000"><input type=submit name=action value="$::phr{'Insert'}" class="fmBtnSt">
&nbsp;&nbsp;<input type=submit name=action value="$::phr{'NextNew'}" class="fmBtnSt">
&nbsp;&nbsp;<input type=button value="$::phr{'Close'}" class="fmBtnSt" onClick="self.close();opener.document.location.reload(1)"></font></b></td></tr>
</table>
</form>
</center>
END
}
#=====================================================================================================
sub getdocURL {
    my($localdocA, $localdocB);
    if(exists $::o{'localdocURL'} and $::o{'localdocURL'} ne ''){
	$localdocA = "<a href=\"$::o{'localdocURL'}\" target=h class=\"transparent\">";
	$localdocB = "</a>";
    } else {
	$localdocA = "<a href=\"$::o{'imgdirurl'}/index.html\" target=h class=\"transparent\">";
	$localdocB = "</a>";
    }
    return ($localdocA, $localdocB);
}
#============================================================================================================

sub getClockScript {
    my ($bscript, $script) = ("", "");
    if( $::vm & 0x20)  { return ($bscript, $script);   }

    if($::o{'useJavaApplet'}) {
	;
    } else { 
	if($::o{'imageClock'}) {
	    $script =<<END;
var cis = new Array(14); var i;
for(i=0;i<14;i++){cis[i]=new Image();cis[i].src="$::o{'imgdirurl'}/z"+i+".gif";}
END

          if(not $::o{'hourformat'}) {	# 12 am/pm format
	      $bscript="onLoad=\"sdck(1,1)\"";
	  } else {
	      $bscript="onLoad=\"sdck(0,1)\"";
	  }
	} else { # do not use image clock
	    $script = " ";
	    if(not $::o{'hourformat'}) {	# 12 am/pm format
		$bscript = "onLoad=\"setClock12()\"";
	    } else {				# 24 am/pm format
		$bscript = "onLoad=\"setClock24()\"";
	    }
	}
    }

    return ($bscript, $script);
}
#============================================================================================================
sub getClockApplet {
    my $result = "";
    if( $::vm & 0x20)  { return "";}

    if($::o{'useJavaApplet'} == 1) {
	$result= "<applet code=dclock codebase=\"$::o{'imgdirurl'}\" width=70 height=24></applet><br>";
    }
    elsif($::o{'useJavaApplet'} == 2) {
	$result = "<applet code=BigTimeZ codebase=\"$::o{'imgdirurl'}\" width=90 height=24></applet><br>";
    } else {
	if($::o{'imageClock'}) {
	    my $lwidth;
	    if(not $::o{'hourformat'}) { $lwidth=12;} else {$lwidth=2;}
            if(!$::calinfo{'pnt'}) {
                $result =<<END;
<table border=0 cellspacing=0 cellpadding=0><tr><td width=18 height=24>
<img height=23 src="$::o{'imgdirurl'}/z10.gif" border=0 width=18 name=a></td><td width=18>
<img height=23 src="$::o{'imgdirurl'}/z10.gif" border=0 width=18 name=b></td><td width=4>
<img height=23 src="$::o{'imgdirurl'}/z13.gif" border=0 width=4 name=c></td><td width=18>
<img height=23 src="$::o{'imgdirurl'}/z10.gif" border=0 width=18 name=d></td><td width=18>
<img height=23 src="$::o{'imgdirurl'}/z10.gif" border=0 width=18 name=e></td><td width=$lwidth>
<img height=23 src="$::o{'imgdirurl'}/z10.gif" border=0 width=$lwidth name=f>
</td></tr></table>
END
    ;
            }
	} else {
	    # need to set onload function 
	    my $digits=6;
	    if($::o{'hourformat'} == 0) { $digits = 8;}
	    $result = "<form name=ck><span style=\"clear:both;\"><INPUT  class=\"fmEntryClock\" type=text NAME=dclock onFocus=\"javascript:document.ck.dclock.blur();\" VALUE=\" \" SIZE=$digits></span></form>";
	}
    }
    $result;
}

#============================================================================================================
sub getOwnerInfo {
    my ($cmd, $observeMG, $tclr) = (@_);
    my($view, $ls, $name, $homepage, $result);
    $homepage = $::calinfo{'homepage'};
    $name = $::calinfo{'dname'};
    $name = $::calinfo{'name'} unless $name;  $name = $::calinfo{'w'} unless $name; 
    $view=$::calinfo{'v'};$ls=$::calinfo{'ls'};
    $result = "";    

    if(! $::d{'megaCal'} or ! $observeMG) {
	if($homepage) {
	    $result .= "<a href=\"$homepage\"><b><span class=\"calendarTitle\"><font color=$tclr>$name</font></span></b></a>";
	} else {
	    $result .= "<b><span class=\"calendarTitle\"><font color=$tclr>$name</font></span></b>";
      }
    } else {
	my ($dndid,$dndop)=("","");
	if($::o{'dnd'} and ($::vm & 0x1000)==0){
	    $dndop ="ondragenter=\"dnden()\" ondragover=\"dndov()\" ondragleave=\"dndlv()\" ondrop=\"dnddp()\"" ;
	}
	$result="<table border=0 cellspacing=0 cellpadding=0><tr><td colspan=10><b><span class=\"calendarTitle\"><font color=$tclr>$::phr{'CombinedCalendar'}</font></span></b></td><tr>";
	my ($memb, @mlist, $sdate);
	@mlist = split(',',$::d{'megaCal'});
	if(defined $::calinfo{'sdate'}) { $sdate = $::calinfo{'sdate'};}
	else {
	    my ($month, $day,$year,$hour,$min);
	    $month= $::calinfo{'month'};   $day  = $::calinfo{'day'};    $year = $::calinfo{'year'}; 
	    $hour = $::calinfo{'hour'};    $min  = $::calinfo{'min'};
	    if(!defined $hour or $hour == 0) {  $hour = $::now{'hour'}; $min =$::now{'min'};}
	    $sdate="$month/$day/$year/$hour/$min";
	}
	my $i=0;
	for $memb (@mlist) {
	    $memb =~ s/[ ]+//g;
	    $result .= "<tr>" if $i == 0;
	    if($::o{'dnd'}) {$dndid="id=\"$memb:1/1/1901\"";}
	    $result .= <<END;
<td $dndid $dndop><font size=1 color=$tclr><span class="memberInTitle"><a href="$::o{'cginame'}?c=$cmd&ls=$ls&w=$memb&v=$view&d=$sdate$::vmg">$memb</a>&nbsp;</span></font></td>
END
;
	    $i++; if($i>=10){ $result .= "</tr>"; $i=0;}
	}
	$result .= "</tr>" if $i;
	$result .= "</table>";
    }
    $result;
}
#============================================================================================================
sub eventInCalendar {
    my ($etable, $event) = (@_);
    my (@keys) = ('kind', 'date', 'duration', 'occurs');   
    my( $href, $key, $matched, $tt, $desc);
    my ($ehr, $emn) =split(':', $event->{'start'});
    my $erepeat = 0; if(defined $event->{'repeat'}) { $erepeat = $event->{'repeat'}; }
    $matched = 0;
    $desc = $event->{'what'}; if(!$desc){$desc="";}  $desc =~ s/\s+//g;
    foreach $href (@$etable) {
        $tt = 1;
        foreach $key (@keys) {
            my $a = $href->{$key} || "";
            my $b = $event->{$key} || "";
            if($a ne $b) { $tt = 0; last; } 
        }
        if($tt and $href->{'kind'} != 4) { 
            my ($hr, $mn) = split(':', $href->{'start'});
            if( $hr+0 != $ehr+0 or $mn != $emn+0) { $tt = 0;}
        }
        if($tt and $href->{'occurs'} and $href->{'occurs'} ne 'OneTime') {
            my $repeat = 0; if(defined $href->{'repeat'}){ $repeat = $href->{'repeat'} + 0;}
            if( ( $repeat or $erepeat) and $repeat != $erepeat) { $tt = 0;}
        }
        if($tt) {
            my $what = $href->{'what'}; if(!$what) { $what="";} $what =~ s/\s+//g;
            if(uc($what) eq uc($desc)) { $matched = 1;}
        }# matched an existing entry
     }
    return $matched;
}

#============================================================================================================
# code moved from webcal.pl to here. 09072001
sub authenticate {
    my ($command, $scriptname) = (@_);
    $scriptname =~ s/[^\/|\\]+$//g; #cookie is set on the directory
    my ($smessage); my $scmd = $command;
    if($webcalConfig::r{'cookieAuth'} ) {
	my $magvalid = 0;
	my $magic;
	my $mcookie;
	my $whoami = readCookie('wcalusername');
	if($webcalConfig::r{'cookieAuth'} != 0) {
	    $mcookie = 'wcalpassword'; $magic = readCookie($mcookie);
	    $whoami = " " if not $whoami; $magic="" if not $magic;
	    ($magvalid, $smessage) = &webcalAuth::VerifyCryptedPassword($whoami,$magic);
	} 
	if($magvalid == 0 or $command =~ /clogin/ ) { # do login
	    &loadLangfile;
	    my ($uname, $pswd) = ("", ""); 
	    $uname = $::calinfo{'w'} if defined $::calinfo{'w'};
	    $uname = $whoami if defined $whoami and $whoami and $whoami ne " ";
	    $uname = $::calinfo{'uname'} if defined  $::calinfo{'uname'} and $::calinfo{'uname'};
	    $pswd =  $::calinfo{'pswd'} if defined $::calinfo{'pswd'};
	    if($::calinfo{'anonymous'} and  $::calinfo{'anonymous'} !~ /false/i ) {
		($whoami, $magic) = ('anonymous', ,'ok');
	    } else {
		($whoami, $magic) = cookieAuth($uname, $pswd, $command); # this is a loop!!!
	    }
	    if($whoami ne "") {
		my $rememberit = $::calinfo{'rememberit'};
		if(! defined $rememberit) { $rememberit = 0 ;}
		my $cookie= prepareCookie('wcalusername', $whoami, $scriptname, "", $rememberit);
		$cookie .= prepareCookie($mcookie, $magic, $scriptname, "", $rememberit);
		$::authCookie .= $cookie;
		if($::calinfo{'c'} eq 'option' or $::calinfo{'c'} eq 'navigation_table' or $::calinfo{'c'} eq 'remind') { # initial setup
		    $command = $::calinfo{'c'};
		} elsif($command ne 'clogina') {
		    $::calinfo{'c'} = 'get'; $command='get';
		}
	    } else { myexit(0);     }
	}
	$::d{'remote_user'} = $whoami;
    } else { 
	if(exists $ENV{'REMOTE_USER'} and $ENV{'REMOTE_USER'}) {
	    my $whoami = $ENV{'REMOTE_USER'};
	    my $cookie= prepareCookie('wcalusername', $whoami, $scriptname, "", 0);
	    $::authCookie .= $cookie;
	    $::d{'remote_user'}= $ENV{'REMOTE_USER'};
	} else {
	    my $whoami = readCookie('wcalusername');	
	    if($whoami) { $::d{'remote_user'} =$whoami;}
	    else { $::d{'remote_user'} ='anonymous';}
	}
    }
    
    #== 11/12/2003 create calendar automatically if does not exist
    if($webcalConfig::r{'cookieAuth'} and $scmd eq 'clogin' and  $::d{'remote_user'} ne 'anonymous') {
        my $acreate = &webcalAuth::autoCreateCalendar();
        my $cal = "$::o{'spooldir'}/$::d{'remote_user'}";
        if($acreate and  ! -d $cal) {
            &webcalAuth::GetUserInfo();
            if($acreate > 0 and $::calinfo{'w'} and $::calinfo{'email'}) {
                my $pswd = $::calinfo{'pswd'};
                if(!$pswd) {
                    my $magic = readCookie('wcalpassword'); 
                    my $dpswd = &webcalAuth::DecryptPassword($magic);
                    $pswd = $dpswd if $dpswd;
                }
                $::calinfo{'passwd'} = $pswd; $::calinfo{'rpasswd'} = $pswd;
                &loadLangfile;
                my ($rv, $rm) = setup(1);
                if(not $rv) { signup($rm); myexit(0);}
            } else {
                # post signup form
                &signup("Please fill in the signup form.");
                myexit(0);
            }
        }
    }
    #== 11/12/2003     

    {
	my $user = $::d{'remote_user'};
	if(! $user or ! -d "$::o{'spooldir'}/$user")  {
	    $user = $::calinfo{'w'};
	}
	if(getinfo($user, 'estyle')) { $::d{'estyle'} = 1;}
    }
    if($command eq 'clogina') {
	loadLangfile;
	&make_style_sheet(""); 
	popack();
	myexit(0);
    }
    $::calinfo{'forget'} = 1;
    return $command;
}

sub find_and_set_calendarName {
    my ($command, $scriptname) = (@_);
    $scriptname =~ s/[^\/]+$//g; #cookie is set on the directory

    if(! $::calinfo{'w'}) {
	if( $::d{'remote_user'} ne 'anonymous') {
	    $::calinfo{'w'} = $::d{'remote_user'};
	} elsif($command eq 'v' or (defined $::calinfo{'anonymous'} and (! $command or $command eq 'get')))  {
	    loadLangfile;
            $::calinfo{'selectCal'} = 1;
	    selectCalendars();
	    $command = $::calinfo{'c'};
	} else { $::calinfo{'w'} = 'anonymous';}
    } else {
	my $tmp = $::calinfo{'w'};
	if( $tmp=~ m/[,: ]/) {
	    $tmp =~ s/[,: ]+/,/g;
	    $tmp =~ s/,$//g;
	    my @mems= split(/,/,$tmp);
	    if(defined $::calinfo{'ww'}) {$::calinfo{'w'} = $::calinfo{'ww'};}
	    else { $::calinfo{'w'} = $mems[0];}
	    if(scalar @mems > 1) {
		$::calinfo{'mg'} = $tmp;
		$::calinfo{'mattendants'} = $tmp;
	    }
	}
    }
    if(!$::calinfo{'w'} and $webcalConfig::r{'cookieAuth'}) {
	loadLangfile;
	&make_style_sheet(""); 
	cookieLogin("","", "");
	myexit(0);
    }
    
    if($command eq 'v') { $command = 'get';}
    if(not $::d{'remote_user'} or $::d{'remote_user'} eq 'anonymous') { $::d{'validuser'} = 0;}
    return $command;
}

# the name nobody is used to logout webcal users.
# used when http password is used 
sub nobodySignoff {
    my ($command) = (@_);
    if($::d{'remote_user'} eq 'nobody' and  $webcalConfig::r{'cookieAuth'} ==0) {
	loadLangfile;
	if($command eq 'signoff') {
	    print "Content-type: text/html\n\n";
	    print "<HTML>\n";
	    print "<HEAD>";
	    print "$::banner{'headseg'}\n";
	    print "<TITLE>webcal message</TITLE>\n";
	    print "$webcalConfig::r{'txtcss'}\n";
	    print "</HEAD>\n";
	    print "<center><br><br>";
	    print "
 <body bgcolor=\"$webcalConfig::r{'backgroundColor'}\" TEXT=\"$webcalConfig::r{'textColor'}\" LINK=\"$webcalConfig::r{'linkColor'}\">
 $::banner{'prolog'}\n
 <center>
 <br><br>
 <h1> $::phr{'ThankYou4Using'} $webcalConfig::r{'cgiInfo'}</h1>
 <br><br>
 <Form action=\"$::o{'cginame'}\" method=POST>$::vmp
 <input type=\"hidden\" name=\"c\" value=\"plogin\">
 <table border=2 cellpadding=2 cellspacing=4 width=60%>
 <tr><td align=\"center\" noWrap><br><b>
 $::phr{'accessAnotherCal'}
 <input type=\"submit\" name=\"action\" value=\"$::phr{'login'}\">
 </b></td></tr>
 </table></form>
 </center>
 $::banner{'postscript'}\n
 </body>
 </HTML>";
	    myexit(0);
	} else {
	    if($::calinfo{'c'} eq 'plogin') {
		print "Status: 401 auth req\n";
		print "WWW-authenticate: Basic realm=\"Calendar\"\n";
		print "Content-type: text/plain\n\n";
		print "$::phr{'access_denied'} ";
		myexit(0);
	    }
	}
    }
}
sub getSetCurrentDateTime {
    # get current date and time
    if($::calinfo{'tzone'}) { $ENV{TZ} = "$::calinfo{'tzone'}";}
    else { delete $ENV{TZ};} #does not  work ???
    # was $ENV{TZ}="localtime"; Unfortunately some systems does not
    # have localtime, noticablly Redhat 5.2 ...
    #
    # localtime sets the tzname the first time it is called.
    # subsequent calls to localtime does not seem to care about
    # the TZ environment anymore. I.e, it remembers the time zone.
    
    if($::calinfo{'toffset'}) {
      my ($vtime,$tmp);
      $tmp = time; $vtime = $tmp + $::calinfo{'toffset'};
      my (@loctime) = localtime($vtime);
      $::now{'year'} =  (@loctime)[5] + 1900,
      $::now{'month'} =  (@loctime)[4] + 0;
      $::now{'day'} =  (@loctime)[3] + 0;
      $::now{'hour'} =  (@loctime)[2] + 0;
      $::now{'min'} =  (@loctime)[1] + 0;
      $::now{'sec'} =  (@loctime)[0] + 0;
      #$::now{'offset'} = 0; # current offset from localtime to UTC, in seconds
    } elsif( $ =~ m/MSWin|NT/i ) {
      my (@loctime) = localtime(time);
      $::now{'year'} =  (@loctime)[5] + 1900,
      $::now{'month'} =  (@loctime)[4] + 0;
      $::now{'day'} =  (@loctime)[3] + 0;
      $::now{'hour'} =  (@loctime)[2] + 0;
      $::now{'min'} =  (@loctime)[1] + 0;
      $::now{'sec'} =  (@loctime)[0] + 0;
      #$::now{'offset'} = 0; # current offset from localtime to UTC, in seconds
    } else {
      my ($locs, $gmts);
      my $datestr= `date "+%S %M %H %d %m %Y"`;
      my @loctime=split(' ', $datestr);
      $loctime[4]  -= 1;
      $::now{'year'} =  (@loctime)[5] + 0,
      $::now{'month'} =  (@loctime)[4] + 0;
      $::now{'day'} =  (@loctime)[3] + 0;
      $::now{'hour'} =  (@loctime)[2] + 0;
      $::now{'min'} =  (@loctime)[1] + 0;
      $::now{'sec'} =  (@loctime)[0] + 0;
      #$locs = &webcalSupport::timeLocal(@loctime);
      #$ENV{TZ} = 'UTC';
      #$datestr= `date "+%S %M %H %d %m %Y"`;
      #@loctime=split(' ', $datestr);
      #$loctime[4] -= 1;
      #$gmts = timeLocal(@loctime);
      #$::now{'offset'} = ($locs - $gmts); # current offset from localtime to UTC, in seconds
    }
    delete $ENV{TZ};

    if(! $::calinfo{'year'}) {
	$::calinfo{'year'} = $::now{'year'};
	$::calinfo{'day'} = $::now{'day'};
	$::calinfo{'month'} = $::now{'month'};
    }
    if(! defined $::calinfo{'hour'}) {
	$::calinfo{'hour'} = $::now{'hour'};
	$::calinfo{'min'} = $::now{'min'};
    }
    if(!$::calinfo{'d'}) { $::calinfo{'d'} = "$::now{'month'}/$::now{'day'}/$::now{'year'}";}
}

sub setPersonalDisplayParams {
    if(exists $::calinfo{'dformat'}) {$::o{'dateformat'} = $::calinfo{'dformat'};}
    if(exists $::calinfo{'dformat2'}) {$::o{'dateformat2'} = $::calinfo{'dformat2'};}
    if(exists $::calinfo{'tformat'}) {$::o{'hourformat'} = $::calinfo{'tformat'};}
    if(exists $::calinfo{'weekstart'}) {$::o{'weekstart'} = $::calinfo{'weekstart'};}
    if(exists $::calinfo{'eweekend'}) {$::o{'excludeWeekend'} = $::calinfo{'eweekend'};}
    if(exists $::calinfo{'language'}) {$::o{'language'} = $::calinfo{'language'};}
    if(exists $::calinfo{'tabs'}) {$::o{'tabs'} = $::calinfo{'tabs'};}
    if($::d{'validuser'}<2){$::o{'tabs'}="get,task";}
    if($::o{'weekstart'} or $::o{'excludeWeekend'}) { $::o{'weekstart'} = 1;}
}

sub convertToWcalDatesAll {
    my $name;
    for $name ('sdate','bdate','searchFrom','searchTo', 'fdate', 'tdate', 'DeleteEventsBeforeDate', 'enddate') {
	if($::calinfo{$name}) {
	    my $dateformat ="";
	    if($::calinfo{'dateformat_in'}){$dateformat = $::o{'dateformat'}; $::o{'dateformat'} = $::calinfo{'dateformat_in'};}
	    $::calinfo{$name} = &to_wcal_date($::calinfo{$name});
	    if($dateformat) { $::o{'dateformat'} = $dateformat;}
	}
    }
}

#============================================================================================================
sub note_tableofcontents {
    my ($w, $rlevel, $cmd, $sec) = (@_);
    my( $dir, $ret, $name, $tcnt, $cnt, $clrcnt, $stopic, @searchwords, $ok, %hash, $tmp, @general, @ary, $aref, $date);
    my (@bgclrs)=($webcalConfig::r{'rowColors'}->[1],$webcalConfig::r{'rowColors'}->[3]);
    $ret = ""; $tcnt=$cnt=0; %hash = (); @ary=();
    $dir = "$::o{'spooldir'}/$w/notes";
    $stopic=""; @searchwords=();
    if($cmd eq 's') { $stopic = $::calinfo{'stopic'};}
    if($stopic) { @searchwords = &buildMExpr($stopic);}
    $date=$::calinfo{'d'};
    my $DIR8= gensym;
    if(opendir($DIR8, "$dir")) {
	my @allfiles = sort {$b cmp $a} grep(/\-t$/, readdir($DIR8));  closedir($DIR8); 
	foreach $name (@allfiles) {
	    if( $name =~ /\-t$/) {
		my $t= "";
		my $fhzf = gensym;
		if(open($fhzf, "<$dir/$name")) { 
		    $t = <$fhzf>; close $fhzf;
		    $tcnt++;
		    $name =~ s/\-t$//g;
		    if($t) {
			my ($dstr, $tstr, $m, $d, $y, $hr, $mn, @ltime, $pit, $dit, $eit, $purl, $tt, $the_cat);
			my $catf = "$dir/${name}-s"; $the_cat="";
			my $fhwf = gensym;
			if( -f "$catf" and open($fhwf, "<$catf")) {
			    $the_cat = <$fhwf>; close $fhwf; $the_cat =~ s/^\s+//g; $the_cat =~ s/\s+$//g;
			}
			my $cf = "$dir/${name}-c";
			my $content= read_file_content($cf);
			$ok=1;
			if($stopic) {
			    $ok = 0; if(matchMExpr(\@searchwords, $t) or matchMExpr(\@searchwords, $content) ) {$ok = 8;}
			} elsif($cmd eq 'v') {
			    if($sec eq $the_cat) { $ok = 4;}
			}
			if($ok) {
			    $content = wrapDiaryLines($content, 1);
			    $content = annotate(\@searchwords, $content) if $ok==8;
			    my $tip="";
			    if($ok == 1) {
				my $tpid= addtip($content);
				$tip = "onMouseOver=\"showtip(event,\'$tpid\');\" onMouseout=\"hidetip(\'$tpid\');\"";
			    }
			    @ltime=localtime($name);
			    $y= 1900 + $ltime[5]; $m=$ltime[4];$d=$ltime[3]; $hr=$ltime[2];$mn=$ltime[1];
			    $dstr = mdy_string($m, $d, $y);	$tstr =hm_string($hr,$mn);
			    if($rlevel > 1 and not $::calinfo{'pnt'}) {
				$eit="<a href=\"$::o{'cginame'}?c=notes&ntc=e&d=$date&nid=$name&w=$w$::vmg\"><b><span class=\"noteEdit\">$::phr{'Edit'}</span></b></a>";
				$dit="<font color=#ff0000><span class=\"noteDelete\">&nbsp;&nbsp;&nbsp;&nbsp;$::phr{'Delete'}</span></font>&nbsp;<input type=checkbox name=\"nid$cnt\" value=\"$name\" class=\"fmRadioS\">";
			    } else { $eit=$dit="&nbsp;";}
			    $purl = "$::o{'cginame'}?c=notes&ntc=p&nid=$name&w=$w$::vmg";
			    $pit="<a href=\"javascript:postnote(\'$purl\',\'n_$cnt\')\"><img src=\"$::o{'imgdirurl'}/pin.gif\" width=9 height=14 border=0></a>";

			    my $tooltipA="<a href=\"javascript:postnote(\'$purl\',\'n_$cnt\')\" $tip>";
			    my $tooltipB = "</a>";
			    my ($bg, $line)=("","");
			    if($ok > 1) { $bg = " background=\"$::o{'imgdirurl'}/nbg.gif\"";}
			    if($::calinfo{'pnt'}) {
				$line="</tr><tr><td height=1></td><td colspan=6 height=1><img src=\"$::o{'imgdirurl'}/b1.gif\" height=1 width=\"100%\"><br><br></td>";
			    } 
			    $tmp = "<td width=20 align=right class=\"notePin\"><font size=1>$pit&nbsp;</font></td><td$bg nowrap class=\"noteTitle\" _zclr_><font size=1><span class=\"noteDatetime\">$dstr $tstr&nbsp;&nbsp;&nbsp;</span></font></td>
<td$bg class=\"noteTitle\" colspan=2 _zclr_>$tooltipA<font color=#000000><b><span class=\"noteTitle\">$t</span></b></font>$tooltipB</td>
<td$bg class=\"noteTitle\" _zclr_><font size=1>$eit</font></td><td class=\"noteTitle\" $bg _zclr_><font size=1>$dit</font></td><td class=\"noteTitle\" width=4 $bg _zclr_><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=4 height=1 border=0></td>";
			    if($ok > 1) {
				$tmp .= <<END;
</tr><tr><td><br></td><td colspan=6>
  <table border=0 cellspacing=0 cellpadding=0 width="100%" bgcolor="#ffffff" class="noteContentHolder">
   <tr><td bgcolor="#333333" width="100%" class="noteContentHolderTd">
      <table width="100%" cellpadding=6 cellspacing=1 border=0 bgcolor="#333333" class="noteContentTbl">
      <tr><td bgcolor="#f8e098" class="noteContentTd"><span class="noteContent">$content</span></td></tr></table>
     </td>
    </tr>
  </table>
<br></td>$line
END
    ;
			    } else {
				$tmp .= <<END;
</tr>
<tr><td height=1><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=1 border=0></td><td height=1 colspan=6 bgcolor="#999999><img" src="$::o{'imgdirurl'}/spacer.gif" width=1 height=1 border=0></td>
END
    ;
			    }

			    my $done=0;
			    if($the_cat) {
				if(! exists $hash{$the_cat}) { $hash{$the_cat} = [];};
				$aref = $hash{$the_cat};
				push @$aref, $tmp;
				$done =1;
			    }
			    if(!$done) { push @ary, $tmp;}
			    $cnt++;
			}
		    }
		}
	    }
	}
	if($cmd eq 's') { $ret .= "<tr><td colspan=2><font size=+1 color=#ff0000><b><span class=\"miscTitle\">$::phr{'Search_Results'}</span></b></font></td></tr>\n"; }
	my ($ref, $key, $j, $aref); $j = 0;
	if(0+@ary > 0 and (!$::calinfo{'pnt'} or not $sec)) {
	    my $pnt=<<END;
<font size=1><a href="$::o{'cginame'}?c=notes&ntc=v&pnt=1&d=$date&w=$w$::vmg" target=pnt><span class="notePrint">$::phr{'Print'}</span></a>&nbsp; &nbsp; &nbsp; &nbsp;</font>
END
    ;
	    if($cmd eq 'v' and $sec eq "") {
		$ret .= "<tr><td align=right class=\"noteCatTd\"><img src=\"$::o{'imgdirurl'}/fo.gif\" width=14 height=11>&nbsp;</td><td colspan=6 align=right nowrap class=\"noteCatTd\">$pnt</td></tr>\n";
	    } else { 
		my ($abgn, $aend);
		$abgn= "<a href=\"$::o{'cginame'}?c=notes&ntc=v&d=$date&w=$w$::vmg\">";
		$aend = "</a>";
		$ret .= "<tr><td align=right class=\"noteCatTd\">$abgn<img src=\"$::o{'imgdirurl'}/fc.gif\" width=14 height=11 border=0>$aend&nbsp;</td><td colspan=6 align=right nowrap class=\"noteCatTd\">$pnt</td></tr>\n";

	    }
	    foreach $ref (@ary) {
		my $bgclr=$bgclrs[$j]; $j = ($j == 0? 1: 0);
		$bgclr = "bgcolor=$bgclr"; 
		$ref =~ s/_zclr_/$bgclr/g;
		$ret .= "<tr>$ref</tr>\n";
	    }
	}
    for $key (sort {uc($a) cmp uc($b)} keys %hash) {
	if(! $::calinfo{'pnt'} or $sec eq $key) {
	    my ($abgn, $aend) =("",""); my ($icon, $ekey);
	    $ekey = urlencode($key);
	    my $pnt=<<END;
<font size=1><a href="$::o{'cginame'}?c=notes&ntc=v&pnt=1&d=$date&w=$w&sec=$ekey$::vmg" target=pnt><span class="notePrint">$::phr{'Print'}</span></a>&nbsp; &nbsp; &nbsp; &nbsp;</font>
END
    ;
	    if($cmd eq 'v' and $sec eq $key) {
		$icon = "fo.gif";
	    } else {
		$abgn= "<a href=\"$::o{'cginame'}?c=notes&ntc=v&d=$date&w=$w&sec=$ekey$::vmg\">"; $aend = "</a>";	 
		$icon = "fc.gif";   
	    }
	    $ret .= "<tr><td colspan=7 class=\"noteFiller\"><font size=1><br></font></td></tr>
<tr><td align=right class=\"noteCatTd\">$abgn<img src=\"$::o{'imgdirurl'}/$icon\" width=14 height=11 border=0>$aend&nbsp;</td><td colspan=4 align=left class=\"noteCatTd\"> $abgn<font color=#0000cc><b><span class=\"noteCat\">$key</span></b></font>$aend</td><td colspan=2 align=right nowrap class=\"noteCatTd\">$pnt</td></tr>\n";
	    $aref = $hash{$key};
	    foreach $ref (@$aref) {
		my $bgclr=$bgclrs[$j]; $j = ($j == 0? 1: 0);
		$bgclr = "bgcolor=$bgclr"; 
		$ref =~ s/_zclr_/$bgclr/g;
		$ret .= "<tr>$ref</tr>\n";
	    }
	}
      }
    }
    if($stopic and $cnt == 0) { $ret = "<tr><td colspan=6><b>No match found.</b></td></tr>";}
    return ($tcnt, $cnt,$ret);
}
#===============================================================================================================
sub substImages {
    my ($in) = (@_);
    my $irepository = "$::o{'imgdirurl'}/$::o{'uploadsubdir'}";
    $in =~ s/\\?\^o\^\/([^\s]+?)(size=)(\d+)x(\d+)([^\s]*)\.(gif|jpg|png|jpeg|bmp)/ <img src=\"$irepository\/$1$2$3x$4$5\.$6\" border=0 align=left valign=top width=\"$3\" height=\"$4\"> /ig;
    $in=~ s/\\?\^o\^\/([^\s]+?)\.(gif|jpg|png|jpeg|bmp)/ <img src=\"$irepository\/$1\.$2\" border=0 align=left valign=top> /ig;
    $in=~ s/(^|[^"'])(http:)(\/\/[^\s]+)(size=)(\d+)x(\d+)([^\s]*)\.(gif|jpg|png|jpeg|bmp)/$1 <img src=\"zttp:$3$4$5x$6$7\.$8\" border=0 align=left valign=top width=\"$5\" height=\"$6\"> /ig; #"'
    $in=~ s/(^|[^"'])(http:\/\/[^\s]+?)\.(gif|jpg|png|jpeg|bmp)/$1 <img src=\"$2\.$3\" border=0 align=left valign=top> /ig; #"'
    $in =~ s/(zttp|ptth):/http:/ig;
    $in =~ s/\\?\^o\^\/([^\s]+?)(size=)(\d+)x(\d+)([^\s]*)\.(swf)/ <embed src=\"$irepository\/$1$2$3x$4$5\.$6\" type=\"application\/x-shockwave-flash\" width=\"$3\" height=\"$4\"> /ig; #"'
    $in =~ s/\\?\^o\^\/([^\s]+?)\.(swf)/ <embed src=\"$irepository\/$1\.$2\" type=\"application\/x-shockwave-flash\"> /ig; #"'
    $in =~ s/\&amp;\#/\&\#/g;
    $in =~ s/\n[ \t\r]*\n/<br clear="all">/g;
    return $in;
}
#===============================================================================================================
sub readNote {
    my ($who, $nid) = (@_);
    my ($dir, $ft, $fc, $fs, $title, $content, $cat); $title=$content=$cat = "";
    $dir = "$::o{'spooldir'}/$who/notes";
    $ft = "$dir/${nid}-t";  $fc = "$dir/${nid}-c"; $fs = "$dir/${nid}-s"; 
    if( -d "$dir" and -f "$ft" and -f "$fc") {
	local ($/) = (undef);
	my $fzf = gensym;
	if(open($fzf, "<$ft")) { $title = <$fzf>; close $fzf;} else { $title = "No title";}
	if(open($fzf, "<$fc")) { $content =<$fzf>; close $fzf;}else{ $content=" ";}
	if( -f "$fs" and open($fzf, "<$fs")) { $cat = <$fzf>; close $fzf;}
        #
    }
    ($title, $content, $cat);
}

sub notes {
  my($cmd,$who, $month, $day, $year, $sdate, $notes, $file, $view, $tmp, $ls, $rwho, $rlevel, $ackmsg, $ncat);
  $who = $::calinfo{'w'}; $rwho = $who;
  if( $::d{'ispublic'} == 0 and $::d{'remote_user'} eq ""){$sdate = $::calinfo{'d'};  requireLogin('diary', $sdate, "");}

  # readers/editors of the calendar can read the notes
  $rlevel = 0;
  if( $::d{'ispublic'} == 0) {
      my $tmp; if($::calinfo{'pnotes'}) {$tmp= $::calinfo{'pnotes'};} else { $tmp = 0;}
      if($::d{'remote_user'} eq $who ) { $rlevel = 10;}
      elsif( $tmp > 0 and isre($::d{'remote_user'}, $who, 'editors') ) { $rlevel = 10;}
      elsif( $tmp > 2 or ($tmp > 1 and isre($::d{'remote_user'}, $who, 'readers')) ) { $rlevel = 1;}
  } else { $rlevel = 10;}
  if($rlevel == 0) { calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who)."); }
  $cmd = $::calinfo{'ntc'};  if(! $cmd) { $cmd = "l";} if($cmd eq 's') { $::d{'SATbs'}=1;}
  if( $rlevel ) {
    $view = $::calinfo{'v'}; $ls = $::calinfo{'ls'};
    $sdate = $::calinfo{'d'};

    #&make_style_sheet();   

    if($cmd eq 'd') { # delete checked entries, 
	if($rlevel <= 1) { calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who)."); }
	my ($total, $i, $ft, $fc, $fs, $name, @all, $cnt, $dir);
	@all=(); $total = $::calinfo{'nidcnt'}; $cnt = 0;
	for($i=0;$i<$total; $i++) {$name="nid$i"; if($::calinfo{$name}) { push @all, $::calinfo{$name};}}
	$dir = "$::o{'spooldir'}/$who/notes";	
	foreach $name (@all) {
	    $ft = "$name" . "-t"; $fc = "$name" . "-c";  $fs = "$name" . "-s"; 
            $ft = untaintname($ft, ""); $fc = untaintname($fc, "");   $fs = untaintname($fs, "");
	    if( -f "$dir/$ft") { unlink "$dir/$ft"; $cnt++;}
	    if( -f "$dir/$fc") { unlink "$dir/$fc";}	    
	    if( -f "$dir/$fs") { unlink "$dir/$fs";}	    
	}
	acknowledge($who,$view,$ls,$sdate, "<font color=#ff0000><b>$cnt</b> entries has been deleted", "notes");
    }  elsif($cmd eq 'e' or $cmd eq 'a') { # edit, done in a popup 
	if($rlevel <= 1) { calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who)."); }
        my ($body, $clockscript) = &getClockScript();
	&headers($::phr{'Note'}, $clockscript, undef,1,1, $body);
	my $headerForm=&newHeader('notes', 1);
	print $headerForm;
	my( $title, $content, $cat, $rid, $upload)=("", "","", "", "");
	if($::o{'allowImageUpload'}) {
	    my $iurl="$::o{'cgiupload'}?c=ui&w=$who";
	    $upload = "<a href=\"Javascript:openpopup(\'$iurl\','uls',500,400)\"><font size=1 color=#0000cc><span class=\"iupload\">$::phr{'IUpload'}</span></font></a><br><br>";
	}
	my $repos = "$::o{'imgdir'}/$::o{'uploadsubdir'}";
	my @list= listImgDirContents($repos, 1);
	if (scalar @list) {
	    my $surl="$::o{'cginame'}?c=simage&imgoffset=0&w=$who&the_form=webcalnotes&the_elt=ncontent";
	    $upload .= "<a href=\"Javascript:openpopup(\'$surl\','imgs',500,600)\" style=\"color:green;background-color:#cccc00\"><font size=1><span class=\"iselect\">$::phr{'UsableImgs'}</span></font></a><br><br>";
	}
	my($nid, $sbtn,$ncmd); $ncmd="add";
	$sbtn=$::phr{'Insert'};
	if($cmd eq 'e') {
	    $nid = $::calinfo{'nid'};
	    if($nid) {
		($title, $content, $cat) = readNote($who, $nid);
		if($title eq "No title") {$title="";}
		$rid="<input type=hidden name=enid value=$nid>";
		$sbtn=$::phr{'Modify'};
		$ncmd="edd";
	    }
	}
	print "<center>";
	my $catlist=build_ncatlist($who,"");
	print <<END;
<br>
<Form name=webcalnotes action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value="notes">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$sdate">
<input type=hidden name=w value="$who">
<input type=hidden name=ntc value="$ncmd">
$rid
<table border=0 cellspacing=0 cellpadding=0>
<tr><td align=right><b><span class="fmLabel">$::phr{'Category'}:</span></b></td><td><input type=text  class="fmEntry" name=ncat value="$cat" size=20 maxlength=256>&nbsp;&nbsp;$catlist</td></tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'Title'}:</span></b></td><td><input type=text class="fmEntry" name=ntitle value="$title" size=60 maxlength=256></td></tr>
<tr><td><font size=1>&nbsp;</font></td><td><font size=1><span class="fmLabelS">Supported HTML tags: &lt;b&gt;, &lt;i&gt;, &lt;u&gt;, &lt;br&gt;, &lt;font&gt;, &lt;p&gt; and &lt;pre&gt;</span></font></td></tr>
<tr><td align=right>$upload <b><span class="fmLabel">$::phr{'Notes'}:</span></b></td><td><textarea name=ncontent rows=8 cols=60 wrap=virtual class="fmText">$content</textarea></td></tr>
<tr><td>&nbsp;</td></tr>
<tr><td colspan=2 align=center><b><input type=submit value="$sbtn" class="fmBtnSt">
&nbsp;&nbsp;&nbsp;&nbsp;<input type=button value="$::phr{'GoBack'}" class="fmBtnSt" onclick="history.go(-1)"></b></td></tr>
</table>
</Form>	
END
	&trailer(0,0);
	myexit(0);
    } elsif($cmd eq 'add' or $cmd eq 'edd') { # doadd or doedit
	if($rlevel <= 1) { calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who)."); }
	my ($dir, $tim, $nameT, $nameC, $nameS, $tmp, $err); $err=0;
	$who = untaintname($who); $dir = "$::o{'spooldir'}/$who/notes";	
	if( !$::calinfo{'ntitle'} and ! $::calinfo{'ncontent'}) {
	    if($cmd eq 'edd') {
		if($::calinfo{'enid'}) {
		    $tim = $::calinfo{'enid'};
		    $nameT = "$tim" . "-t"; $nameC= "$tim" . "-c";   $nameS= "$tim" . "-s";  
                    $nameT = untaintname($nameT, ""); $nameC = untaintname($nameC, ""); $nameS = untaintname($nameS, "");
		    unlink "$dir/$nameT" if -f "$dir/$nameT";
		    unlink "$dir/$nameC" if -f "$dir/$nameC";
		    unlink "$dir/$nameS" if -f "$dir/$nameS";
		    acknowledge($who,$view,$ls,$sdate, "Empty note deleted", "notes");		    
		    myexit(0);
		} 
	    }
	    calerror("Empty Content",1);
	} else {
	    if( ! -d "$dir") { mkdir("$dir",0711) or $err++;}
	    if($::calinfo{'enid'}) { $tim = $::calinfo{'enid'};} else {$tim=time;}
	    $nameT = "$tim" . "-t"; $nameC= "$tim" . "-c";   $nameT = untaintname($nameT, "");  $nameC = untaintname($nameC, "");
	    $tmp = $::calinfo{'ntitle'}; if (!$tmp) {$tmp ="No title";}
	    my $fhz = gensym;
	    if(open($fhz, ">$dir/$nameT")) { print $fhz $tmp; close($fhz);} else {$err++;}
	    $tmp = $::calinfo{'ncontent'};
	    if(open($fhz, ">$dir/$nameC")) { print $fhz $tmp; close($fhz);} else {$err++;}
	    if($::calinfo{'ncat'}) {
		$nameS= "$tim" . "-s"; $nameS = untaintname($nameS, ""); $tmp = $::calinfo{'ncat'}; $tmp =~ s/\n/ /g;
		if(open($fhz, ">$dir/$nameS")) { print $fhz $tmp; close($fhz);} 
		$tmp=~ s/^\s+|\s+$//g; $tmp =~ s/\s+/ /g; update_catlist($who, $tmp)
	    }
	    if($err) { calerror("Internal Error: Cannot create new files",1); }
	    else { acknowledge($who,$view,$ls,$sdate, $::phr{'UpdatedOK'}, "notes");}
	}
	myexit(0);
    } elsif($cmd eq 'p') { # post it
	my ($title, $content, $cat, $nid, $dir, $ft, $fc, $err, $msg, $pnt, $zs, $print, $ps, $onload);
	$nid = $::calinfo{'nid'}; 
	$err=0; $msg="";
	if($nid) {
	    ($title, $content, $cat) = readNote($who, $nid);
	    $content = wrapDiaryLines($content, 1);
	    $pnt = $::calinfo{'pnt'};
	    if($cat) { $cat = "<font color=#ff0000 size=1><span class=\"noteCat\">$cat</span></font>";} else {$cat = "";}
	    my $url;
	    if(!$pnt){$url="$::o{'cginame'}?c=notes&ntc=p&nid=$nid&w=$who&pnt=1$::vmg";$ps=$::phr{'Print'};$onload="onload=\"document.bgColor='#ffff00'\"";}
	    else{$url="";$ps=""; $onload="onload=\"window.print()\"";}
	    $print =<<END;
<table width="100%" bgcolor="#ffff00"><tr><td>$cat</td><td align=right><font color="#0000ff" size=1>
<a href="$url" target=_pn><span class="notePrint">$ps</span></a> &nbsp;&nbsp;
&nbsp;&nbsp; <a href="javascript:self.close()"><span class="notePrint">$::phr{'Close'}</span></a></font></td></tr></table>
END
    ;
	    if($title or $content) {
		print headers("webcal note", "", 120, "", 0, $onload);
		print "$print";
		print "<center><table cellpadding=8 width=\"100%\" bgcolor=#ffff00><tr><td bgcolor=#ffff00><b><span class=\"noteTitle\">$title</span></b></td></tr><tr><td><span class=\"noteContent\">$content</span></td></tr>";
		if(!$pnt) {
		    print "<tr><td align=center><FORM><font color=#ff0000><b><input type=button class=\"fmBtn\" value=\"  $::phr{'Close'}  \" onClick=\"javascript:self.close()\"></b></font></Form></td></tr>";
		}
		print "</table></center></body></html>";
	    } else { $msg = "The specified note is no longer available."; $err=1;}
	} else { $msg = "Note ID is unspecified"; $err=1;}
	if($err) {
	    print headers("webcal note", "", 0, "", 0, "onload='setTimeout(\"self.close();\",5000)\'");
	    print "<center><br><br><font color=#ff0000><b><span class=\"msg\">$msg</span></b></font><br><br>";
	    print "<table cellpadding=8 bgcolor=#ffff00 width=\"100%\"><tr><td><b><span class=\"noteTitle\">$title</span></b></td></tr>
<tr><td><span class=\"noteContent\">$content</span></td></tr>";
	    print "<tr><td><br></td><tr><td align=center><FORM><input type=button class=\"fmBtn\" value=\"$::phr{'Close'}\" onClick=\"javascript:self.close()\"></Form></td></tr></table>";	    
	    print "</center></body></html>";
	}
	myexit(0);
    }

    #
    if($cmd eq 'l' or $cmd eq 's' or $cmd eq 'v') { # list all notes,
	my ($tcnt,$cnt, $allnotes, $submit, $search, $section);
	($month, $day, $year) = split(/\//, $sdate);
	$section = ""; if($::calinfo{'sec'}) { $section=$::calinfo{'sec'};}
	($tcnt,$cnt, $allnotes)= note_tableofcontents($who, $rlevel, $cmd, $section);
	if($cnt > 0 and $rlevel > 1 and not $::calinfo{'pnt'}) {
	    $submit = "<br><table width=\"80%\" cellspacing=2><tr><td align=right><font color=#ff0000><b><a href=\"javascript:document.webcalnotes.submit()\"><font color=#0000ff><b><span class=\"fmLabel\">$::phr{'DeleteChecked'}</span></b></font></a><input type=hidden name=nidcnt value=$cnt><input type=hidden name=w value=\"$who\"></td><tr></table>";
	} else { $submit = "";}
	if($tcnt > 0) {
	    my $stopic ="";   if($::calinfo{'stopic'}) {$stopic = $::calinfo{'stopic'};}
	    if(! $::calinfo{'pnt'}) {
		$search = <<END;
<Form name=searchnotes action="$::o{'cginame'}" method=POST  class="searchform">
<input type=hidden name=c value="notes">
<input type=hidden name=ntc value="s">
<table width="100%" border=0 cellspacing=0 cellpadding=0><tr><td align=right>
<table border=0 class="noteSearch"><tr><td nowrap><font size=1><span class="fmLabelSa"><br>$::phr{'Search'}:<br></span></font>
<font size=1><input type=text name=stopic size=8 maxlength=128 value="$stopic" class="fmEntrySa"></font>
<font size=1><input type=submit value="$::phr{'Go'}" class="fmBtnStSa"></font></td></tr></table>
</td></tr></table>
</Form>
END
    ;
	    } else { $search = "";}
	} else {$search = "Use the link on the navigation bar to add a note.";}

	# create form

    if(!$::calinfo{'pnt'}) {
        my ($body, $clockscript) = &getClockScript();
	&headers($::phr{'Notes'}, $clockscript,undef,1,1, $body);
	my $headerForm=&newHeader('notes', 1);
	print $headerForm;
    } else {
	&headers($::phr{'Notes'}, "" ,undef,1,1, "onLoad=\"window.print()\"");
    }
	print "<center>";
	if(($::d{'authResult'} | $::d{'ispublic'}) < 4 or $::d{'validuser'} == 0) {
	    print "<font color=#999900><b><span class=\"authWarn\">$::phr{'AuthRequired'}!</span></b></font>";
	} 
	my $adjwidth = $::o{'tw'} - 4;
	print <<END;
<table border=0 width="$adjwidth%" cellspacing=0 cellpadding=0><tr><td valign=top width="85%">
<Form name=webcalnotes action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name=c value="notes">
<input type=hidden name=v value=$view>
<input type=hidden name=ls value=$ls>
<input type=hidden name=d value="$sdate">
<input type=hidden name=w value="$who">
<input type=hidden name=ntc value="d">
<table width="100%" border=0 cellspacing=0 cellpadding=0 class="note">
<br>
$allnotes
</table>
$submit
</Form>
</td><td valign=top align=right width="15%">
$search
</td></tr></table>
END
	print "</center>";
	&trailer(0,1);
    }
  } else { calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who) <br> $::phr{'errorPerm'}");}
}
#============================================================================================================
# when to use a pull down menu in the masterhead?
#  1) if the 'ulist' option is set for 'remote_user', honor it
#     in this case, 'remote_user's short list is used if defined
#  2) 'ulist' is undefined for 'remote_user', honor the ulist option of 'who' if defined
#
#  3) otherwise, use the global listAllCals option
#
sub use_pulldown_nemu {
    my $ruser = $::d{'remote_user'};
    my $who = $::calinfo{'w'};
    my $retv = 0;
    if($::calinfo{'ulist'}) {
        if( $::calinfo{'ulist'} > 2) {return 1;} #override
        elsif($::calinfo{'ulist'} < 0) {return 0;} #override
    }

    if($ruser eq $who or ! -f "$::o{'spooldir'}/$ruser/info") {
	$retv = $::calinfo{'ulist'} if defined $::calinfo{'ulist'};
    } else { $retv = getinfo($ruser, 'ulist');}
    if($retv) { $retv = 2 if $retv > 2;  $retv = 1 if $retv < 0; return $retv - 1;}  # retv takes 2 or 1, for pulldown menu and text_entry
    if($::o{'listAllCals'} > 0) { return(1);}
    return 0;
}
#============================================================================================================
sub getMyFaviorateLinks {
    my ($user)=(@_);
    my ($ans,  $links, $cal, $ref);
    $user = untaintname($user,$::phr{'Invalidusername'});
    $cal = "$::o{'spooldir'}/$user";
    if( ! -d $cal ) { return ("", "");}
    $ans = $links  = "";
    if( -f "$cal/links") {
        my ($k, $v);
        %::flinks = ();
        doReadFile("$cal/links");
        foreach $k (sort {uc($a) cmp uc($b)} keys %::flinks) {
            $v = $::flinks{$k};
            $links .= "<font size=1><a href=\"$v\" class=\"favoriateLink\"><font color=#9999cc>$k</font></a></font><img src=\"$::o{'imgdirurl'}/spacer.gif\" width=10 height=1>";
        }
    }
    $ref = "<a href=\"javascript:openpopup('$::o{'cgilink'}?c=post','lnks',500,400)\"><img src=\"$::o{'imgdirurl'}/link.gif\" height=10 width=15 border=0></a>";
    if ($links) {
	$ans = <<END;
<table border=0 cellspacing=0 cellpadding=0 width="$::o{'tw'}%" background="$::o{'imgdirurl'}/vbg.gif">
<tr><td height=16 width="80%" align="right"><img src="$::o{'imgdirurl'}/bg0.gif" width=30 height=16></td>
<td nowrap align=right height=16 background="$::o{'imgdirurl'}/bg1.gif" bgcolor="#d8d8d8">$links<img src="$::o{'imgdirurl'}/spacer.gif" width=10 height=1></td>
<td height=16 background="$::o{'imgdirurl'}/bg1.gif" bgcolor="#d8d8d8">$ref</td></tr>
</table>
END
	 $ref = "";
    }
    $::my_favoriate_links = $ans;
    return $ref;
}
#=====================================================================================================================
sub mkCalList {
    my ($who, $text_clr, $observerMG)=(@_);
    my ($script, $orefB, $orefE, $popa, $popb, $wrap, $entry)=("","","","","", "", "");
    my (@othercals);
    if($::o{'listAllCals'} and &use_pulldown_nemu) {
        $::calinfo{'_clist_'} = 1;  @othercals = &listcals; delete $::calinfo{'_clist_'};
	my $allC = join(',',@othercals);
	if($observerMG and $::d{'megaCal'} ne "") {
	    #unshift @othercals,$::phr{'CombinedCalendar'};
	    $entry=select_optionX("w","$::phr{'CombinedCalendar'}",$::d{'megaCal'},@othercals);
	    $wrap="";
	} else {$entry=select_option("w",$who,@othercals);}
	my $acs = 0+@othercals;
	if($acs > 1 and $acs < 20) {
	    $entry =~ s#</select>#<option value=\"$allC\">==$::phr{'All'}==</select>#;
	}
	$entry =~ s/fmList/fmListH/g;
	$entry =~ s/>/ onChange=\"javascript:document.webcal.submit();\">/; #"
    } else {
	$popa="<a href=\"javascript:openpopup('$::o{'cginame'}?c=getcal&w=$who',\'calendars\',500,400)\" class=\"transparent\">";
	$popb = "</a>";
	$orefB = "<a href=\"javascript:openpopup('$::o{'cginame'}?c=getcal&w=$who',\'calendars\',500,400)\" class=\"transparent\">";
	$orefE ="</a>";
	$entry= "<input type=text size=16 maxlength=96  class=\"fmEntryH\" name=w value=\"";
	if($observerMG and $::d{'megaCal'} ne "") {
	    $entry .= "$::d{'megaCal'}\">";
	} else {
	    $entry .= "$who\">";
	}
	$entry .="<font $text_clr><b>&nbsp;<input type=button class=\"fmBtnH\" value=\"$::phr{'Go'}\" onClick=\"javascript:document.webcal.submit()\"></b></font>";
    }
    return ($entry, $script, $orefB, $orefE, $popa, $popb, $wrap);
}
#========================================================================================================   
sub getThemeColor {
    my $this_day;
    if(exists $::o{'headerColor'}) { $this_day= $::o{'headerColor'};} else {$this_day = 5;}
    if(exists $::calinfo{'themecolor'}) {
	if($::calinfo{'themecolor'} == -1) { $this_day = wday($::now{'month'}, $::now{'day'}, $::now{'year'});}
	elsif($::calinfo{'themecolor'} >= 0) { $this_day = $::calinfo{'themecolor'};}
    } else {
        if( ! exists $::o{'headerColor'}) {
            $this_day = wday($::now{'month'}, $::now{'day'}, $::now{'year'});
        }
    }
    if($this_day < 0 or $this_day > 6) { $this_day = 5;}
    $::themeColor=$::themeColors[$this_day];
    return $this_day;
}
#========================================================================================================   
sub newHeader0 {
    if($::o{'headerCode'}) {return( ("", customize_header($::o{'headerCode'}, @_)));}
    my ($cmd,$observerMG) = (@_);
    my ($who, $view, $ls, $date, $entry, $script, $orefB, $orefE, $mg, $wrap);
    my ($this_day, $tmp, $text_clr, $popa, $popb, $mylinks);
    my ($txt_clr, $logout, $log_in_out);
    my ($localdocA, $localdocB) = &getdocURL();
    my $version_string = &getVersionString();
    $who = $::calinfo{'w'};$view = $::calinfo{'v'}; $ls = $::calinfo{'ls'}; $date = $::calinfo{'d'};
    if(!$date)  {
	my ($month,$day,$year);
	$month=$::calinfo{'month'};$day=$::calinfo{'day'};$year=$::calinfo{'year'};
	$date="$month/$day/$year";
    }
    
    $this_day = &getThemeColor;
    $tmp = $::themeColors[$this_day];
    $text_clr = "color=$tmp";

    my $ownerinfo = &getOwnerInfo($cmd, $observerMG, $tmp);
    ($entry, $script, $orefB, $orefE, $popa, $popb, $wrap) = &mkCalList($who, $text_clr, $observerMG);
    if( ($::d{'remote_user'} ne 'anonymous' and $::d{'remote_user'} ne 'nobody') and
	($::d{'megaCal'} ne "" or ($::d{'remote_user'} and $who ne $::d{'remote_user'})) ) {
        my $me = $::d{'remote_user'}; my $alt= "$me: $::phr{'BackToCalendar'}";
        my $ghome= "<img src=\"$::o{'imgdirurl'}/spacer.gif\" width=4 height=1 border=0><a href=\"$::o{'cginame'}?c=get&w=$me&v=$view&ls=$ls&d=$date$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/home.gif\" width=10 height=11 border=0 alt=\"$alt\" title=\"$alt\"></a>&nbsp;";
        $entry .= $ghome;
    }
    $mylinks =&getMyFaviorateLinks($::d{'remote_user'});
    if($::d{'remote_user'} ne 'nobody'){$logout=$::phr{'Logout'};}
    else { $logout = "";}

    my $calselection;    my $hiddencalselection="";
    if(($::vm & 0x1) == 0) {
	$calselection="$popa<img src=\"$::o{'imgdirurl'}/yopen.gif\" width=25 height=16 border=0 align=bottom>$popb$entry";
    } else {
        $calselection="";
        my $w="";if($observerMG and $::d{'megaCal'}){$w=$::d{'megaCal'};}else{$w=$who;}
        $hiddencalselection="<input type=hidden name=w value=\"$w\">";
    }

    my ($pct1, $pct2, $pct3, $catlist, $clabel) =(25,1, 54,"","");
    if($::o{'category_filter'} and $::calinfo{'cfilter'} and not ($::vm &0x400000)) {
	my $cat; 
	if($::calinfo{'category'} or $::calinfo{'hiddencat'}){$cat=$::calinfo{'hiddencat'} || $::calinfo{'category'};}else{$cat="";}
	$catlist = build_catlist($who,'category',1, $cat); $catlist =~ s/fmList/fmListH/g;
	if($catlist) {my $tmp=""; if($cat !~ /^\s*$/) {$tmp="<img src=\"$::o{'imgdirurl'}/run.gif\" align=absmiddle border=0 width=24 height=8 title=\"\">";}
	    $catlist = "<a href=\"javascript:openpopup('$::o{'cgimisc'}?cmd=scat','scat',460,300)\" class=\"transparent\"><font size=-1 $text_clr><span class=fmLabelH>$::phr{'Category'}:</span></font></a>$tmp<font size=1><br></font>$catlist";
	    if($calselection){
		$clabel="$popa<font size=-1 $text_clr><span class=fmLabelH>$::phr{'Calendar'}:</span></font>$popb<font size=1><br>$entry</font>";$calselection="";
		$pct1 = 15; $pct2=15; $pct3=50;
	    } else {
		$pct1 = 1; $pct2=25; $pct3=54;
	    }
	}
    }
    #========================================================================================================
    my ($dndid,$dndop,$trash)=("","","");
    if($::o{'dnd'} and ($::vm & 0x1000)==0){
	$dndop ="ondragenter=\"dnden()\" ondragover=\"dndov()\" ondragleave=\"dndlv()\" ondrop=\"dnddp()\"" ;
	$dndid="id=\"___:1/1/1900\"";
	$trash="<img src=\"$::o{'imgdirurl'}/trash.gif\" width=15 height=10 border=0 title=\"\">";
    }
    #========================================================================================================
    my $head = <<ENDOFHEAD;
<input type=hidden name=c value=$cmd><input type=hidden name=v value=$view><input type=hidden name=ls value=$ls><input type=hidden name=ww value="$who"><input type=hidden name=d value="$date">
<table class="header" border=0 cellspacing=0 cellpadding=0 width="100%">
<tr>
 <td class="headertd"><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=32 border=0></td>
 <td class="headertd" valign=bottom nowrap width="10%">
  $localdocA<img src="$::o{'imgdirurl'}/xebcal00${this_day}.gif" width=152 height=43 border=0>$localdocB
<a href="$::o{'cginame'}?c=version"><font color="#ccccff" size=1><span class="version">$version_string</span></font></a>
</td>
 <td class="headertd"><img src="$::o{'imgdirurl'}/spacer.gif" width=16 height=1 border=0></td>
 <td class="headertd" nowrap width="$pct1%"><font $text_clr>$clabel$calselection$hiddencalselection</font></td>
 <td class="headertd"><img src="$::o{'imgdirurl'}/spacer.gif" width=8 height=1 border=0></td>
 <td class="headertd" nowrap width="$pct2%"><font $text_clr>$catlist</font></td>
 <td class="headertd"><img src="$::o{'imgdirurl'}/spacer.gif" width=16 height=1 border=0></td>
 <td class="headertd" $wrap width="$pct3%"><font $text_clr>$ownerinfo</font></td>
<td class="headertd" align=right nowrap width="5%" $dndid $dndop><a href="$::o{'cginame'}?c=logout&w=$who&v=$view&ls=$ls&d=$date$::vmg">
<font $text_clr><b><span class="logout">$logout</span></b></font></a><img src="$::o{'imgdirurl'}/spacer.gif" width=4 height=1 border=0>$trash $mylinks</td>
</tr>
</table>
ENDOFHEAD

    return ($script, $head);
}
#============================================================================================================
sub tabs_nbar {
    my ($cmd,$observerMG) = (@_);
    my (@othercals, $result, $who, $view, $ls, $stmp, $date, $entry, $mg, $time, $hour, $minu);
    my ($this_day, $tmp, $text_clr, $popa, $popb, $tab, $ftf);
    my ($this_clr, $that_clr, $txt_clra, $txt_clrb, $clr, $tlr, $zA, $zB, $wrap,$hover);
    my $mdy_string = mdy_wstring($::now{'month'}, $::now{'day'}, $::now{'year'});
    $who = $::calinfo{'w'};$view = $::calinfo{'v'}; $ls = $::calinfo{'ls'}; $date = $::calinfo{'d'};
    if(!$date)  {
	my ($month,$day,$year);
	$month=$::calinfo{'month'};$day=$::calinfo{'day'};$year=$::calinfo{'year'};
	$date="$month/$day/$year";
    }

    if($::d{'megaCal'} ne "") {$mg="&mg=$::d{'megaCal'}"; } else {$mg="";}
#    my $bgcolor= $::calinfo{'bgcolor'} || $webcalConfig::r{'backgroundColor'};
    my $bgcolor= $::calinfo{'bgcolor'} || $webcalConfig::r{'backgroundColor'};
    my $hex = parseColor($bgcolor);
#    my $tab_bg= $::calinfo{'tabcolor'} || $webcalConfig::r{'tabcolor'};
#    my $tab_hbg = $::calinfo{'tabcolorh'} || $webcalConfig::r{'tabcolorh'};
    my $tab_bg  = $webcalConfig::r{'tabcolor'};
    my $tab_hbg = $webcalConfig::r{'tabcolorh'};

    $this_day = &getThemeColor;    
    $tmp = $::themeColors[$this_day];
    $text_clr = "color=$tmp";
    $this_clr = "bgcolor=$tmp";
    $that_clr = "bgcolor=$tab_bg";
    $txt_clra = "color=#336699";
    $txt_clrb = "color=#ccccff";    

    my ($smenu_left, $smenu_middle, $smenu_right)= &calendar_submenu($cmd, $who, $date, $view, $ls, $mg);

    my $clockApplet = &getClockApplet();

    my $out =<<END; 
<table border=0 cellspacing=0 cellpadding=0 width="$::o{'tw'}%" class="tabcontainer">
<tr><td class="tabfillerrow"><img src="$::o{'imgdirurl'}/spacer.gif" width=20 height=8 border=0></td></tr>
<tr><td width="100%"><table border=0 cellspacing=0 cellpadding=0 width="100%" class="tabsbar">
<tr>
<td class="tabfiller" valign=bottom><img src="$::o{'imgdirurl'}/spacer.gif" width=8 height=4 border=0></td>
END
    my $swidth=70;
    my ($td1,  $td2);
    $td1 = <<END;
<td bgcolor="$bgcolor" class="tab00" width=1 height=1><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=1 border=0></td>
END
    ;
    $td2 = <<END;
<td class="tab01" width=1 bgcolor="$bgcolor" background="$::o{'imgdirurl'}/b0.gif"><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=1 border=0></td>
END
    ;
    foreach $tab (split(/,/,$::o{'tabs'})) {
	next if $tab eq 'admin' or $tab eq 'search';  # Search and Admin removed .... 08/04/2004
	my $href = "$::o{'cginame'}?c=$tab&w=$who&v=$view&ls=$ls&d=$date$mg$::vmg";
	my $highlight="";
	$swidth -= 2;
	if ($tab eq $cmd) {
	    $clr = $this_clr;
	    $tlr = $txt_clrb;
	    $hover="";
	    $highlight="Active";
	    if(exists $::d{'SATbs'}) {$zA= "<a href=\"$href\" class=\"transparetn\">"; }
            else { $zA = "<a href=\"javascript:void(0)\" class=\"transparent\">";}
            $zB= "</a>";
	} else {
	    $highlight="";
	    $clr = $that_clr;
	    $tlr = $txt_clra;
	    $zA= "<a href=\"$href\" class=\"transparent\">";
	    $zB= "</a>";
#	    $hover="onmouseover=\"nhover(this,1,'$tab_hbg','$tab_bg')\" onmouseout=\"nhover(this,0,'$tab_hbg','$tab_bg')\" onclick=\"ngoto(this,'$href')\"";
	    $hover="onmouseover=\"chover(this,1,'tabtabHover','tabtab')\" onmouseout=\"chover(this,0,'tabtabHover','tabtab')\" onclick=\"ngoto(this,'$href')\"";

	}
	$out .= <<ENDOFTEXT;
<td class="tabtab$highlight" align=center valign=bottom nowrap width="2%" $clr $hover>
<table border=0 cellpadding=0 cellspacing=0 class="atab"><tr>$td1
<td height=1 width=6 bgcolor="$bgcolor" class="tab10"><img src="$::o{'imgdirurl'}/l1.gif" width=6 height=1 border=0></td>
<td height=1 bgcolor="#b8bcb8" class="tab20"><img src="$::o{'imgdirurl'}/spacer.gif" width=24 height=1 border=0></td>
<td height=1 width=6 bgcolor="$bgcolor" class="tab30"><img src="$::o{'imgdirurl'}/r1.gif" width=6 height=1 border=0></td>
<td width=1 height=1 bgcolor="$bgcolor" class="tab40"><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=1 border=0></td></tr>
<tr>
$td2
<td width=6 height=5 valign=top class="tab11"><img src="$::o{'imgdirurl'}/t/l${hex}.gif" width=6 height=5 border=0></td>
<td align=center nowrap class="tab21">$zA<img src="$::o{'imgdirurl'}/y$tab.gif" width=25 height=16 border=0>$zB<br>$zA<font size=1 $tlr><span class="tabTxt$highlight">&nbsp;$::tabNames{$tab}&nbsp;</span></font>$zB</td>
<td width=6 height=5 valign=top class="tab31"><img src="$::o{'imgdirurl'}/t/r${hex}.gif" width=6 height=5 border=0></td>
<td width=1 bgcolor="$bgcolor" background="$::o{'imgdirurl'}/b0.gif" class="tab41"><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=24 border=0></td>
</tr>
</table>
 </td>
ENDOFTEXT
    $td1=$td2="";
  }
    my ($alink, $motd) = get_motd();
    my $spacer;
    if($motd) {
	my $tmp = int(32* rand()); 
	my $mclr = $webcalConfig::r{'txtColors'}->[$tmp];
	$spacer=<<END;
<td class="tabfiller" width="$swidth%" align=center valign=bottom nowrap><font color=$mclr><span class="motd">&nbsp;$motd</span></font></td>
END
    ;
    } else {
	$spacer=<<END;
<td class="tabfiller" width="$swidth%" align=center><img src="$::o{'imgdirurl'}/spacer.gif" width=32 height=1 border=0></td>
END
    ;
    }

    my $tend="";
    if(not $::d{'megaCal'} and $::calinfo{'ctype'} and $::calinfo{'ctype'} eq 'public_m' and -f "$::o{'spooldir'}/$who/pnd" and
       isre($::d{'remote_user'}, $who, 'editors')) {
	    $tend =<<END;
<a href="$::o{'cginame'}?c=pending&w=$who&ls=$ls&v=$view$mg$::vmg"><img src="$::o{'imgdirurl'}/eye.gif" width=14 height=14 align=top border=0 title="Tend to pending events" alt="Tend to pending events"></a> 
END
    ;
	}

    my $foot = <<ENDOFFOOT;
$spacer
 <td class="tabdtime" width="20%" nowrap align=right valign=bottom>$tend<font $text_clr>$alink <b><span class="datetime">$mdy_string&nbsp;</span></b></font></td>
 <td class="tabclock" width="8%" valign=bottom align=right nowrap>$clockApplet</td>
 </tr>
</table></td></tr>
<tr $this_clr><td width="100%">
<table border=0 cellspacing=0 cellpadding=0 width="100%" class="hnbar"><tr>
<td class="hnbartd"><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=20 border=0></td>
<td class="hnbartd" colspan=1 nowrap><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=14 border=0>$smenu_left</td><td class="hnbartd" align=center><font size=1>&nbsp;</font>$smenu_middle</td><td class="hnbartd" nowrap align=right colspan=1><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=14 border=0><font size=1>&nbsp;</font>$smenu_right</td>
</tr>
<tr><td class="hnbartd" colspan=4 bgcolor="#333333"><img src="$::o{'imgdirurl'}/spacer.gif" width=1 height=1 border=0></td></tr>
</table>
</td></tr>
</table>
ENDOFFOOT

    return  $out . $foot;
}
#============================================================================================================
sub parseColor {
    use integer;
    my ($in) = (@_);
    if($::approxbg{"$in"}) { return $::approxbg{"$in"};}
    my ($r,$g, $b, $hex,$rr,$gg,$bb, $ok); $ok=0;
    if( $in=~ /#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/ or
	$in=~ /([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/) {
	($r,$g,$b) = ($1,$2,$3); $ok=1;
    } else {
	my $k=lc($in);
	if($::sixteenColors{$k} and
	   $::sixteenColors{$k} =~ /#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/ ) {
	   ($r,$g,$b) = ($1,$2,$3);   $ok=1;	   
       }
    }
    if($ok) {
	$rr = sprintf("%02x", 51 * ((hex($r) + 50)/51));
	$gg = sprintf("%02x", 51 * ((hex($g) + 50)/51));
	$bb = sprintf("%02x", 51 * ((hex($b) + 50)/51));
	$hex = "$rr$gg$bb";
	$::approxbg{"$in"}=$hex;
	return $hex;
    }
    return "ffffff";
}
#============================================================================================================
sub calendar_submenu {
    my ($cmd, $who, $date, $view, $ls, $mg) = (@_);
    my ($left, $middle, $right);

#<img src="$::o{'imgdirurl'}/add.gif" width=12 height=16 align=top border=0>
#<font face="arial,helvetica,sans-serif" size=1 color=#006600>&nbsp;<b>+</b>&nbsp;</font>
    $middle = "";
    $left=$right="<font $webcalConfig::fontsize{'menubar'}>&nbsp;</font>";
    
    if($cmd eq 'get') {
	$left = <<END;
<font $webcalConfig::fontsize{'menubar'} color="#006600">&nbsp;</font>
<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
<a class="nbtn" href="$::o{'cginame'}?c=ne&k=1&v=$view&ls=$ls&w=$who&d=$date$mg$::vmg"><font $webcalConfig::fontsize{'menubar'} color=white><span class="hnbar">&nbsp;$::phr{'Appointment'}&nbsp;</span></font></a><img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
<a class="nbtn" href="$::o{'cginame'}?c=ne&k=2&w=$who&v=$view&ls=$ls&d=$date$mg$::vmg"><font $webcalConfig::fontsize{'menubar'} color=white><span class="hnbar">&nbsp;$::phr{'Todo'}&nbsp;</span></font></a><img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
<a class="nbtn" href="$::o{'cginame'}?c=ne&k=3&w=$who&v=$view&ls=$ls&d=$date$mg$::vmg"><font $webcalConfig::fontsize{'menubar'} color=white><span class="hnbar">&nbsp;$::phr{'Meeting'}&nbsp;</span></font></a><img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
<a class="nbtn" href="$::o{'cginame'}?c=ne&k=4&w=$who&v=$view&ls=$ls&d=$date$mg$::vmg"><font $webcalConfig::fontsize{'menubar'} color=white><span class="hnbar">&nbsp;$::phr{'Special'}&nbsp;</span></font></a><img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
<a class="nbtn" href="$::o{'cginame'}?c=vc&k=4&w=$who&v=$view&ls=$ls&d=$date$mg$::vmg"><font $webcalConfig::fontsize{'menubar'} color=white><span class="hnbar">&nbsp;vCal&nbsp;</span></font></a>
END
    $middle = <<END;

<a class="nbtn" href="$::o{'cginame'}?c=get&pnt=1&ls=$ls&w=$who&v=$view&d=$date$mg$::vmg" target=pnt><img src="$::o{'imgdirurl'}/printer.gif" width=16 height=16 border=0 title="$::phr{'Print'}" alt="$::phr{'Print'}" align=bottom></a>
END
    ;

	my ($lview1, $lview2, $lview3, $bview) = &set_view_buttons($who,$ls,$view,$date,$mg, 1); 
        my ($dv,$wv,$mv,$yv) = &set_d_w_m_y_buttons('get', $who,$ls,$view,$date,$mg,'#cccc99', "hnbar", $webcalConfig::fontsize{'menubar'}, 1);
        $right = <<END;
$dv<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
$wv<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
$mv<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
$yv<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>

$bview $lview1 $lview2 $lview3
END

    } elsif($cmd eq 'task') {
	my $cmd; if($::calinfo{'tkind'} and $::calinfo{'tkind'} eq 'c') { $cmd='task&tkind=c';} else{ $cmd="task";}
	$left = <<END;
<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
<a class="nbtn" href="$::o{'cginame'}?c=ne&sk=1&ls=$ls&w=$who&v=$view&k=2&d=$date$mg$::vmg">
<font $webcalConfig::fontsize{'menubar'} color=white><span class="hnbar">&nbsp;$::phr{'AddNewTask'}&nbsp;</span></font></a>
<img src="$::o{'imgdirurl'}/spacer.gif" width=100 height=4 border=0>
END
    ;
    $middle = <<END;
<a class="nbtn" href="$::o{'cginame'}?c=$cmd&pnt=1&ls=$ls&w=$who&v=$view&d=$date$mg$::vmg" target=pnt><img src="$::o{'imgdirurl'}/printer.gif" width=16 height=16 border=0 title="$::phr{'Print'}" alt="$::phr{'Print'}" align=bottom></a>
END
    ;
        my ($dv,$wv,$mv,$yv) = &set_d_w_m_y_buttons($cmd, $who,$ls,$view,$date,$mg,'#cccc99', "hnbar", $webcalConfig::fontsize{'menubar'}, 1);
        $right = <<END;
$dv<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
$wv<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
$mv<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
$yv

END
    ;

    } elsif($cmd eq 'ad') {
        if(not $::o{'contactdb'} or $::o{'contactdb'} =~ /default/i ) {
            $left = <<END;
<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
<a class="nbtn" href="$::o{'cginame'}?c=ead&w=$who&v=$view&ls=$ls&d=$date$mg$::vmg"><font $webcalConfig::fontsize{'menubar'} color=white><span class="hnbar">&nbsp;$::phr{'AddNewAddress'}&nbsp;</span></font></a>
<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
<a class="nbtn" href="$::o{'cginame'}?c=vcard&w=$who&v=$view&ls=$ls&d=$date$mg$::vmg"><font $webcalConfig::fontsize{'menubar'} color=white><span class="hnbar">&nbsp;vCard&nbsp;</span></font></a>
END
    ;
        }
    } elsif($cmd eq 'notes') {
	$left = <<END;
<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
<a class="nbtn" href="$::o{'cginame'}?c=notes&ntc=a&w=$who&v=$view&ls=$ls&d=$date$mg$::vmg"><font $webcalConfig::fontsize{'menubar'} color=white><span class="hnbar">&nbsp;$::phr{'AddNewNote'}&nbsp;</span></font></a>
END
    } elsif($cmd eq 'diary') {
       $left = <<END;
<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
<a class="nbtn" href="$::o{'cginame'}?c=ndiary&w=$who&v=$view&ls=$ls&d=$date$mg$::vmg"><font $webcalConfig::fontsize{'menubar'} color=white><span class="hnbar">&nbsp;$::phr{'AddNewEntry'}&nbsp;</span></font></a>
<img src="$::o{'imgdirurl'}/spacer.gif" width=160 height=1 border=0>
END
    
    $middle = <<END;
<a class="nbtn" href="$::o{'cginame'}?c=diary&pnt=1&ls=$ls&w=$who&v=$view&d=$date$mg$::vmg" target=pnt><img src="$::o{'imgdirurl'}/printer.gif" width=16 height=16 border=0 title="$::phr{'Print'}" alt="$::phr{'Print'}"></a>
END

    my $lview;
    if($::vm & 0x8000) {
	$lview=<<EOF;
<img src="$::o{'imgdirurl'}/vzlist.gif" height=15 width=15 border=0 align=top title="$::phr{'EventsTable'}" alt="$::phr{'EventsTable'}">
<a class="nbtn" href="$::o{'cginame'}?c=diary&d_e=false&ls=$ls&w=$who&v=$view&d=$date$mg$::vmg"><img src="$::o{'imgdirurl'}/zlist2.gif" height=15 width=15 border=0 align=top title="$::phr{'Diary'}" alt="$::phr{'Diary'}"></a>	
EOF
    ;
    } else {
	$lview=<<EOF;
<a class="nbtn" href="$::o{'cginame'}?c=diary&d_e=true&ls=$ls&w=$who&v=$view&d=$date$mg$::vmg"><img src="$::o{'imgdirurl'}/zlist.gif" height=15 width=15 border=0 align=top title="$::phr{'EventsTable'}" alt="$::phr{'EventsTable'}"></a>	
<img src="$::o{'imgdirurl'}/vzlist2.gif" height=15 width=15 border=0 align=top title="$::phr{'Diary'}" alt="$::phr{'Diary'}">
EOF
    ;
    }
        my ($dv,$wv,$mv,$yv) = &set_d_w_m_y_buttons('diary', $who,$ls,$view,$date,$mg,'#cccc99', "hnbar", $webcalConfig::fontsize{'menubar'}, 1);

    $right = <<END;
$dv<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
$wv<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
$mv<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
$yv<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0>
$lview
END

    } elsif($cmd eq 'search') {

    } elsif($cmd eq 'option') {

        if($::o{'create'} == 0 and (isadmin($::d{'remote_user'}) or iscreator($::d{'remote_user'}) 
				    or isvgadmin($::d{'remote_user'}, $::d{'remote_user'}))) {
            $left = <<END;
<span class="hnbar">&nbsp;</span>
<a class="nbtn" href="$::o{'cginame'}?c=setup">
<font $webcalConfig::fontsize{'menubar'} color=white><span class="hnbar">&nbsp;$::phr{'CreateNewCal'}&nbsp;</span></font></a>
END
        }
	if($::o{'vgroup'} and isadmin($::d{'remote_user'})) {
            $left .= <<END;
<img src="$::o{'imgdirurl'}/zdot.gif" width=15 height=6 border=0><span class="hnbar">&nbsp;</span>
<a class="nbtn" href="$::o{'cgimisc'}?cmd=vgp">
<font $webcalConfig::fontsize{'menubar'} color=white><span class="hnbar">&nbsp;$::phr{'VirtualGroup'}&nbsp;</span></font></a>
END
    ;
	}
        if($::o{'allowImageUpload'} and $::o{'reviewImageUpload'}) {
            if(ismember($::d{'remote_user'}, $::o{'ImageUploadReviewer'}) or isadmin($::d{'remote_user'})) {
                my @list = listImgDirContents("$::o{'imgdir'}/$::o{'uploadtmpsubdir'}", 0);
                if(0+@list > 0) {
                    $right="<img src=\"$::o{'imgdirurl'}/blinkeye.gif\" border=0 width=14 height=14>
<a href=\"$::o{'cginame'}?c=reviewUI&w=$who&v=$view&ls=$ls$::vmg\"><font $webcalConfig::fontsize{'menubar'} color=white><span class=\"hnbar\">&nbsp;$::phr{'ReviewUI'}&nbsp;</span><font color=white></a>";
                }
            }
        }
    }    
    if($::vm & 0x1000) { $left = "";}
    ( $left, $middle, $right);
}

#============================================================================================================
sub set_view_buttons {
    my($who,$ls,$view,$date,$mg, $flag) = (@_);
    my ($lview1, $lview2, $lview3, $bview) = ("","","","");
    my ($xx,$yy,$zz, $Z, $size, $align, $css);
    $xx = $::vm;
    if(($xx & 0x200)) { # list view 3
	$yy = $xx & ~0x200; 
	$zz = $xx; 
    } else { #listview 2
	$yy = $xx & ~0x200;
	$zz = $xx | 0x200; 
    }
    $yy="&x=$yy$::vmc"; $zz = "&x=$zz$::vmc";

    if($flag) { $size=15; $Z='z'; $align="align=bottom"; $css="hnbar";} else { $size=12, $Z='m'; $align="";$css="hnbarMini";}

    if(not $ls) {
	$bview=<<EOF;
<span class="$css"><img src="$::o{'imgdirurl'}/v${Z}block.gif" height=$size width=$size border=0 $align title="$::phr{'BlockView'}" alt="$::phr{'BlockView'}"></span>
EOF

	$lview1=<<EOF;
<a class="nbtn" href="$::o{'cginame'}?c=get&ls=1&w=$who&v=$view&d=$date$mg$::vmg"><span class="$css"><img src="$::o{'imgdirurl'}/${Z}list.gif" height=$size width=$size border=0 $align  title="$::phr{'ListView'} 1" alt="$::phr{'ListView'} 1"></span></a>
EOF
    
    $lview2 =<<EOF;
<a class="nbtn" href="$::o{'cginame'}?c=get&ls=-1&w=$who&v=$view&d=$date$mg$yy"><span class="$css"><img src="$::o{'imgdirurl'}/${Z}list1.gif" height=$size width=$size border=0 $align title="$::phr{'ListView'} 2" alt="$::phr{'ListView'} 2"></span></a>
EOF
    ;
    $lview3 =<<EOF;
<a class="nbtn" href="$::o{'cginame'}?c=get&ls=-1&w=$who&v=$view&d=$date$mg$zz"><span class="$css"><img src="$::o{'imgdirurl'}/${Z}list2.gif" height=$size width=$size border=0 $align title="$::phr{'ListView'} 3" alt="$::phr{'ListView'} 3"></span></a>
EOF
    ;

    } elsif($ls > 0) {
	$bview=<<EOF;
<a class="nbtn" href="$::o{'cginame'}?c=get&ls=0&w=$who&v=$view&d=$date$mg$::vmg"><span class="$css"><img src="$::o{'imgdirurl'}/${Z}block.gif" height=$size width=$size border=0 $align title="$::phr{'BlockView'}" alt="$::phr{'BlockView'}"></span></a>
EOF
    
    $lview1=<<EOF;
<span class="$css"><img src="$::o{'imgdirurl'}/v${Z}list.gif" height=$size width=$size border=0 $align  title="$::phr{'ListView'} 1" alt="$::phr{'ListView'} 1"></span>
EOF
    ;

    $lview2 =<<EOF;
<a class="nbtn" href="$::o{'cginame'}?c=get&ls=-1&w=$who&v=$view&d=$date$mg$yy"><span class="$css"><img src="$::o{'imgdirurl'}/${Z}list1.gif" height=$size width=$size border=0 $align title="$::phr{'ListView'} 2" alt="$::phr{'ListView'} 2"></span></a>
EOF
    $lview3 =<<EOF;
<a class="nbtn" href="$::o{'cginame'}?c=get&ls=-1&w=$who&v=$view&d=$date$mg$zz"><span class="$css"><img src="$::o{'imgdirurl'}/${Z}list2.gif" height=$size width=$size border=0 $align title="$::phr{'ListView'} 3" alt="$::phr{'ListView'} 3"></span></a>
EOF
    ;
    }
    return ($lview1, $lview2, $lview3, $bview);
}


sub set_d_w_m_y_buttons {
    my($cmd, $who,$ls,$view,$date,$mg, $dclr,$css, $size, $flag) = (@_);
    my ($dv,$wv,$mv,$yv, $viwe);
    my ($Day, $Week, $Month, $Year);
    if($flag) {
        ($Day, $Week, $Month, $Year) = 
            ("&nbsp;$::phr{'Day'}&nbsp;","&nbsp;$::phr{'Week'}&nbsp;",
	     "&nbsp;$::phr{'Month'}&nbsp;","&nbsp;$::phr{'Year'}&nbsp;");
    } else {
	my ($vdd, $vww,$vmm,$vyy)=("","","","");
	if($view == 1){$vdd="v";}elsif($view ==2){$vww="v";}elsif($view==3){$vmm="v";} else {$vyy="v";}
        $Day = "<img src=\"$::o{'imgdirurl'}/${vdd}md.gif\" width=12 height=12 border=0 title=\"$::phr{'Day'}\" alt=\"$::phr{'Day'}\">";
        $Week = "<img src=\"$::o{'imgdirurl'}/${vww}mw.gif\" width=12 height=12 border=0 title=\"$::phr{'Week'}\" alt=\"$::phr{'Week'}\">";
        $Month = "<img src=\"$::o{'imgdirurl'}/${vmm}mm.gif\" width=12 height=12 border=0 title=\"$::phr{'Month'}\" alt=\"$::phr{'Month'}\">";
        $Year = "<img src=\"$::o{'imgdirurl'}/${vyy}my.gif\" width=12 height=12 border=0 title=\"$::phr{'Year'}\" alt=\"$::phr{'Year'}\">";
#	if($view == 1) { $Day = "";} elsif($view ==2){$Week = "";} elsif($view==3){$Month="";} else {$Year="";}
    }
                                    
    if($::d{'SATbs'}) { $viwe=10;} else {$viwe=$view;}
    if($viwe == 1) {
        $dv = <<END;
<font $size><span class="$css"><font color=$dclr>$Day</font></span></font>
END
    ;
    } else {
        $dv = <<END;
<a class="nbtn" href="$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=1&d=$date$mg$::vmg"><font $size color=white><span class="$css">$Day</span></font></a>
END
    ;
    }
    if($viwe == 2) {
        $wv = <<END;
<font $size><span class="$css"><font color=$dclr>$Week</font></span></font>
END
    ;
    } else {
        $wv = <<END;
<a class="nbtn" href="$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=2&d=$date$mg$::vmg"><font $size color=white><span class="$css">$Week</span></font></a>
END
    ;
    }
    if($viwe == 3) {
        $mv = <<END;
<font $size><span class="$css"><font color=$dclr>$Month</font></span></font>
END
    ;
    } else {
        $mv = <<END;
<a class="nbtn" href="$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=3&d=$date$mg$::vmg"><font $size color=white><span class="$css">$Month</span></font></a>
END
   ; 
    }
    if($viwe == 4) {
        $yv = <<END;
<font $size><span class="$css"><font color=$dclr>$Year</font></span></font>
END
    ;
    } else {
        $yv = <<END;
<a class="nbtn" href="$::o{'cginame'}?c=$cmd&ls=$ls&w=$who&v=4&d=$date$mg$::vmg"><font $size color=white><span class="$css">$Year</span></font></a>
END
    ;
    }
    return($dv, $wv, $mv, $yv);
}
#==================================================================================

sub mini_tabs_nbar {
    my ($cmd,$observerMG) = (@_);
    my ($ans, $ans1) = ("", "");
    if($cmd eq 'get') {
        my ($who, $ls, $view, $mg, $date);
        $who = $::calinfo{'w'};$view = $::calinfo{'v'}; $ls = $::calinfo{'ls'}; 
        $date = $::calinfo{'d'};
        if(!$date) {
            my ($month,$day,$year);
            $month=$::calinfo{'month'};$day=$::calinfo{'day'};
            $year=$::calinfo{'year'}; $date="$month/$day/$year";
        }
        if($::d{'megaCal'} ne "") {$mg="&mg=$::d{'megaCal'}"; } else {$mg="";}
        my ($dv,$wv,$mv,$yv) =
            &set_d_w_m_y_buttons('get', $who,$ls,$view,$date,$mg,'#cccc99',,'hnbarMini', 'size=1', 0);
        $ans = "$dv $wv $mv $yv";
	my ($lview1, $lview2, $lview3, $bview) = 
	    &set_view_buttons($who,$ls,$view,$date,$mg,0);
	$ans1 = " $bview $lview1 $lview2 $lview3";
    }
    return ($ans, $ans1);
}

#============================================================================================================
sub getVersionString {
    return "$webCalVersion-$patchlevel";
}

#============================================================================================================
sub doReadFile {
    my ($path) = (@_); if($path =~ /^(\/.+)$/ ) { $path = $1;}
    my $fh = gensym;
    if($path and open($fh, "<$path")) {
        &webcalLock::doflock(\*$fh, LOCK_SH, "$path") or calerror("Cannot lock file '$path': $!\n",1);
        my $result = do "$path";
        &webcalLock::doflock(\*$fh, LOCK_UN, "$path") or calerror("Cannot unlock file '$path': $!\n",1);
        close $fh;
        return $result;
    }
    return 0;
}
#============================================================================================================
sub listImgDirContents {
    my ($dir, $hide) = (@_);
    my ($name, @list1, @list2, @list3);
    my $who = $::d{'remote_user'};  if( !$who) { $who="nobody";}
    my $cal = $::calinfo{'w'}; if (!$cal) { $cal = "nobody";}
    @list1=(); @list2=(); @list3=();
    my $DIR9= gensym;
    if(opendir($DIR9, $dir)) {
        while ($name = readdir($DIR9)) {
            next if $name =~/^\./;
	    next if (! -f "$dir/$name");
	    next if $hide and $name =~ /^private/ and $name !~ /^private_$who/;
	    if( $name =~ /$who/ or  $name =~ /^private_$who/) { push (@list1, $name);}
	    elsif($name =~ /$cal/) { push (@list2, $name);}
	    else { push (@list3, $name);}
        }
        closedir($DIR9);
    }
    return (sort(@list1), sort(@list2), sort(@list3));
}
#============================================================================================================
sub showAvailableImages {
    my($who, $repos, $name, @list, $imgdirurl, $imgoffset, $total, $nbar, $the_form, $the_elt, $dofm, $fminfo,$append);
    $repos = "$::o{'imgdir'}/$::o{'uploadsubdir'}";
    @list= listImgDirContents($repos, 1);
    $total = 0 + @list;
    $nbar = ""; $append=1;
    if($total == 0) {calerror("No images are available in the repository.", -1);}
    $who = $::calinfo{'w'}; $the_form= $::calinfo{'the_form'}; $the_elt= $::calinfo{'the_elt'}; 
    if($the_form and $the_elt) {
	$dofm=1; $fminfo="&the_form=$the_form" . "&the_elt=$the_elt";
	if($::calinfo{'noappend'}) {$append=0; $fminfo .= "&noappend=1";} 
    } else {$the_form=$the_elt=""; $dofm=0; $fminfo="";}
    $imgoffset =0;  $imgoffset = $::calinfo{'imgoffset'} if defined $::calinfo{'imgoffset'};
    if($total > 20) {
        my ($offset, $i, $j);
	$offset = $imgoffset;
        for($i=0; $i<$total; $i+= 20) {
            $j = $i+19; if($j > $total) { $j = $total;}
            my $tmp = "$i" . "-" . "$j";
	    if($nbar) { $nbar .= "&nbsp;|&nbsp;";}
            if($i ne $offset) { $nbar .= "<a href=\"$::o{'cginame'}?c=simage&imgoffset=$i&w=$who$fminfo\" class=\"lnkrange\">$tmp</a>";}
            else { $nbar .= "<b><font color=\"#333333\"><span class=\"lnkrange\">$tmp</span></font></b>";}
        }
    }
    $imgdirurl = "$::o{'imgdirurl'}/$::o{'uploadsubdir'}";
    my $jsscript = "";
    if($dofm) {
	$jsscript =<<END;
function imgadd(s) {
var ele=window.opener.document.$the_form.$the_elt;var tmp=ele.value; var nn="^o^/"+s;
if(tmp.indexOf(nn) == -1) { ele.value += "  ^o^/"+s;} 
}
function imgselect(s) {
var ele=window.opener.document.$the_form.$the_elt;var tmp=ele.value;var ptn=/\\^o\\^\\/([^\\s]+)/;var nn="^o^/"+s;
tmp=tmp.replace(ptn,nn);var jnk=tmp.match(ptn);if(jnk==null){tmp += " ^o^/"+s;} ele.value=tmp; self.close();
}
END
    ;
     }
    &headers("$::phr{'UsableImgs'}", $jsscript, undef,1);
    print "<center>
<h2 class=\"miscTitle\">$::phr{'UsableImgs'}</h2>
<table width=\"90%\" border=0><tr><td><font color=#ff0000><b><span class=\"msg\">$::phr{'UImageInst'}</span></b></font></td></tr></table>
<br>";
    
    if($dofm) { print "<form name=\"noname\">";} 
    print "<table bgcolor=$webcalConfig::r{'backgroundColor'} border=1 cellpadding=2 cellspacing=0 width=\"70%\">";
    my $end = $total; if($total > $imgoffset + 20 ) { $end = $imgoffset + 20;}
    my $i;
    for($i = $imgoffset; $i < $end; $i++) {
        $name = $list[$i];
        print "<tr><td><span class=\"fmLabel\"><font color=#ff0000>\\</font><font color=#009900>^o^</font><font color=#ff0000>/</font>$name</span>";
	if($dofm) {
	    print "<br><input type=button value=\" + \" onclick=\"javascript:imgselect(\'$name\')\" class=\"fmBtn\">";
	    if($append){ print "&nbsp;<input type=button value=\" ++ \" onclick=\"javascript:imgadd(\'$name\')\" class=\"fmBtn\">";}
	}
        print "</td><td>";
	if($name =~/([^\s]+?)(size=)(\d+)x(\d+)([^\s]*)\.(gif|jpg|png|jpeg|bmp)/i) {
	    print "<img src=\"$imgdirurl/$name\" border=0 width=\"$3\" height=\"$4\">";
	} elsif($name =~/([^\s]+?)\.(gif|jpg|png|jpeg|bmp)/i) {
	    print "<img src=\"$imgdirurl/$name\" border=0>";
	} elsif($name =~/([^\s]+?)(size=)(\d+)x(\d+)([^\s]*)\.(swf)/i) {
	    print "<embed src=\"$imgdirurl/$name\" type=\"application/x-shockwave-flash\" width=\"$3\" height=\"$4\">";
	} elsif($name =~/([^\s]+?)\.(swf)/i) {
	    print "<embed src=\"$imgdirurl/$name\" type=\"application/x-shockwave-flash\">";
	} else { print "$name";}
	print "</td></tr>";
    }
    print "</table>";    
    if($dofm) { print "</form>";} 

    print "<table bgcolor=$webcalConfig::r{'backgroundColor'} border=0 cellpadding=2 cellspacing=0 width=\"70%\">";
    print "<tr><td align=center colspan=2><font size=+1><b>";
    if($total > 20) {
        if($imgoffset > 0) {
            my $tmp = $imgoffset -20;
            print "<a href=\"$::o{'cginame'}?c=simage&imgoffset=$tmp&w=$who$fminfo\" class=\"lnkstep\">&lt;&lt;</a>&nbsp;&nbsp;";
        }
        if($imgoffset +20 < $total) {
            my $tmp = $imgoffset +20;
            print "&nbsp;&nbsp;<a href=\"$::o{'cginame'}?c=simage&imgoffset=$tmp&w=$who$fminfo\" class=\"lnkstep\">&gt;&gt;</font></a>";
        }
    }
    print "</b></font>";
    print "</td><td align=right><form><b><input type=button value=\"$::phr{'Close'}\" onclick=\"self.close()\" class=\"fmBtnSt\"></b></form>";
    print "</b></font></td></tr></table></center>";
    if($nbar){ print "<br><hr><center><br><font size=1><blockquote class=\"rangeSelectNBar\">$nbar</blockquote></font></center>";}
    &trailer(0,0);
    myexit(0);
}


sub reviewUpload {
    if(!$::o{'allowImageUpload'}) { calerror("Image upload is disabled.", 1);}
    if($::o{'reviewImageUpload'}) {    
	my($who, $isreviewer, $repos, $name, @list, @flist, $i, $imgdirurl, $total);
	$who = $::d{'remote_user'};
	$isreviewer = ismember($who, $::o{'ImageUploadReviewer'});
        my $isadmin = isadmin($::d{'remote_user'});
	if(!$isreviewer and ! $isadmin) { calerror("You ($who) are not authorized to review image uploads.");}
	$repos = "$::o{'imgdir'}/$::o{'uploadtmpsubdir'}";
	my $htaccess = "$repos/.htaccess";
	if( -f "$htaccess") {  rename $htaccess, $htaccess . "-old";}
        @flist = ();
        @list= listImgDirContents($repos, 0);
        $total = 0 + @list;
	if($total == 0) {calerror("There is no new uploads need to be processed.", 1);}
        foreach $name (@list) {
            $name = untaintname($name, "");
            push(@flist,"$repos/$name");
        }
	my $cnt = chmod 0644, @flist; # make upload readable 
	$imgdirurl = "$::o{'imgdirurl'}/$::o{'uploadtmpsubdir'}";
	&headers("$::phr{'ReviewUI'}",undef, undef,1);
	$i=0;

	my $wwho = $::calinfo{'w'};
	my $view = $::calinfo{'v'};
	my $ls = $::calinfo{'ls'};
	print "<center>
<h2>$::phr{'ReviewUI'}</h2>
<Form action=\"$::o{'cginame'}\" method=POST>$::vmp
<input type=hidden name=c value=\"doReviewUI\">
<input type=hidden name=total value=\"$total\">
<input type=hidden name=w value=\"$wwho\">
<input type=hidden name=v value=\"$view\">
<input type=hidden name=ls value=\"$ls\">
<table bgcolor=$webcalConfig::r{'backgroundColor'} border=1 cellpadding=2 cellspacing=0 width=\"70%\">
";
	while( defined($name = shift @list)) {
	    print "<tr><td><input type=checkbox class=\"fmRadio\" name=\"img$i\" value=\"$name\"><span class=\"fmLabel\">&nbsp;&nbsp;$name</span></td>
<td><img src=\"$imgdirurl/$name\" border=0></td></tr>";
	    $i++;
	}
	print "<tr><td colspan=2><font color=#0000cc><blockquote class=\"msg\">
The permission on all fresh uploads has been changed so you can review them. These files are now
readable by the public. You <font color=red><b>MUST click on one of the submission buttons</b></font>
below to restore permissions on these files.</blockquote></font></td></tr>";
	print "<tr><td align=center colspan=2><font color=#336699><b>";
	print "<input type=submit name=action value=\"$::phr{'ApproveChecked'}\" class=\"fmBtnSt\"> &nbsp;&nbsp;&nbsp;";
	print "<input type=submit name=action value=\"$::phr{'RejectChecked'}\" class=\"fmBtnSt\"> &nbsp;&nbsp;&nbsp;";
	print "<input type=submit name=action value=\"$::phr{'Cancel'}\" class=\"fmBtnSt\">";
	print "</b></font></td></tr></table>";
	&trailer(0,0);
    } else {
	calerror("Review image upload is not enforced. Edit your site configuration file to enable this feature", 1);
    }
}
sub doReviewUpload {
    if(! $::o{'allowImageUpload'}) { calerror("Image upload is disabled.", 1);}
    if($::o{'reviewImageUpload'}) {    
	my($who, $isreviewer, $repos, $destdir, $name, %marks, @list, $i, $cnm, $total, $action, $cnt, $msg,$debug);
	$who = $::d{'remote_user'};
	$isreviewer = ismember($who, $::o{'ImageUploadReviewer'});
        my $isadmin = isadmin($::d{'remote_user'});
	if(!$isreviewer and ! $isadmin) { calerror("You ($who) are not authorized to review image uploads.");}
	$repos = "$::o{'imgdir'}/$::o{'uploadtmpsubdir'}";    
	$destdir = "$::o{'imgdir'}/$::o{'uploadsubdir'}";    
	%marks=(); 
        @list = listImgDirContents($repos, 0);
	$action = $::calinfo{'action'};
	$total = $::calinfo{'total'};
	$cnt = 0;	
	for($i=0; $i<$total; $i++) { $cnm = "img$i";   if($::calinfo{$cnm}){ my $k=$::calinfo{$cnm}; $marks{$k}=1; $cnt++;}};
	if($cnt == 0 and $action ne "$::phr{'Cancel'}") {
	    foreach $name (@list) { $name=untaintname($name,""); chmod 0200, "$repos/$name";}
	    calerror("Please select some images first.", 1);
	}

	if($action eq "$::phr{'ApproveChecked'}") { # approve upload
	    foreach $name (@list) {
		$name = untaintname($name, "");
		if( $marks{$name}) { # approve this image
		    my $ok = 0;
		    chmod 0644, "$repos/$name";
		    my $fhdf = gensym;
		    if(open($fhdf, ">$destdir/$name")) {
			binmode($fhdf);
			if(open(SF, "<$repos/$name")){$ok=1;binmode(SF);while(<SF>){print $fhdf $_;} close(SF);}
			close($fhdf);
			chmod 0644, "$destdir/$name";		
		    }
		    if(!$ok) {calerror("Cannot read or write to \"$destdir/$name\" or \"$repos/$name\"", 1);}
		    unlink "$repos/$name";
		} else { # change permission back to 0200
		    chmod 0200, "$repos/$name";
		}
	    }
	    $msg="You have approved $cnt files. Thank you.";
	} elsif($action eq "$::phr{'RejectChecked'}") { # reject upload
	    if( ! -f "$destdir/rejected.gif") {
		if(open(TF, ">$destdir/rejected.gif")) {
		    binmode(TF);
		    if(open(SF,"<$::o{'imgdir'}/rejected.gif")){binmode(SF);while(<SF>){print TF $_;} close SF;}
		    close TF;
		    chmod 0644, "$destdir/rejected.gif";
		}
	    }
	    my $rej = "$destdir/rejected.gif";
	    
	    foreach $name (@list) {
		$name = untaintname($name, "");
		if( $marks{$name}) { # delete this image		
		    #unlink "$destdir/$name" if -f "$destdir/$name";
		    #if( -f "$rej") { link "$rej", "$destdir/$name";}
		    my $fhdf = gensym;
		    if(open($fhdf,">$destdir/$name")){
			binmode($fhdf);
			my $fsf = gensym;
			if(open($fsf,"<$rej")){binmode($fsf);while(<$fsf>){print $fhdf $_;} close $fsf;}
			close($fhdf);
		    } else {unlink "$destdir/$name" if -f "$destdir/$name";}
		    unlink "$repos/$name";
		} else { # change permission back to 0200
		    chmod 0200, "$repos/$name";
		}
	    }
	    $msg = "You have rejected $cnt files. Thank you.";
	} else { #cancel
	    foreach $name (@list) { $name=untaintname($name,""); chmod 0200, "$repos/$name";}
	    $msg = "Action canceled."
	}
	my $htaccess = "$::o{'imgdir'}/$::o{'uploadtmpsubdir'}/.htaccess";
	if( -f "$htaccess" . "-old") { rename "$htaccess" . "-old", "$htaccess";}
	else {
	    my $fhht = gensym;
	    if(open($fhht, ">$htaccess")) {
		     print $fhht <<_END_;
AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName Restricted
AuthType Basic
<Limit GET POST PUT>
require valid-user
</Limit>
_END_
    ;
		     close $fhht;
		 }
	}
	# acknowledge
	{
	    my ($who, $ls, $view, $d);
	    $who = $::calinfo{'w'};
	    $ls = $::calinfo{'ls'};
	    $view = $::calinfo{'v'};
	    $d= printDate0($::now{'month'}, $::now{'day'}, $::now{'year'});
	    acknowledge($who, $view, $ls, $d, $msg);
	}
    } else {
	calerror("Review image upload is not enforced. Edit your site configuration file to enable this feature", 1);    
    }
}
#============================================================================================================
sub summary {
    my($who, $cal, @list, $tmp, $cnt);
    $who = $::calinfo{'w'};
    @list = (); 
    &headers("$::phr{'Calendar'} Summary","",0,0,1);
    if($::calinfo{'mg'}) {
	my ($memb, @mlist);
	@mlist = split(',',$::calinfo{'mg'});
	for $memb (@mlist) {
	    $memb =~ s/[ ]+//g;
	    push @list, $memb if $memb ne "$who";
	}
    }
    unshift @list, $who;
    print "<center><br><table><tr>";
    $cnt = 0;
    foreach $cal (@list) {
	$tmp = summaryone($cal);
	print "<td width=\"30%\"bgcolor=$webcalConfig::r{'dkbackground'}><table width=\"100%\" border=0 cellpadding=2>", "\n";
	print $tmp;
	print "</table></td>";
	$cnt++;
	if($cnt == 3) { print "</tr><tr>"; $cnt = 0;}
    }
    print "</tr></table>", "\n";
    print "<br><br><table><tr><td align=center><form><b><input type=button class=\"fmBtn\" value=\"$::phr{'Close'}\" onClick=\"self.close()\"></b></form></td></tr></table>";
    print "</center>";
    &trailer(0,0);
}
sub summaryone {
    use integer;
    my ($who) = (@_);
    my ($cal, $msg, $rname, $total, $apt, $todo, $meet, $special, $ret, $href, $diary, $contacts, $mgps, $notes);
    $who=untaintname($who,$::phr{'Invalidusername'});
    $cal = "$::o{'spooldir'}/$who";
    $ret = "";
    $total = $apt = $todo = $meet = $special = $contacts = $diary = $mgps = $notes = 0;
    if( -d $cal and -f "$cal/info") {
	$rname = getinfo($who, 'name');
	@::caldata=();
	&doReadFile("$cal/data");
	foreach $href (@::caldata) {
	    if($href->{'kind'} == 1) { $apt++;}
	    elsif($href->{'kind'} == 2) { $todo++;}
	    elsif($href->{'kind'} == 3) { $meet++;}
	    else { $special++;}
	}
	@::addressbook = ();
	if( -f "$cal/address") { &doReadFile("$cal/address"); $contacts = 0+@::addressbook;}
	%::meetingGroups = ();
	if( -f "$cal/mgroup") { &doReadFile("$cal/mgroup"); my @mgs = (keys %::meetingGroups); $mgps = $#mgs;}
	$notes = countFiles("$cal/notes") / 2;
	my $i; for($i=2000; $i < 2030; $i++){$diary += countFiles("$cal/$i");}
	$total = $apt + $todo + $meet + $special;
	$ret = <<END;
<tr bgcolor=#0000ff><td colspan=2 nowrap><font color=#ffffff><b>$::phr{'Calendar'}: $who </b> ($rname)</font></td></tr>
<tr><td><b>$::phr{'Events'}:</b></td><td><b>$total</b></td></tr>
<tr><td>$::phr{'Appointment'}:</td><td>$apt</td></tr>
<tr><td>$::phr{'Todo'}:</td><td>$todo</td></tr>
<tr><td>$::phr{'Meeting'}:</td><td>$meet</td></tr>
<tr><td>$::phr{'Special'}:</td><td>$special</td></tr>
<tr><td><b>$::phr{'Meeting_group'}:</b></td><td>$mgps</td></tr>
<tr><td><b>$::phr{'Contacts'}:</b></td><td>$contacts</td></tr>
<tr><td><b>$::phr{'Notes'}:</b></td><td>$notes</td></tr>
<tr><td><b>$::phr{'Diary'}:</b></td><td>$diary</td></tr>
END
    }
    $ret;
}
#============================================================================================================
sub countFiles {
    my $dir = shift;
    my $cnt = 0;
    if(-d $dir) {
	my $DIRa= gensym;
	if(opendir($DIRa, "$dir")) {
	    my @all = readdir($DIRa);
	    closedir($DIRa);
	    my $n;
	    foreach $n (@all) {
		next if $n =~ /^\./;
		if( -f "$dir/$n") { $cnt++;}
		elsif( -d "$dir/$n") { $cnt += &countFiles("$dir/$n");}
	    }
	}
    }
    return $cnt;
}
#==========================================================================================================
sub cmpDateTime {
    my ($a, $b)=(@_);
    my $utimea = iso8601timeToTime($a);
    my $utimeb = iso8601timeToTime($b);
    return $utimea <=> $utimeb;
}

sub iso8601timeToTime {
    my($a)= (@_);
    my($date, $time, $utime, $year, $mon, $mday, $hour, $min, $sec, $isutc, $tzone);
    if( $a =~ m/(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)(Z?)/ or
	$a =~ m/(\d{4})\-(\d\d)\-(\d\d)T(\d\d):(\d\d):(\d\d)(Z?)/ )  {
	$year = $1; $mon = $2; $mday = $3;
	$hour =$4; $min = $5; $sec = $6;
	$isutc = $7;	
	if($isutc) {
	    ($sec, $min,$hour,$mday, $mon, $year, $tzone, $utime) = 
		UTCToLocal($sec, $min,$hour,$mday, $mon -1, $year -1900, undef);
	} else { $utime = timeLocal($sec, $min, $hour, $mday, $mon -1, $year);}
    }
    return($utime);
}
#==========================================================================================================
sub parseVCard {
    my ($who,$des) = (@_);  
    my (@lines,$nlines, $i, $j, $k);
    my (@entries);
    $des =~ s/\r\n/\n/g;
    $des =~ s/\r/\n/g;
    $des =~ s/=0D=0A=?\n/ /g;    
    $des =~ s/\n\W*:/:/g;
    $des =~ s/\n\s//g;
#    $des =~ s/\n\s+/\n/g;

    # split input into lines
    @lines = split(/\n/, $des);
    $nlines = 0+@lines;
    @entries =();
    $i=0;
    while($i < $nlines) {
	$i = nextVCard(\@lines, $i, $nlines, \@entries);
    }
    return @entries;
}
sub nextVCard {
    my ($aref, $start, $end, $storage) = (@_);
    my ($i, $tmp, @ary);
    @ary=();
    $i = $start;
    $tmp = $aref->[$i];
    while( $i < $end and $tmp !~ /BEGIN:\s*VCARD/i) {
	$i++; $tmp = $aref->[$i];
    }
    if($i< $end) {
	push @ary, $tmp;
	$i++;	$tmp = $aref->[$i];
	while( $i < $end and $tmp !~ /END:\s*VCARD/i) {
	    if($tmp =~ /BEGIN:\s*VCARD/i) {
		$i = nextVCard($aref, $i, $end, $storage);
	    }  else {
		push @ary, $tmp;
		$i++;
	    }
	    $tmp = $aref->[$i];
	}
	$tmp = $aref->[$i];
	if($tmp =~ /END:VCARD/i) { push @ary, $tmp;}
	my $href = fromVCard(\@ary);
	push @$storage, $href if $href;
    }
    return $i;
}
sub fromVCard {
    my ($aref) = (@_);
    my($line, $m, $n, $p, $v, @names,%hash, $addrcnt, $ecnt);
    %hash=();
    $ecnt = 0;
    $hash{'phone'} = $hash{'fax'} ="";
    $hash{'info'} = "";
    foreach $line (@$aref) {
	next if $line =~ /:VCARD/i;
	($m, $v)=split(/:/, $line, 2);
        $v="" unless $v; $v =~ s/^\s+//; $v =~ s/^\s+$//;
        $m =~ s/^\s+//; $m =~ s/^\s+$//;
	($n,$p) = split(/;/, $m, 2); $n = uc($n);
	if($n eq 'FN') { $hash{'fn'} = $v; $ecnt=1;}
	elsif($n eq 'N') {
	    my($ln,$fn,$an,$pfx,$sfx) = split(/;\s*/,$v);
	    $hash{'fname'} = $fn;
	    $hash{'lname'} = $ln;
	    $ecnt=1;
	} elsif($n eq 'ADR') {
	    $ecnt=1;
            if(exists $hash{'addr'} ) {
                $ m=~ s/\s//g;
                $hash{'info'} .= "$m:$v\n";
            } else {
                my ($po, $ea, $street,$city,$state,$zip,$country)=split(/;/,$v);
                $po="" unless $po; $ea="" unless $ea;  $street="" unless $street; 
                $city="" unless $city; $state="" unless $state; $zip="" unless $zip; 
                $country="" unless $country; 
                $hash{'addr'} = "$po $ea $street";
                $hash{'city'} = "$city";	    
                $hash{'state'} = "$state";	    
                $hash{'zip'} = "$zip";	    
                $hash{'country'} = "$country";	    
            }
	} elsif($n eq 'TEL') {
	    $ecnt=1;
	    my $number;
	    if($p) { 
		$number="$p=$v"; 
		if($p =~ /FAX/i) { if($hash{'fax'}){$hash{'fax'} .= "\n$v ";}else{ $hash{'fax'}=$v;}}
		else{if($hash{'phone'}) { $hash{'phone'} .= "\n$number";} else {$hash{'phone'} = $number;}}
	    } else { 
		$number = $v; 
		if($hash{'phone'}) { $hash{'phone'} .= "\n$number";} else {$hash{'phone'} = $number;}
	    }
	} elsif($n eq 'EMAIL') {
	    $ecnt=1;
	    $hash{'email'} = "$v";	    
	} elsif($n eq 'ORG') {
	    $ecnt=1;
	    $hash{'com'} = "$v"; 
	} elsif($n eq 'NOTE') {
	    $ecnt=1;
	    $hash{'info'} .= "$v"; 
	} elsif($n eq 'REV') {
	    $ecnt=1;
	    $hash{'rev'} = "$v"; 
	} elsif($n eq 'X-URL') {
	    $ecnt=1;
	    $hash{'hpage'} = "$v"; 
	}
    }
    if(!exists $hash{'fname'} and !exists $hash{'lname'}) { 
	if($hash{'fn'}){$hash{'fname'} = $hash{'fn'}; } else {$hash{'fname'} = "";}
	$hash{'lname'}="";
    }
    if($ecnt == 0)  { return undef;}
    return \%hash;
}
#=======================================================================================================
sub toVCard {
    my ($href, $who, $privacy)=(@_);
    my($msg, $tmp, $rev, $fnm, $lnm, $addrok, $smp, $p, $q);
    return "" if $privacy < 3;
    $msg = "BEGIN:VCARD\n";
    if($href->{'fname'}){ $fnm = $href->{'fname'};} else {$fnm = "";}
    if($href->{'lname'}){ $lnm = $href->{'lname'};} else {$lnm = "";}
    if($fnm or $lnm){
        $tmp = "FN:$fnm $lnm\n";     $msg .= $tmp;
        $tmp = "N:$lnm;$fnm;;;;;\n"; $msg .= $tmp;
    }
    $href->{'addr'} ="" unless $href->{'addr'}; $href->{'city'} ="" unless $href->{'city'};
    $href->{'state'} ="" unless $href->{'state'}; $href->{'zip'} ="" unless $href->{'zip'};
    $href->{'country'}="" unless $href->{'country'}; 
    $addrok =  ($href->{'addr'} or $href->{'city'} or $href->{'state'} or $href->{'zip'} or $href->{'country'});
    if($addrok) {
	$tmp = "ADR;POSTAL:;;$href->{'addr'};$href->{'city'};$href->{'state'};$href->{'zip'};$href->{'country'}\n"; 
	$msg .= $tmp;
	$tmp = "LABEL;POSTAL;ENCODING=QUOTED-PRINTABLE: ; ;";
	$tmp .= "$href->{'addr'}";
	if($href->{'city'} or $href->{'state'} or $href->{'zip'}) {
	    $tmp .= "=0D=0A=\n$href->{'city'} $href->{'state'} $href->{'zip'}";
	}
	if($href->{'country'}) {
	    $tmp .= "=0D=0A=\n$href->{'country'}"; 
	}
	$msg .= "$tmp\n";
    }
    if($href->{'phone'}) { 
	my (@parts) = split(/\n/, $href->{'phone'});
	foreach $smp (@parts) { 
	    if( $smp =~ /([\w|;]+)[=|;](.+)/) {
		$p = $1; $q=$2;
		$tmp = "TEL;$p:$q";
	    } elsif( $smp =~ /([A-Za-z]+)\s(.+)/) {
		$p = $1; $q=$2;
		$tmp = "TEL;$p:$q";
	    } else { $tmp = "TEL:$smp";}
	    $msg .= "$tmp\n";
	}
    }
    if($href->{'fax'}) {
	my (@parts) = split(/\n/, $href->{'fax'});
	foreach $smp (@parts) { 
	    if( $smp =~ /([\w|;]+)[=|;](.+)/) {
		$p = $1; $q=$2;
		$tmp = "TEL;$p:$q";
	    } elsif( $smp =~ /([A-Za-z]+)\s(.+)/) {
		$p = $1; $q=$2;
		$tmp = "TEL;$p:$q";
	    } else { $tmp = "TEL;FAX:$smp";}
	    $msg .= "$tmp\n";
	}
    }
    if($href->{'email'}){   $tmp = "EMAIL;INTERNET:$href->{'email'}\n"; $msg .= $tmp;	}
    if($href->{'com'}){
	$tmp = $href->{'com'}; $tmp =~ s/\n/=0D=0A=\n/g;
	$tmp = "ORG:$tmp\n"; $msg .= $tmp;  
    }
    if($href->{'hpage'}) {$tmp = "X-URL:$href->{'hpage'}\n"; $msg .= $tmp; }
    if($href->{'info'}) {
	$tmp = $href->{'info'}; $tmp =~ s/\n/=0D=0A=\n/g;
	my $imgurl = &getIUploaddirFullURL;
	$tmp =~ s/\\?\^o\^\//$imgurl\//g;	
	$tmp = "NOTE;ENCODING=QUOTED-PRINTABLE:$tmp\n"; $msg .= $tmp;	    	
    } 
    if($href->{'tag'}) { $tmp = "UID:$who-$href->{'tag'}\n"; $msg .= $tmp; }
    if($href->{'rev'}) {$rev =$href->{'rev'};}
    else {
	my @z = gmtime(time); 
	$rev =sprintf "%4d%02d%02dT%02d%02d%02dZ", $z[5]+1900,$z[4]+1,$z[3],$z[2],$z[1],$z[0];
    }
    $tmp = "REV:$rev\n"; $msg .= $tmp;
    $msg .= "VERSION:2.1\n";
    $msg .= "END:VCARD\n";
    $msg =~ s/\n/\015\012/g;
    return "$msg";
}
#============================================================================================================
sub mychop { my ($a) = (@_); if($a){$a =~ s/^\s+//g; $a =~ s/\s+$//g;} else {$a="";} $a;}
sub addressInAddressbook {
    my ($book, $entry) = (@_); # book is a reference to an array of anonymous hash tables.
    return 0 if $entry->{'outdated'};

    my ($href, $tmp, $ans, $matched, $k, $v, $emaila, $emailb, $mentry, %mentry, $reva, $revb);
    my @keys = ('lname','fname','phone','fax','addr','city','state','zip','com','hpage');
    $ans = 0;
    %mentry=();
    foreach $k (@keys) {  if(!exists $entry->{$k}) {$mentry{$k} = "";} else {$mentry{$k}=mychop($entry->{$k});}}
    $mentry=\%mentry;
    $emaila = $mentry->{'email'};
    $reva = $entry->{'rev'}; if(!$reva) { $reva = "";}
    foreach $href (@$book) {
	next if ! $href;
	next if $href->{'outdated'};
	foreach $k (@keys) {  if(!exists $href->{$k}) {$href->{$k} = "";}}
	$matched = 0;
	$emailb = mychop($href->{'email'});
	if($emaila and $emailb and $emaila eq $emailb) { # find a match entry
	    $matched = 1;
	    my $age = 0;
	    $revb = $href->{'rev'};
	    if($reva and $revb) {
		$age=cmpDateTime($reva, $revb); # -1 if reva<revb, 0 if reva=revb; 1 if reva>revb
		if($age == 0) { return 1;}
	    }
	    foreach $k (@keys) {
		my $a = mychop($href->{$k}); 
		my $b = $mentry->{$k};
		if($a ne $b) {  $matched =0; last;}
	    }
	    if(!$matched) {
		if($age < 0) { $entry->{'outdated'} = 1;}
		elsif($age > 0) { $href->{'outdated'} = 1;}
	    }
	    $ans = $matched;
	    last;
	} else {
	    $matched = 1;
	    foreach $k (@keys) {
		my $a = mychop($href->{$k}); 
		my $b = $mentry->{$k};
		if($a ne $b) {  $matched =0; last;}
	    }
	    if($matched) {$ans = 1;last;}
	}
    }
    $ans;
}
#============================================================================================================
sub newHeader {
    my ($cmd,$observerMG) = (@_);
    my ($header, $nbar, $js)= ("","","");
    $::my_favoriate_links = "";
    if(($::vm & 0x6) == 0) { ($js,$header) = &newHeader0(@_);} # not 'none' nor 'custom'
    else {
	my $v = $::vm;
	if(($v & 0x4) and $::calinfo{'hdr'}) { # use the customized header 
	    $header = customize_header(substImages($::calinfo{'hdr'}), @_);
	} elsif( $v & 0x2) {  # header=none
            ;
	} else {  # fallback to default header
	    ($js,$header) = &newHeader0(@_);
	}
    }
    if(($::vm & 0x8) == 0) { $nbar = &tabs_nbar(@_);}
    elsif( ($::vm & 0x800)) { ($::mnbar, $::vnbar) = &mini_tabs_nbar(@_); }

    my $code=<<END;
$::my_favoriate_links
$js
<table border=0 cellspacing=0 cellpadding=0 width="$::o{'tw'}%">
<tr><td width="100%">
<Form name=webcal action="$::o{'cginame'}" method=GET class="headerform">$::vmp
$header
</Form>
</td></tr></table>
$nbar
END
    ;
    return $code;
}
sub customize_header {
    my ($in, $cmd, $observeMG) = (@_);
    my ($who, $view, $ls, $date, $entry, $script, $orefB, $orefE, $mg, $wrap);
    my ($txt_clr, $logout, $log_in_out);
    my ($this_day, $color, $text_clr, $popa, $popb, $mylinks);
    $who = $::calinfo{'w'};$view = $::calinfo{'v'}; $ls = $::calinfo{'ls'}; $date = $::calinfo{'d'};
    $this_day = &getThemeColor;
    $color = $::themeColors[$this_day];
    $text_clr = "color=$color";

    #----- logo 
    if( $in =~ /<logo>/i) {
	my ($localdocA, $localdocB) = &getdocURL();
	my $logo ="$localdocA<img src=\"$::o{'imgdirurl'}/xebcal00${this_day}.gif\" width=152 height=43 border=0>$localdocB";
	$in =~ s/<logo>/$logo/i;
    }
    #----- version string
    if( $in =~ /<version>/i) {
	my $version_string = &getVersionString();
	$in =~ s/<version>/<a href=\"$::o{'cginame'}?c=version\"><span class=\"version\">$version_string<\/span><\/a>/i; #"
    }
    
    my $catfilter=0;
    #----- category filter
    if( $in =~ /<category_filter>/i and $::o{'category_filter'} and $::calinfo{'cfilter'} and not ($::vm &0x400000)) {
	my $cat;
	if($::calinfo{'category'} or $::calinfo{'hiddencat'}){$cat=$::calinfo{'hiddencat'} || $::calinfo{'category'};}else{$cat="";}
	my $catlist = build_catlist($who,'category',1, $cat); $catlist =~ s/fmList/fmListH/g;

	if($catlist) {my $smp=""; if($cat !~ /^\s*$/) {$smp="<img src=\"$::o{'imgdirurl'}/run.gif\" align=absmiddle border=0 width=24 height=8 title=\"\">";}
	    my $tmp = "<a href=\"javascript:openpopup('$::o{'cgimisc'}?cmd=scat','scat',460,300)\" class=\"transparent\"><font size=-1 $text_clr><span class=fmLabel>$::phr{'Category'}:</span></font></a>$smp<font size=1><br></font>$catlist";
	    $in =~ s/<category_filter>/$tmp/i;	
	    $catfilter=1;
	}
    }

    #----- calendar selection
    my $whichcalset=0;
    if( $in =~ /<calendar_selector>/i) {
	my ($entry, $script, $orefB, $orefE, $popa, $popb, $wrap) = &mkCalList($who, $text_clr, $observeMG);
	my $s=""; my $yopen=""; my $hiddencalselection="";
	if(($::vm & 0x1) == 0) {
	    if( ($::d{'remote_user'} ne 'anonymous' and	$::d{'remote_user'} ne 'nobody') and
		( $::d{'megaCal'} ne ""  or  ($::d{'remote_user'} and $who ne $::d{'remote_user'})) ) {
		my $me = $::d{'remote_user'}; my $alt= "$me: $::phr{'BackToCalendar'}";
		my $ghome= "<img src=\"$::o{'imgdirurl'}/spacer.gif\" width=4 height=1 border=0><a href=\"$::o{'cginame'}?c=get&w=$me&v=$view&ls=$ls&d=$date$::vmg\" class=\"transparent\"><img src=\"$::o{'imgdirurl'}/home.gif\" width=10 height=11 border=0 alt=\"$alt\" title=\"$alt\"></a>&nbsp;";
		$entry .= $ghome;
	    }
	    if($catfilter){$s="$popa<font size=-1 $text_clr><span class=fmLabel>$::phr{'Calendar'}:</span></font>$popb<font size=1><br></font>$entry";}
            else { $s="$popa<img src=\"$::o{'imgdirurl'}/yopen.gif\" width=25 height=16 border=0 align=bottom>$popb$entry"; }
	} else {
            my $w="";if($observeMG and $::d{'megaCal'}){$w=$::d{'megaCal'};}else{$w=$who;}
            $hiddencalselection="<input type=hidden name=w value=\"$w\">";
        } 
	$in =~ s/<calendar_selector>/$s$hiddencalselection/i;
        $whichcalset=1;
    }
    #----- calendar descriptive name
    if( $in =~ /<calendar_title>/i) {
	my $info = &getOwnerInfo($cmd, $observeMG, $color);
	$in =~ s/<calendar_title>/$info/i;	
    }

    #----- logout button
    if( $in =~ /<logout>/i) {
	$mylinks=&getMyFaviorateLinks($::d{'remote_user'});
	if($::d{'remote_user'} ne 'nobody'){$logout=$::phr{'Logout'};}
	else { $logout = "";}
	my $s = <<END;
<a href="$::o{'cginame'}?c=logout&w=$who&v=$view&ls=$ls&d=$date$::vmg"><b><span class="logout"><font $text_clr>$logout</font></span></b></a><img src="$::o{'imgdirurl'}/spacer.gif" width=4 height=1 border=0>$mylinks
END
    ;
	$in =~ s/<logout>/$s/i;		
    }
    if($in =~ /\\?\^o\^\/([^\s]+?)\.(gif|jpg|png|jpeg|bmp)/i) {
	my $irepository = "$::o{'imgdirurl'}/$::o{'uploadsubdir'}";
	$in =~ s/\\?\^o\^\/([^\s]+?)\.(gif|jpg|png|jpeg|bmp)/$irepository\/$1\.$2 border=0 align=left valign=top> /ig;
    }
    if(not $whichcalset) {
        my $w="";if($observeMG and $::d{'megaCal'}){$w=$::d{'megaCal'};}else{$w=$who;}
        my $v="<input type=hidden name=w value=\"$w\">";
        $in .= $v;
    }
    return $in;
}
#=====================================================================================================================
# used upto 0x800000

sub setViewMode {
    my $vm = 0;
    if($::calinfo{'view'}) {    
	my (@options, $t);
	@options=split(/,/, $::calinfo{'view'});
	foreach $t (@options) {
	    if( $t eq 'list1') { $::calinfo{'ls'} = 1; $vm |= 0x4000;}
	    elsif( $t eq 'list2') { $::calinfo{'ls'} = -1; $vm |= 0x2000;} 
	    elsif( $t eq 'list3') { $::calinfo{'ls'} = -1; $vm |= 0x2200; }
	    elsif( $t eq 'block') { $::calinfo{'ls'} = 0;}
	    elsif( $t eq 'day') { $::calinfo{'v'} = 1;}	    
	    elsif( $t eq 'week') { $::calinfo{'v'} = 2;}	    
	    elsif( $t eq 'month') { $::calinfo{'v'} = 3;}	    
	    elsif( $t eq 'year') { $::calinfo{'v'} = 4;}	    
	}

    }
    
    if($::calinfo{'listview'}) {  $::calinfo{'ls'} = -1; } 
    if($::calinfo{'ls'} and $::calinfo{'ls'} == 255) {
        if(defined $::calinfo{'dlist'}) {  $::calinfo{'ls'} = $::calinfo{'dlist'}; } else {$::calinfo{'ls'} = 0;}
    }
    
    if($::calinfo{'header'}) { 
	my (@options, $t);
	@options=split(/,/, $::calinfo{'header'});
	foreach $t (@options) {
	    if( $t eq 'none' or $t eq 'false') { $vm  |= 0x2;}
	    elsif( $t eq 'custom') { $vm  |= 0x4;}
	}
    }

    if( $::calinfo{'calendarselection'} ) {
	my $t = $::calinfo{'calendarselection'};
	if($t eq 'false' or $t eq 'none') { $vm |= 0x1;}
	elsif($t eq 'menu') { $::calinfo{'ulist'} = 4;}
	elsif($t eq 'entry') { $::calinfo{'ulist'} = -2;} 
    }
    if( $::calinfo{'categoryfilter'} ) {
	my $t = $::calinfo{'categoryfilter'};
	if($t eq 'false' or $t eq 'none') { $vm |= 0x400000;}
	else { $vm &= ~0x400000;}
    }

    my $nbar="";
    if($::calinfo{'nbar'}) { $nbar=$::calinfo{'nbar'};}
    elsif($::calinfo{'navigationbar'}) { $nbar=$::calinfo{'navigationbar'};}
    elsif($::calinfo{'navigationtable'}) { $nbar=$::calinfo{'navigationtable'};}
    if($nbar eq 'false') { $vm |= 0x8;}
    elsif($nbar eq 'mini') {$vm |= 0x808;}

    # used in listview2 and listview3 only
    if( ($::calinfo{'listviewnavigation'} and $::calinfo{'listviewnavigation'} =~ /month/i)) { $vm |= 0x400;}
    
    if($::calinfo{'quickadd'} and $::calinfo{'quickadd'} eq 'false') { $vm |= 0x10;}

    if($::calinfo{'clock'} and $::calinfo{'clock'} eq 'false') { $vm |= 0x20;}

    if($::calinfo{'elink'} and $::calinfo{'elink'} eq 'detail') { $vm |= 0x50;} # disable quickadd also

    # used in block/week view only 
    if($::calinfo{'busytable'} and $::calinfo{'busytable'} eq 'false') { $vm |= 0x80;}

    # used in block/day view only
    if($::calinfo{'monthtable'} and $::calinfo{'monthtable'} eq 'false') { $vm |= 0x100;}

    # turn off adding event 
    if($::calinfo{'edit'} and $::calinfo{'edit'} eq 'false') {$vm |= 0x1050; } # alter event-link also

    if((defined $::calinfo{'refresh'}) and 
       ($::calinfo{'refresh'} eq 'false' or $::calinfo{'refresh'} eq '0')) { $vm |= 0x80000; } # turn off auto refresh
    if(not $::calinfo{'x'}){$::calinfo{'x'}=0;}
    if($vm) {  
        my $oldx=0;
        if($::calinfo{'or'} and $::calinfo{'x'}) { $oldx = 0+$::calinfo{'x'};}
        $::calinfo{'x'}= $oldx | 0+$vm; 
    } else {
	my $dflag = 0;
	if($::calinfo{'d_e'} and $::calinfo{'d_e'} ne 'false') { $dflag = 0x8000;}
	if($::calinfo{'ddetail'}) {
	    if($::calinfo{'ddetail'} =~ /^d/i)  {  $dflag |= 0x10000;}
	    elsif($::calinfo{'ddetail'} =~ /^b/i)  {  $dflag |= 0x20000;}	    
	    else { $dflag |= 0x40000;}
	}
	if($::calinfo{'wdetail'}) {
	    if($::calinfo{'wdetail'} =~ /^d/i){ $dflag |= 0x100000;} else {  $dflag |= 0x200000;}
	} 
	if($::calinfo{'ydetail'} and $::calinfo{'ydetail'} =~ /^n/i) { $dflag |= 0x800000;} 
	
	if($dflag) {
	    if($::calinfo{'x'}) { $::calinfo{'x'} |= (0+$dflag);}
	    else { $::calinfo{'x'} = 0+$dflag;}
	}
    }
    $::calinfo{'x'} |= (0+$::calinfo{'xcode'}) if $::calinfo{'xcode'};

    if($::calinfo{'hx'}){ if(not $::calinfo{'ycode'}){ $::calinfo{'x'} &= ~4;}else{$::calinfo{'x'} |= 4;}}
    else { $::calinfo{'x'} |= 4 if $::calinfo{'ycode'};}

    if($::calinfo{'x'}) {
	if($::calinfo{'d_e'}) {
	    if($::calinfo{'d_e'} eq 'false') { $::calinfo{'x'} &= ~0x8000; }
	    else { $::calinfo{'x'} |= 0x8000;}
	} 
	if($::calinfo{'ddetail'}) {
	    if($::calinfo{'ddetail'} =~ /^d/i ) { $::calinfo{'x'} |= 0x10000;  $::calinfo{'x'} &= ~0x60000; $::d{'getall'}=1; }
	    elsif($::calinfo{'ddetail'} =~ /^b/i ) { $::calinfo{'x'} |= 0x20000;  $::calinfo{'x'} &= ~0x50000; $::d{'getall'}=1;} 
	    else { $::calinfo{'x'} |= 0x40000;  $::calinfo{'x'} &= ~0x30000; }
	} 
	if($::calinfo{'wdetail'}) { 
	    if($::calinfo{'wdetail'} =~ /^d/i) {$::calinfo{'x'} |= 0x100000; $::calinfo{'x'} &= ~0x200000; }
	    else {$::calinfo{'x'} |= 0x200000; $::calinfo{'x'} &= ~0x100000;} 
	}
	if($::calinfo{'ydetail'}) { 
	    if($::calinfo{'ydetail'} =~ /^n/i) {$::calinfo{'x'} |= 0x800000;} 
	    else {$::calinfo{'x'} &= ~0x800000;} 
	}
	if(defined $::calinfo{'refresh'}) {
	    if(($::calinfo{'refresh'} eq '0') or ($::calinfo{'refresh'} eq 'false')) { $::calinfo{'x'} |= 0x80000; }
	    else { $::calinfo{'x'} &= ~0x80000; }
	}
	my $x = $::calinfo{'x'};
	$::vm = $x; 
	if($::calinfo{'forget'} or $::calinfo{'anonymous'}) {  $x &= ~0x6000;}
	$::vmg="&x=$x";
	$::vmp="<input type=hidden name=x value=$x>";
    }
    if($::o{'category_filter'} and $::calinfo{'cfilter'} and ($::calinfo{'hiddencat'} or $::calinfo{'category'})){
	my $cat=$::calinfo{'hiddencat'} || $::calinfo{'category'}; 
	if($cat !~ /^\s*$/) {
	    my $tmp=urlencode($cat);
	    $::vmc = "&category=$tmp";
	    $::vmg .= $::vmc;
	    $::vmp .= "<input type=hidden name=category value=\"$cat\">";
	    $::catfilterpattern=$cat;
	    $::catfiltersub=sub{my ($c)=(@_);if($c and $c=~/^\s*$::catfilterpattern\s*$/i){return 1;}return 0;}
	}
    }

    if($::o{'search_filter'}  and ($::calinfo{'stopic'} or $::calinfo{'hiddensrch'} or $::calinfo{'srch'})){
	my ($srch, $tmp, $who, $ls, $v, $mg, $d, $w );
	if($::calinfo{'c'} eq "dosearch") { $srch = $::calinfo{'stopic'} || "";}
	else { $srch = $::calinfo{'stopic'} || $::calinfo{'hiddensrch'} || $::calinfo{'srch'}; }
	if($srch !~ /^\s*$/) {
	    $srch = &html_escape($srch, 0);
	    @::srchwords= &buildMExpr($srch); 
	    $tmp = &html_escape($srch,1);
	    $::vmp .= "<input type=hidden name=srch value=\"$tmp\">";
	    $::srchftrptn=$tmp;
	    $d=$::calinfo{'d'}; $ls=$::calinfo{'ls'}; $v=$::calinfo{'v'}; $w=$::calinfo{'w'};
	    if($::d{'megaCal'}){$mg="&mg=$::d{'megaCal'}";} else {$mg="";}
	    $::srchi=<<END;
<a href="$::o{'cginame'}?c=get&ls=$ls&w=$w&v=$v&d=$d$mg$::vmg" onclick="document.csearch.stopic.value=''"><span class="awarn">$::phr{'ClearSearch'}</span></a><img src="$::o{'imgdirurl'}/ran.gif" width=24 height=8 border=0 alt="" align=absmiddle>
END
    ;
	    $tmp=urlencode($srch);   $::vmc .= "&srch=$tmp";   $::vmg .= $::vmc;
#	    my $tmpp = join(' ', @::srchwords);
#	    $::srchn="<font color=#0000ff>$::phr{'Search_Results'}</font> ";
	}
    }

    if($::vm & 0x4000) { $::calinfo{'ls'} = 1;}
    elsif($::vm & 0x2000) { $::calinfo{'ls'} = -1; }

    if($::vm & 0x10) { # disable the quickadd button
	$::o{'qadd'} = "";
    } else {
	$::o{'qadd'} = "<font size=-2>&nbsp;&nbsp;<a href=\"javascript:qa()\"><span class=\"quickadd\">&nbsp;$::phr{'QuickAdd'}</span></a>&nbsp;&nbsp;</font>";
	if($::o{'block_move'}) {
	    my $who = $::calinfo{'w'};
	    my $url="$::o{'cginame'}?w=$who&c=bkm";
	    $::o{'qadd'} .= "<font size=-2>&nbsp;&nbsp;<a href=\"javascript:openpopup('$url','cats',640,500)\"><span class=\"quickadd\">$::phr{'BMove'}</span></a></font>";
	}
    }
}
sub html_escape {
    my ($str, $encode) =(@_);
    if($encode){ $str =~ s/&/&amp;/g; $str =~ s/</&lt;/g; $str =~ s/>/&gt;/g; $str =~ s/\"/&quot;/g;}  # encode
    else { $str =~ s/&lt;/</g; $str =~ s/&gt;/>/g; $str =~ s/&quot;/\"/g; $str =~ s/&amp;/&/g;}        # decode
    return $str;
}
#============================================================================================================
sub motd {
    my ($update_only)=(@_);
    if(!isadmin($::d{'remote_user'}) ) {
	my $msg ="You're not allowed to edit \"Message of the Day\".";
	if($update_only) { return(0, $msg);}
	calerror($msg, 0);
    }
    my($who, $motd, $action ,$view, $ls, $dt);
    $who = $::calinfo{'w'}; if (! $who) { $who=$::d{'remote_user'};}
    $motd = "$::o{'spooldir'}/.motd";
    $action = $::calinfo{'motdcmd'};
    $view= $::calinfo{'v'};
    $ls = $::calinfo{'ls'};
    $dt = $::calinfo{'d'};
    if(!$action or $action ne "doit") { # postform
	if($update_only) { return (0, "Cannot post form in update-only mode");}
	local ($/)=(undef);
	&headers("Web Calendar: Edit motd", " ");
	my $oldmotd="";
	my $upload="";
	if( -f "$motd") { my $fh = gensym; if(open($fh, "<$motd")) { $oldmotd = <$fh>;} close $fh;}
	if($::o{'allowImageUpload'}) {
	    my $iurl="$::o{'cgiupload'}?c=ui&w=$who";
	    $upload = "<a href=\"Javascript:openpopup(\'$iurl\','uls',500,400)\"><font size=1 color=#0000cc><span class=\"iupload\">$::phr{'IUpload'}</span></font></a>";
	}
	my $repos = "$::o{'imgdir'}/$::o{'uploadsubdir'}";
	my @list= listImgDirContents($repos, 1);
	if (scalar @list) {
	    my $surl="$::o{'cginame'}?c=simage&imgoffset=0&w=$who&the_form=motdc&the_elt=nmotd";
	    $upload .= "&nbsp;&nbsp;<a href=\"Javascript:openpopup(\'$surl\','imgs',500,600)\" style=\"color:green;background-color:#cccc00\"><font size=1><span class=\"iselect\">$::phr{'UsableImgs'}</span></font></a><br><br>";
	}
	print <<END;
<br>
<center>
<h2>Edit Message of the Day</h2>
<br>
<Form action="$::o{'cginame'}" method=POST name=motdc>$::vmp
<input type=hidden name=v value="$view">
<input type=hidden name=ls value="$ls">
<input type=hidden name=c value="motd">
<input type=hidden name=w value="$who">
<input type=hidden name=motdcmd value="doit">
<table bgcolor=$webcalConfig::r{'backgroundColor'} border=0 cellpadding=2 cellspacing=0 width="70%">
<tr><td align=center><b><font size=+1><span class="miscTitle">Message of the Day</span></font></b>&nbsp;&nbsp; $upload</td></tr>
<tr><td align=center><textarea name=nmotd cols=60 rows=10 class="fmText">$oldmotd</textarea></td></tr>
<tr><td align=center><b><input type=submit name=action value="$::phr{'Submit'}" class="fmBtnSt"> &nbsp;&nbsp;
<input type=button value="$::phr{'GoBack'}" onclick="history.go(-1)" class="fmBtnSt"></b>
</td></tr></table>
</center>
END
    ;
	&trailer(0,0);
    } else { #edit
	my $nmotd=$::calinfo{'nmotd'};
	$nmotd =~ s/^\s+//; $nmotd =~ s/\s+$//;
	if($nmotd eq "") { if( -f "$motd") { unlink "$motd";}}
	else { my $fh = gensym; if(open($fh, ">$motd")) { print $fh $nmotd;} close $fh;}
	if($update_only) { return(1, "Motd updated");}
	acknowledge($who, $view, $ls, $dt, "Motd updated, thank you", 'get');
	;
    } 
}
#===============================================================================================
%::mime_icons = (
		 # 1. image 
		 'gif'=>1,'jpg'=>1,'png'=>1,'jpeg'=>1,
		 'bmp'=>1,'ppm'=>1,'pnm'=>1,'rgb'=>1,
		 'ras'=>1,'pgm'=>1,'tiff'=>1,'tif'=>1,'jpe'=>1,
		 # 2. pdf
		 'pdf'=>2,
		 # 3. ps
		 'ps'=>3,'eps'=>3,
		 # 4. rtf
		 'rtf'=>4,
		 # 5. mp3
		 'mp3'=>5,
		 # 6. mpeg
		 'mpeg'=>6,'mpg'=>6,'mpe'=>6,
		 # 7. audio
		 'au'=>7,'wav'=>7,'af'=>7,'snd'=>7,
		 # 8. video
		 'avi'=>8,
		 # 9. quicktime
		 'qt'=>9,'mov'=>9,
		 # 10. flash
		 'swf'=>10, 'rf'=>10,
		 # 11. real audio/video
		 'ra'=>11,'ram'=>11,'rt'=>11,'rm'=>11,'rmm'=>11,'rp'=>11,
		 # 12. TeX
		 'tex'=>12,
		 # 13. MS spread sheet
		 'xls'=>13,
		 # 14. MS power point
		 'ppt'=>14,
		 # 15  MS word
		 'doc'=>15,
		 # 16. dvi
		 'dvi'=>16,
		 # 17. zip
		 'zip'=>17,
		 );
@::mime_icons = (
		 'url.gif',   # 0
		 'img.gif',   # 1
		 'pdf.gif',   # 2
		 'ps.gif',    # 3
		 'rtf.gif',   # 4
		 'mp3.gif',   # 5
		 'mpeg.gif',  # 6
		 'audio.gif', # 7
		 'video.gif', # 8
		 'qtime.gif', # 9
		 'flash.gif', # 10
		 'real.gif',  # 11
		 'tex.gif',   # 12
		 'xls.gif',   # 13
		 'ppt.gif',   # 14
		 'doc.gif',   # 15
		 'dvi.gif',   # 16
		 'zip.gif',   # 17
		 );

sub select_url_icon {
    my ($url) = (@_);
    my $id = 0;
    if($url =~ /\.([^\.]{2,4})$/) {
	my $suffix= lc($1);
	if(defined $::mime_icons{$suffix}) {$id =$::mime_icons{$suffix};}
    }
    return $::mime_icons[$id];
}
#===============================================================================================
sub customized_freq {
    my ($occurs) = (@_);
    if(substr($occurs,0,1) eq 'Z' and $occurs =~ /^Z(.+),(\d+),(\d*)/) {
	my($r, $c, $d) = ($1, $2, $3);
	my $str = "";
	if($r eq 'D') { if($c==1){$str="Daily";} else{ $str = "Every $c days";}}
	elsif($r eq 'MD') { if($c==1){$str="Monthly";} else {$str = "Every $c month on the same day";}}
	elsif($r eq 'MWD') { if($c==1){$str="Monthly";} else{$str = "Every $c month on the same weekday";}}
	elsif($r eq 'MND') { $str = "Every $c month on the same day counting from the end of the month";}
	elsif($r eq 'MNW') { $str = "Every $c month on the same weekday counting from the end of the month";}
	elsif($r eq 'X') { $str = "Every $c weekdays";}
	elsif($r eq 'W') {
	    my $w = ""; 
	    if($d & 0x1){$w .= $::phr{'Su'};} if($d & 0x2){$w .= $::phr{'Mo'};} 
	    if($d & 0x4){$w .= $::phr{'Tu'};} if($d & 0x8){$w .= $::phr{'We'};} 
	    if($d & 0x10){$w .= $::phr{'Th'};}if($d & 0x20){$w .= $::phr{'Fr'};} 
	    if($d & 0x40){$w .= $::phr{'Sa'};} 
	    if($c==1){$str="Weekly on $w";} elsif($c==2){$str="Biweekly on $w";}
	    else {$str = "Every $c weeks on $w";}
	}
	return ( $occurs, $str);
    }
    return ('Custom', "=======$::phr{'More'}========");
}
sub cfreq { # display a customized recurring frequency form.
    my ($ooc, $ntt, $script, $body);
    $ooc = $::calinfo{'ooc'};   $ntt = $::calinfo{'ntt'};

    $body =" onload=\"pform('$ooc')\"";

    &headers("Customized Recurring Rule"," ",0,0,0,$body);

    my ($ndv, $nmv, $nwv, $nwdv)=("","","","");
    my ($dwd1, $dwd2) =("","");
    my ($ndva, $nmva, $nwva)=("","","");
    my ($dwd1a, $dwd2a) =("","");
    my ($d0,$d1,$d2,$d3,$d4,$d5,$d6)=("","","","","","","");
    my( $bd0, $bd1, $bd2)=(0,0,0);
    if($ooc and $ooc =~ /^Z(.+),(\d+),(\d*)/) {
	my ($r, $c, $d) = ($1, $2, $3);
	if($r eq 'D') {$ndv=$c; $bd0=2;}
	elsif($r eq 'MD') { $nmv=$c; $dwd1="checked"; $bd1=2;}
	elsif($r eq 'MWD') {$nmv=$c; $dwd2="checked"; $bd1=2;}	
	elsif($r eq 'MND') {$nmva=$c; $dwd1a="checked"; $bd1=2;}	
	elsif($r eq 'MNW') {$nmva=$c; $dwd2a="checked"; $bd1=2;}	
	elsif($r eq 'W') { 
	    $nwv=$c; $bd2=2;
	    if($d & 0x1){$d0="checked";} if($d & 0x2){$d1="checked";} if($d & 0x4){$d2="checked";}
	    if($d & 0x8){$d3="checked";} if($d & 0x10){$d4="checked";} if($d & 0x20){$d5="checked";}
	    if($d & 0x40){$d6="checked";}
	}
	elsif($r eq 'WD') { 
	    $nwdv = $c;
	}
    }
    print <<EOF
<center>
<h2>Please Select a Recurring Rule</h2>
</center>
<form method=post name=fd onsubmit="return cfreqD()">
<table border=0 cellspacing=0 cellpadding=$bd0><tr><td align=center bgcolor="#0000ff">
<table border=0 width=640 cellspacing=0 cellpadding=4 bgcolor="#ccccff">
<tr><td nowrap><font size=2><span class="fmLabel">Occurs every </span>
<input type=text name=nd value="$ndv" size=3 maxlength=4 class="fmEntry">
<span class="fmLabel">days for</span>
<input type=text name=ntt value="$ntt" size=3 maxlength=4 class="fmEntry">
<span class="fmLabel">times</span></font></td>
<td align=right><font size=2><b><input type=button  class="fmBtnSt" value="$::phr{'Select'}" onclick="cfreqD();"></b></font></td></tr>
</table>
</td></tr></table>
</form>

<br>

<form method=post name=fm onsubmit="return cfreqM()">
<table border=0 cellspacing=0 cellpadding=$bd1><tr><td align=center bgcolor="#0000ff">
<table border=0 width=640 cellspacing=0 cellpadding=4 bgcolor="#ccffcc">
<tr><td nowrap><font size=2><span class="fmLabel">Occurs every</span>
<input name=nm type=text value="$nmv" size=3 maxlength=4 class="fmEntry">
<span class="fmLabel">months on the</span>
<span class="fmLabel">same</span> <input type=radio name=dwd value=1 $dwd1 class="fmRadio"> <span class="fmLabel">day &nbsp;</span>
 <input type=radio name=dwd value=2 $dwd2 class="fmRadio"> <span class="fmLabel">weekday for </span>
<input type=text name=ntt value="$ntt" size=3 maxlength=4 class="fmEntry">
<span class="fmLabel">times </span></font></td>
<td align=right><font size=2><b><input type=button value="$::phr{'Select'}" onclick="cfreqM();" class="fmBtnSt"></b></font></td></tr>
</table>
</td></tr></table>
</form>

<br>
<form method=post name=fmn onsubmit="return cfreqMN()">
<table border=0 cellspacing=0 cellpadding=$bd1><tr><td align=center bgcolor="#0000ff">
<table border=0 width=640 cellspacing=0 cellpadding=4 bgcolor="#ccccaa">
<tr><td nowrap><font size=2><span class="fmLabel">Occurs every</span>
<input name=nm type=text value="$nmva" size=3 maxlength=4 class="fmEntry">
<span class="fmLabel">months on the</span>
<span class="fmLabel">same</span> <input type=radio name=dwd value=1 $dwd1a class="fmRadio"><span class="fmLabel"> day &nbsp; </span>
 <input type=radio name=dwd value=2 $dwd2a class="fmRadio"><span class="fmLabel"> weekday 
for </span>
<input type=text name=ntt value="$ntt" size=3 maxlength=4 class="fmEntry">
<span class="fmLabel">times, count backwords</span></font></td>
<td align=right><font size=2><b><input type=button class="fmBtnSt" value="$::phr{'Select'}" onclick="cfreqMN();"></b></font></td></tr>
<tr><td colspan=2><font size=2 color=blue><span class="fmLabel">
(If the event is scheduled on Jan. 28th, and occurs on the same day every 2 months for 4 times, then the event will occur
 on the 4th day counting backwards from the end of the month on March, May and July.)
</span></font></td></tr> 
</table>
</td></tr></table>
</form>
<br>

<form method=post name=fw onsubmit="return cfreqW()">
<table border=0 cellspacing=0 cellpadding=$bd2><tr><td align=center bgcolor="#0000ff">
<table border=0 width=640 cellspacing=0 cellpadding=4 bgcolor="#ffcccc">
<tr><td nowrap><font size=2><span class="fmLabel">Occurs every </span>
<input type=text name=nw value="$nwv" size=3 maxlength=4 class="fmEntry">
<span class="fmLabel">weeks on</span>
 <input type=checkbox name=d0 value=1 class="fmRadio" $d0><span class="fmLabelS">Su&nbsp;</span>
 <input type=checkbox name=d1 value=2 class="fmRadio"$d1><span class="fmLabelS">Mo&nbsp;</span>
 <input type=checkbox name=d2 value=4 class="fmRadio"$d2><span class="fmLabelS">Tu&nbsp;</span>
 <input type=checkbox name=d3 value=8 class="fmRadio" $d3><span class="fmLabelS">We&nbsp;</span>
 <input type=checkbox name=d4 value=16 class="fmRadio" $d4><span class="fmLabelS">Th&nbsp;</span>
 <input type=checkbox name=d5 value=32 class="fmRadio" $d5><span class="fmLabelS">Fr&nbsp;</span>
 <input type=checkbox name=d6 value=64 class="fmRadio" $d6><span class="fmLabelS">Sa&nbsp;</span>
<span class="fmLabel">for</span> <input type=text  class="fmEntry" name=ntt value="$ntt" size=3 maxlength=4> 
<span class="fmLabel">weeks</span>
</font></td>
<td align=right><font size=2><b><input type=button value="$::phr{'Select'}" onclick="cfreqW();" class="fmBtnSt"></b></font></td></tr>
</table>
</td></tr></table>
</form>
<br>

<form method=post name=fwd onsubmit="return cfreqWD()">
<table border=0 cellspacing=0 cellpadding=$bd0><tr><td align=center bgcolor="#0000ff">
<table border=0 width=640 cellspacing=0 cellpadding=4 bgcolor="#ccccff">
<tr><td nowrap><font size=2><span class="fmLabel">Occurs every </span>
<input type=text name=nwd value="$nwdv" size=3 maxlength=4 class="fmEntry">
<span class="fmLabel">weekdays for</span>
<input type=text name=ntt value="$ntt" size=3 maxlength=4 class="fmEntry">
<span class="fmLabel">times</span></font></td>
<td align=right><font size=2><b><input type=button  class="fmBtnSt" value="$::phr{'Select'}" onclick="cfreqWD();"></b></font></td></tr>
</table>
</td></tr></table>
</form>

<center>
<b><a href="javascript:self.close()"><font color=blue><b><span class="fmLabel">Close</span></b></font></a></b>
</center>
EOF
    ;
    &trailer(0,0);
}
#===============================================================================================
sub wdayoffsets {
    my ($in) =(@_); my($i, $t, @a); @a=(0, 0, $in, 0,0,0,0,0,0,0); $t=0;
    for($i=0; $i < 7; $i++) { if($in & (1<<$i)){$t++;} $a[3+$i]=$t; } 
    return(@a);
}
#===============================================================================================
sub calmatch16 {
    use integer;
    my ($today, $date, $repeat, $exception, $kind, $word, $c1, $c2) =(@_);
    my ( $i, $tm, $td, $ty, $dm, $dd, $dy, $nth, $elength, $tmp,
	 $smp, $ump, $twday, $wday, $occ, $modulo, $wdaymask, @maskary);

    if($word eq 'W') { @maskary = wdayoffsets($c2); $wdaymask=$c2;} else { $wdaymask=0;}

    if(defined $exception) { $elength = 0+@{$exception}; } else {$elength = -1;}

    if($today eq $date) {			# today is the day, check for exceptions
	my $eoffset=1;      
	if($word eq 'X') { 
	    ($tm, $td, $ty)=split(/\//, $today);
	    $twday = wday($tm-1, $td, $ty);	# weekday for today
	    return 0 if $c2 != $twday; 
	} elsif($wdaymask) {			# not on all weekdays
	    ($tm, $td, $ty)=split(/\//, $today);
	    $twday = wday($tm-1, $td, $ty);	# weekday for today
	    return 0 if (((1 << $twday) & $wdaymask) == 0);
	    $eoffset = $maskary[3+$twday];
	}
	if($elength > 0) {
	    for ($i=0; $i <$elength; $i++) {
		if( abs($exception->[$i]) == $eoffset) {
		    if($kind != 2 or $exception->[$i] > 0) { return 0; }
		}
	    }
	}
	return 1;
    } elsif ($repeat and $repeat > 0) {
	($tm, $td, $ty)=split(/\//, $today);
	($dm, $dd, $dy)=split(/\//, $date);
	if($dy > $ty or ( $dy == $ty and ($dm > $tm or ($dm == $tm and $dd > $td)))) { return 0; }
	$tm--; $dm--;

	if($word eq "D") {
	    $modulo=$c1;
	    $nth = ndays($tm, $td, $ty, $dm, $dd, $dy)-1;
	    if(($nth % $modulo) != 0) { return 0;}
	    $nth =($nth+$modulo)/$modulo; if( $nth > $repeat) { return 0; }
	    if($elength > 0) {
		for ($i=0; $i <$elength; $i++) {
		    if( abs($exception->[$i]) == $nth) {
			if($kind != 2 or $exception->[$i] > 0) { return 0; } 
		    }
		}
	    }
	    return $nth;
	} elsif($word eq "MD") {
	    if($td != $dd) { return 0; }
	    $tmp = nmonths($tm, $ty, $dm, $dy);
	    my $cnt = ($tmp -1)/$c1;
	    if($tmp != ($cnt * $c1 + 1) or $tmp > $repeat * $c1) { return 0;}
	    $cnt += 1;
	    if($elength > 0) {
		for ($i=0; $i <$elength; $i++) {
		    if( abs($exception->[$i]) == $cnt) { 
			if($kind != 2 or $exception->[$i] > 0) { return 0; }
		    }
		}
	    }
	    return ($cnt);
	} elsif($word eq "MWD") {
	    $tmp = nmonths($tm, $ty, $dm, $dy);
	    my $cnt = ($tmp -1)/$c1;
	    if($tmp != ($cnt * $c1 + 1) or $tmp > $repeat * $c1) { return 0;}
	    $twday = wday($tm, $td, $ty);	# weekday for today
	    $wday =  wday($dm, $dd, $dy);	# weekday of event
	    if($twday == $wday) {
		$cnt += 1;
		my ($code, $tcode);
		$code = $dd % 7; if($code==0 ){ $code = 7;}
		$tcode = $td % 7; if($tcode==0 ){ $tcode = 7;}
		$smp = (($td - $tcode)/7);
		$ump = (($dd - $code)/ 7);
		if($smp != $ump) { return 0 ; }
		if($elength > 0) {
		    for ($i=0; $i <$elength; $i++) {
			if( abs($exception->[$i]) == $cnt) {
			    if($kind != 2 or $exception->[$i] > 0) { return 0; }
			}
		    }
		}
		return ($cnt);
	    }
	    return 0;
	} elsif($word eq "MND") {
	    $tmp = nmonths($tm, $ty, $dm, $dy);
	    my $cnt = ($tmp -1)/$c1;
	    if($tmp != ($cnt * $c1 + 1) or $tmp > $repeat * $c1) { return 0;}
	    my ($mxdays, $ndb, $tt); $mxdays= ndays_in_month($dm, $dy); $ndb = $mxdays - $dd;
	    $mxdays = ndays_in_month($tm, $ty); $tt = $mxdays - $ndb;
	    if($td != $tt or $tt <= 0) { return 0; }
	    $cnt += 1;
	    if($elength > 0) {
		for ($i=0; $i <$elength; $i++) {
		    if( abs($exception->[$i]) == $cnt) { 
			if($kind != 2 or $exception->[$i] > 0) { return 0; }
		    }
		}
	    }
	    return ($cnt);
	} elsif($word eq "MNW") {
	    my ($code, $codet);
	    $tmp = nmonths($tm, $ty, $dm, $dy);
	    my $cnt = ($tmp -1)/$c1;
	    if($tmp != ($cnt * $c1 + 1) or $tmp > $repeat * $c1) { return 0;}
	    $twday = wday($tm, $td, $ty);	# weekday for today
	    $wday =  wday($dm, $dd, $dy);	# weekday of event
	    if($twday == $wday) {
		my ($mxdays, $nth, $mth);
		$mxdays = ndays_in_month($dm, $dy);
		$nth =  1 + ($mxdays-$dd)/7;	# the nth weekday, counting backwards
		$mxdays = ndays_in_month($tm, $ty);
		$mth =  1 + ($mxdays-$td)/7;	# the nth weekday, counting backwards
		if($nth != $mth) { return 0 ; }
		$cnt++;
		if($elength > 0) {
		    for ($i=0; $i <$elength; $i++) {
			if( abs($exception->[$i]) == $cnt) {
			    if($kind != 2 or $exception->[$i] > 0) { return 0; }
			}
		    }
		}
		return ($cnt);
	    }
	    return 0;
	} elsif($word eq 'W') {
	    $twday = wday($tm, $td, $ty);	# weekday for today
	    return 0 if (((1 << $twday) & $wdaymask) == 0);
	    $wday = wday($dm, $dd, $dy);	# weekday of event
	    $nth = ndays($tm, $td, $ty, $dm, $dd, $dy);
	    my $wknum = ($nth+$wday-$twday)/7;
	    my $cnt = $wknum / $c1;
	    if($cnt * $c1 != $wknum) { return 0; }
	    
	    $tmp = $cnt * $maskary[9] + $maskary[3+$twday];
	    if($tmp > $repeat) { return 0;}
	    
	    if($elength > 0) {
		for ($i=0; $i <$elength; $i++) {
		    if( abs($exception->[$i]) == $tmp) {
			if($kind != 2 or $exception->[$i] > 0) { return 0; }
		    }
		}
	    }
	    return ($tmp);
	} elsif($word eq 'X') {
	    use integer;
	    $twday = wday($tm, $td, $ty);	# weekday for today
	    return 0 if $twday == 0 or $twday == 6; 
	    $wday = $c2; #$wday = wday($dm, $dd, $dy);	# weekday of event
	    $nth = ndays($tm, $td, $ty, $dm, $dd, $dy);
	    my $nwks = ($nth-1)/7; 
	    my $nwdays = $nwks * 5 + ($twday - $wday); if($twday <$wday) {$nwdays += 5;}
	    my $mod  = $nwdays % $c1;
	    return 0 if $mod;
	    my $tmp = 1+($nwdays / $c1);
	    if($tmp > $repeat) { return 0;}
	    
	    if($elength > 0) {
		for ($i=0; $i <$elength; $i++) {
		    if( abs($exception->[$i]) == $tmp) {
			if($kind != 2 or $exception->[$i] > 0) { return 0; }
		    }
		}
	    }
	    return ($tmp);
	}
    }
    return(0);
}
#===============================================================================================
sub user_defined_color_pairs {
    my ($ekind) = (@_);
    my (@pairs) = ($::calinfo{'apair'}, $::calinfo{'tpair'}, $::calinfo{'mpair'}, $::calinfo{'spair'});
    my ($des, $opt);
    $opt = $pairs[0]; $pairs[0] = $pairs[$ekind-1];  $pairs[$ekind-1] = $opt;
    my @twos =();
    map { push @twos, $_ if $_;} @pairs;
    $des = join("|----,,|", @twos);
    $opt = "";
    if($des) {
	my (@ary) = split('\|', $des);
	my ($tmp, $lab, $fgbg);
	foreach $tmp (@ary) {
	    ($lab, $fgbg) = split(/,/, $tmp, 2);
	    if($lab and $fgbg) { 
		$opt .= "<option value=\"$fgbg\">$lab";
	    }
	}
    }
    if($opt) {
	return 
 "<font size=1 color=red><select name=clrpair class=\"fmList\" onChange='javascript:setclrpair()'><option value=\"\">?????$opt</select></font>";
    } 
    return "";
}
sub cpair {
    my $ekind = $::calinfo{'e'};
    my ($ee,$i, $j);
    if($ekind eq 'a') { $ee = "<font color=$::o{'tclra'}>$::phr{'Appointment'}</font>";}
    elsif($ekind eq 't') { $ee = "<font color=$::o{'tclrt'}>$::phr{'Todo'}</font>";}
    elsif($ekind eq 'm') { $ee = "<font color=$::o{'tclrm'}>$::phr{'Meeting'}</font>";}
    elsif($ekind eq 's') { $ee = "<font color=$::o{'tclrs'}>$::phr{'Special'}</font>";}
    else { calerror("Invalid event type", -1); } # should never be here
    &headers(undef, " ",0,0,0,"onLoad=\"doinitfgbgpair('$ekind')\"");
    print <<END;
<center><br><b><u>$::phr{'PredefineColorPairs'} $ee</u></b>
<p>
<form method=post name=webcalo onsubmit="return dosubmitfgbg('$ekind');">
<input type=hidden name=e value=$ekind>
<table border=0 cellspacing=0 cellpadding=0>
END
    ;
    for($i=0; $i<10; $i++) {
	
	print <<END;
<tr>
<td><span class="fmLabel">$::phr{'Label'}:</span> <input name="lab$i" type=text size=10 maxlength=10 class="fmEntry"></td>
<td><span class="fmLabel">&nbsp;$::phr{'Fg'}:</span>
 <input  class="fmEntry" name="c${i}fg" type=text size=8 maxlength=8 onChange="showclrpair($i)"></td>
<td><span class="fmLabel">&nbsp;$::phr{'Bg'}: </span><input name="c${i}bg" type=text class="fmEntry" size=8 maxlength=8 onChange="showclrpair($i)"></td>
<td>&nbsp;&nbsp;<a href="javascript:void(0)" onclick="openpopup('$::o{'cginame'}?c=showclrc$i','clrs',500,480)"><img src="$::o{'imgdirurl'}/clr.gif" width=20 height=9 border=0 title="colors" alt="colors"></a>
</tr>
END
    ;
    }
    print <<END;
<tr><td colspan=4 align=center><b><br><font color=red><input type=button class="fmBtn" value="$::phr{'Submit'}"
onclick="dosubmitfgbg('$ekind')"></font>&nbsp;&nbsp;&nbsp;
<input type=button value="$::phr{'Close'}" class="fmBtn" onclick="self.close()"></b></td></tr>
</table></center>
END
    ;
    &trailer(0,0);
}
#===============================================================================================
sub css_class1{
    my ($in, $hashref)=(@_);
    my (@all, %all,$name,$sname, $k, $v);
    @all = split(/,/, $in); %all=();
    foreach $k (@all) {
        ($name, $sname) = split(/:/, $k);
        if($name =~ /^w\-.+\-sCs\-(.+)$/) { $all{$1} = $name;};
    }
    return  map { $hashref->{$_}= $all{$_} } (keys %all);
}

sub user_defined_css {
    my($name, $style, $example, $code)=(@_); $style="" if not $style;
    my ($content, $who, @list, %hash, $sample, $n, $v, $sid);
    $who= $::calinfo{'w'}; $content=""; $sample=$sid="";
    read_in_css($who, 0);
    %hash=();
    map { css_class1($_, \%hash) } (sort keys %::css);
    @list = map { ($_, $hash{$_}) } (sort keys %hash);
    if(0+@list > 0 or $style) {
        if($style) {
	    my ($nam, $value)=extract_cal_css_name($style);
	    if($nam ne $who) { push @list, "$nam:$value", $style;}
	}
        $content=select_valueV($name, $style, $code, ('??????', "", @list));
    }
    if($example) {
	while( defined ($n = shift @list)) {
	    $v = shift @list; $sample .= "<b>$n:</b> <span class=\"$v\">Sample Text ABCD abcd 0123</span><br><br>";
	}
	if($sample) { $sid = addtip("<b>Font Samples</b><br><br> $sample"); }
    }
    return ($content, $sid);
}

sub default_css_setup {
    my ($who, @list, @ary, $i, $j, $len,%hash);
    $who= $::calinfo{'w'};
    @list=(0,0,0,0);
    read_in_css($who, 0);
    %hash=();   map { css_class1($_, \%hash) } (keys %::css);
    @ary = (sort values %hash); $len = scalar(@ary);
    for($i=1;$i<=4;$i++) {
	my $tmp = "css$i"; $tmp=$::calinfo{$tmp};
	if($tmp) {for($j=0; $j<$len; $j++) { if($tmp eq $ary[$j]){$list[$i-1]=$j+1; last;}}}
    }
    return @list;
}
sub make_style_sheet {
    my ($who) = (@_);
    my ($content, $memb, @mlist, $all, %marks, $file);
    $content="";
    $ = time;
    if(!$who) {$who= $::calinfo{'w'} || $::d{'remote_user'} || "_-_";}
    $file = "$::o{'spooldir'}/$who/css";
    if( -f "$file") { $::mycss=""; doReadFile($file); $all = $::mycss; } else {$all="";}
    if($::d{'megaCal'} ne "") { $all .= ":" . $::d{'megaCal'};}
    @mlist = split(/[:,]+/,$all); %marks=();
    for $memb (@mlist) {
	$memb =~ s/\s+//g;
	if(! $marks{$memb} and $memb ne $who ) { 
	    $marks{$memb}=1; 
	    my ($prop, $jnk) = make_css($memb,0); 
	    $content .= $prop;
	}
    }
    if($::o{'corporate_calendar'}) {
	@mlist = split(/[:,]+/, $::o{'corporate_calendar'});
	for $memb (@mlist) {
	    $memb =~ s/\s+//g;
	    if(! $marks{$memb} and $memb ne $who ) {
		$marks{$memb}=1; 
		my ($prop, $jnk) = make_css($memb,0); 
		$content .= $prop;
	    }	
	}
    }
    $::style_sheet = $content;
    ($::style_sheet_self, $::style_sheet_self_default) = make_css($who,1);
    # update system style sheet if necessary
    make_system_css();
}

sub make_system_css { # 
    my $cssdir = "$::o{'imgdir'}/$::o{'stylesheetdir'}";
    my ($cssfile, $sysfile, $pref);
    $pref = ""; $cssfile = "";
    if($::calinfo{'dcsf'}) { 
	$pref = $::calinfo{'dcsf'};
	if( ! -f "$::o{'cgidir'}/$pref" ) { $pref = "";}
    }
    if(! $pref) { $pref = $::o{'cssFile'} || 'default.css';}
    $sysfile = "$::o{'cgidir'}/$pref";
    if( -f $sysfile) {
	$cssfile = "$cssdir/nobody-_-$pref";
	if( ($pref and -f $sysfile) and ((! -f $cssfile ) or (-M "$sysfile") < ( -M $cssfile))) {
	    my $content= read_file_content($sysfile);
	    my $style=<<END;
$content
A.transparent:hover {background-color:transparent;}
END
    ;
	    write_file($cssfile, $style);
	}
    }
    if( $cssfile and -f $cssfile) {
	$::style_sheet_system =
	    "<LINK REL=\"stylesheet\" TYPE=\"text/css\" HREF=\"$::o{'imgdirurl'}/$::o{'stylesheetdir'}/nobody-_-$pref\">\n";
    } else {
	$::style_sheet_system =<<END;

<STYLE TYPE="text/css"> 
<!--
A.transparent:hover {background-color:transparent;}
-->
</STYLE>

END
    ;
    }
}

sub make_css {
    my ($user,$flag) =(@_);
    my $style_sheet = "";
    my $sheet_default = ""; 
    my $dir = "$::o{'spooldir'}/$user";
    if($user and -d "$dir") {
	my $css1 = "$::o{'imgdir'}/$::o{'stylesheetdir'}/${user}.css";
	my $cs1 = "$dir/css.css"; 
	my $css2 = "$::o{'imgdir'}/$::o{'stylesheetdir'}/${user}-default.css";
	my $cs2 = "$dir/default.css"; 
	if((! -f "$css1") or ((-f "$cs1") and ((-M "$cs1") < (-M "$css1")))) {
	    generate_sheet($user);
	}
	if( ( -f $cs2) and (! -f $css2) or  ((-f "$cs2") and ((-M "$cs2") < (-M "$css2")))) {
	     generate_sheet_default($user); 
	 }
	elsif ( ! -f $cs2) {
	    unlink $css2 if -f $css2;
	} 

	if( -f $css1) {
	    $style_sheet = "<LINK REL=\"stylesheet\" TYPE=\"text/css\" HREF=\"$::o{'imgdirurl'}/$::o{'stylesheetdir'}/${user}.css\">\n";
	}
	if($flag and -f $css2 and (not $::calinfo{'dcsf'} or $::calinfo{'dcsf'} =~ /\-default\.css/)) {
	    $style_sheet .= "<LINK REL=\"stylesheet\" TYPE=\"text/css\" HREF=\"$::o{'imgdirurl'}/$::o{'stylesheetdir'}/${user}-default.css\">\n";	    
	    $sheet_default = " \n";
	}
    }
    return ($style_sheet, $sheet_default);
}
sub generate_sheet {
    my ($user) =(@_);
    my $sheet = read_in_css($user, 1);
    my $file = "$::o{'imgdir'}/$::o{'stylesheetdir'}/${user}.css";
    write_file($file, $sheet );
}
sub generate_sheet_default {
    my ($user) =(@_);
    my $default = read_in_default_css($user);
    my $file = "$::o{'imgdir'}/$::o{'stylesheetdir'}/${user}-default.css";    
    if($default) {  write_file($file,  $default );}
    else { unlink $file if -f $file;}
}
sub write_file {
    my($file, $content) = (@_);
    if($file =~ /^(\/.+)$/ ) { $file = $1;}
    my $FILEL=gensym;
    if(sysopen($FILEL, "$file", O_WRONLY | O_CREAT)) {
	&webcalLock::doflock( \*$FILEL, LOCK_EX, "$file") or
	    &calerror("Cannot lock file '$file': $!\n");     
	truncate($FILEL, 0);
	print $FILEL $content;
	&webcalLock::doflock( \*$FILEL, LOCK_UN, "$file") or 
	    &calerror("Cannot unlock file '$file': $!\n"); 
	close $FILEL;	  
	return 1;
    }    
    return 0;
}

sub read_in_default_css {
    my ($u) = (@_);
    my ($content, $cal, $file);
    $u = untaintname($u);
    $cal = "$::o{'spooldir'}/$u";
    $file = "$cal/default.css";
    $content = "";
    if( -d $cal and -f $file){$content = read_file_content($file);} 
    return ($content);
}

sub read_file_content {
    my ($path)= (@_);
    my $content = "";
    if( $path and -f $path) {
        local ($/) = (undef);
	my $fh = gensym;
	if(open($fh, "<$path")) {
	    &webcalLock::doflock(\*$fh, LOCK_SH, "$path");
	    $content = <$fh>;
	    &webcalLock::doflock(\*$fh, LOCK_UN, "$path");
	    close $fh;
	}
    }
    return $content;
}

sub read_in_css {
    my ($content, $cal, $file);
    my ($u, $fmt) = (@_);
    $u = untaintname($u);
    $cal = "$::o{'spooldir'}/$u";
    $file = "$cal/css.css";
    $content = " ";
    if( -d "$cal" and -f "$file") {
	my ($k,$v, $irepository);
	%::css =();  &doReadFile("$file");
	if($fmt) {
	    $irepository = "$::o{'imgdirurl'}/$::o{'uploadsubdir'}";
	    foreach $k (reverse sort keys %::css) {
		my (@keys, $key, $a);
		$v = $::css{$k}; $v =~ s/\\?\^o\^\/([^\s]+?)\.(gif|jpg|png|jpeg|bmp)/$irepository\/$1\.$2/ig;
		if( not &toplevelClass($k) ) {
		    $k =~ s/,\s*/,\./g; $k =~ s/_/\-/g;
		    $key = ".$k";
		} else {
		    $key = $k;
		}
		$content .= "$key {$v}\n";
	    }
	}
    }
    return $content;
}
sub toplevelClass {
    my ($name) = (@_);
    $name = lc($name);
    return 1 if $name =~ /\./;
    # only the A and H2 tags is used implicitly without a class name in webcal
    return 1 if ($name eq "a" or $name =~ /^a:/ or $name =~ /^h\d$/);
    return 0;
}
#===============================================================================================
sub insert_to_all {
    my ($eventsRef, $src) = (@_);
    my (%excludes, @cals, $cal, $path, @excludes, $theE, $href, $tmp);
    @excludes = split(/[,: ]+/, "$::o{'corporate_calendar'}:$src");
    map { $excludes{$_} = 1; } (@excludes);
    my $DIRb= gensym;
    if (opendir($DIRb, $::o{'spooldir'})) {
	@cals = readdir($DIRb); closedir($DIRb);
	foreach $cal (@cals) {
	    $path = "$::o{'spooldir'}/$cal";
	    if( !$excludes{$cal} and -d $path and -f "$path/info" and -f "$path/data" and ! -f "$path/no_ccal") {
		my $fhhh = gensym;
		if(sysopen($fhhh, "$path/data",O_WRONLY | O_CREAT, 0644) and 
		   &webcalLock::doflock( \*$fhhh, LOCK_EX, "$path/data")) {
		    my $total = do "$path/data";
		    truncate($fhhh, 0);		
		    print $fhhh "\@::caldata = (\n";
		    for $href (@::caldata) {
			$tmp=print1Entry($href);
			print $fhhh $tmp;
		    }
		    $total++; 
		    for $theE (@$eventsRef) {
			$theE->{'key'} = $total; $total++;
			$tmp=print1Entry($theE); print $fhhh $tmp;
			update_catlist($cal, $theE->{'cat'}) if $theE->{'cat'};
		    }
		    print $fhhh ");\n$total;\n";
                    &webcalLock::doflock( \*$fhhh, LOCK_UN,"$path/data");
		    close $fhhh;		    
		}
	    }
	}
    }
}

sub modify_all {
    my($src, $action) = (@_);
    # action is: 
    # modify:        delete $::lastOldEvent, add $::lastNewEvent
    # deleteAll:     delete $::lastOldEvent
    # deleteOne:     delete $::lastOldEvent, add $::lastOldEvent
    # deleteForward: delete $::lastOldEvent, add $::lastOldEvent
    #
    my (%excludes, @cals, $cal, $path, @excludes, $theE, $href, $tmp);
    @excludes = split(/[,: ]+/, "$::o{'corporate_calendar'}:$src");
    map { $excludes{$_} = 1; } (@excludes);
    my $oldseq = $::lastOldEvent->{'seq'};
    my $DIRc= gensym;
    if (opendir($DIRc, $::o{'spooldir'})) {
	@cals = readdir($DIRc); closedir($DIRc);
	foreach $cal (@cals) {
	    $path = "$::o{'spooldir'}/$cal";
	    if( !$excludes{$cal} and -d $path and -f "$path/info" and -f "$path/data") {
		my $fhhh = gensym;
		if(sysopen($fhhh, "$path/data",O_WRONLY | O_CREAT, 0644) and 
		   &webcalLock::doflock( \*$fhhh, LOCK_EX, "$path/data")) {
		    my $total = do "$path/data";
		    truncate($fhhh, 0);		
		    print $fhhh "\@::caldata = (\n";
		    for $href (@::caldata) {
			if($href->{'seq'} ne $oldseq) {$tmp=print1Entry($href); print $fhhh $tmp;}
		    }
		    $total++; 
		    if($action eq 'modify') {
			$theE = $::lastNewEvent;
			$theE->{'key'} = $total; $total++;
			$tmp=print1Entry($theE); print $fhhh $tmp;
		    } elsif($action eq 'deleteOne' or $action eq 'deleteForward') {
			$theE = $::lastOldEvent;
			$theE->{'key'} = $total; $total++;
			$tmp=print1Entry($theE); print $fhhh $tmp;
		    }
		    print $fhhh ");\n$total;\n";
                    &webcalLock::doflock( \*$fhhh, LOCK_UN,"$path/data");
		    close $fhhh;		    
		}
	    }
	}
    }
}
#===============================================================================================
sub attendPending {
    my ($who, $view, $ls, $href, $cmd, $total,$tmp, $k, $filter, $byfilter); $filter = $byfilter="";
    $who = $::calinfo{'w'}; $view = $::calinfo{'v'}; $ls = $::calinfo{'ls'};
    if(defined $::calinfo{'cnd'}) { $cmd = $::calinfo{'cnd'};} else { $cmd = 0;}
    if(not isre($::d{'remote_user'}, $who, 'editors')) {
	if($cmd == 0 and $::d{'remote_user'} ne 'anonymous') { $filter = $::d{'remote_user'}; $byfilter=" by $filter";}
	else { calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who)."); }
    }
    doReadFile("$::o{'spooldir'}/$who/data");
    if(defined $::calinfo{'cnd'}) { $cmd = $::calinfo{'cnd'};} else { $cmd = 0;}

    if($cmd == 0) {
	&headers("Tend to pending events" ,"");    
	$total=0;
	print <<END;
<center><h2>Tend to pending events</h2>$byfilter</center>

<center>
<Form action="$::o{'cginame'}" method=POST>$::vmp
<input type=hidden name="c" value="pending">
<input type=hidden name="cnd" value=1>
<input type=hidden name="v" value=$view>
<input type=hidden name="w" value="$who">
<input type=hidden name="ls" value=$ls>
<table border=1>
END
    ;
	$::d{'tend_2_pending'}=1;
	for $href (@::caldata) {
	    if($href->{'pnd'} and (not $filter or $href->{'author'} eq $filter)) {
		my ($mon, $day, $year) = split(/\//, $href->{'date'}); $mon--;
		$tmp = printEvent($href, 4, 1, 9, "$mon/$day/$year", 0);
		my $authoremail=$::calinfo{'pelastemail'}; delete $::calinfo{'pelastemail'};
		$k=$href->{'key'};
		print <<EBN;
<tr><td><input type=checkbox class="fmRadio" name="total$total" value="$k"></td>
    <td>$tmp</td>
EBN
    ;
		if($authoremail) {
		    print <<EBN;
<td><input type=checkbox class="fmRadio" name="email$total" value="$authoremail">&nbsp;<font size=2>$::phr{'pendmsg'}</font></td>
    </tr>
EBN
    ;
		} else {
		    print "<td>&nbsp;</td></tr>";
		}
		$total++;
	    }
	}
	print "<input type=hidden name=\"Total\" value=\"$total\">";
	if($total == 0) {
	    print "<center>There are no pending events$byfilter.</center>";
	} elsif(not $filter) {
	    print "<tr><td colspan=3 align=center>";
	    print "<input type=submit name=action value=\"$::phr{'ApproveChecked'}\" class=\"fmBtnSt\">";
	    print "&nbsp;&nbsp;&nbsp;&nbsp;";
	    print "<input type=submit name=action value=\"$::phr{'RejectChecked'}\" class=\"fmBtnSt\">";
	    print "&nbsp;&nbsp;&nbsp;&nbsp;";
	    print "<input type=submit name=action value=\"$::phr{'Cancel'}\" class=\"fmBtnSt\">";
	    print "</td></tr>";
	}
	print "</table></form></center>";
	&trailer;
	myexit(0);
    } else {
	my ($action, $i, %marks, $tmp, $cnt, %mykeys, %yourkeys, %atts, %emails, %subjects);
	$action = $::calinfo{'action'}; 
	if($action eq "$::phr{'ApproveChecked'}")  { $action ='a';}
	elsif($action eq "$::phr{'RejectChecked'}"){ $action ='r';}
	else { # cancel
	    &calendar;
	    &myexit(0);
	}
	$total = $::calinfo{'Total'};
	%marks=(); %emails=(); %subjects=(); $cnt=0; %mykeys=(); %yourkeys=(); %atts=();
	for($i=0; $i<$total;$i++) {
	    $tmp = "total$i";
	    if($::calinfo{$tmp}) {
		my $key=$::calinfo{$tmp}; $marks{$key}=1; $cnt++;
		my $smp = "email$i"; if($::calinfo{$smp}) { $emails{$key}=$::calinfo{$smp};}
	    }
	}
	if($cnt > 0) {
	    my $calname = "$::o{'spooldir'}/$who";
	    my $counter = 1;
	    my $fhzz = gensym;	    
	    if(sysopen($fhzz, "$calname/data", O_WRONLY | O_CREAT, 0644 ) ) {
		&webcalLock::doflock(\*$fhzz,LOCK_EX,"$calname/data") or calerror("Cannot lock file '$calname/data': $!\n");
		truncate($fhzz, 0);
		print $fhzz "\@::caldata = (\n";
		for $href (@::caldata) {
		    $tmp = $href->{'key'};
		    if($tmp > $counter) { $counter = $tmp;}
		    if($marks{$tmp}) {
			if($emails{$tmp}) {$subjects{$tmp} = $href->{'what'};}
			if($action eq 'a') { 
			    delete $href->{'pnd'};
			    $tmp = print1Entry($href);
			    print $fhzz $tmp;			    
			} 
			if($href->{'attendants'}) {
			    my $k= $href->{'mkey'};
			    if($k) {
				my $mkey = $k; $mkey =~ s/_eMe_\d+//g;
				if($mkey eq $who) {$mykeys{$k}=1;} else { $yourkeys{$k}=1;}
				$atts{$k}=$href->{'attendants'};
			    }
			}
		    } else {
			$tmp = print1Entry($href);
			print $fhzz $tmp;
		    }
		}
		print $fhzz ");\n$counter;\n";
		&webcalLock::doflock(\*$fhzz, LOCK_UN, "$calname/data") or calerror("Cannot unlock '$calname/data': $!\n");
		close $fhzz;
	    }
	    if($cnt >= $total) {
		my $mkfile="$::o{'spooldir'}/$who/pnd";
		if( -f "$mkfile") { unlink "$mkfile";}
	    }
#=======================================================
	    if(1) { # dependents and invitees
		my ($cal, $k, $jnk, $me, $mkey, @dependents, %doneHash);
		$me = $who; 
		&get_moderated_calendars(); 
		if($action eq 'r') { # reject
		    my @mykeys = (keys %mykeys);
		    for $k (@mykeys) {
			my $mk = $k; $mk =~ s/_eMe_\d+//g;
			my $invitee= expandMeetingGroups($mk, $atts{$k});
			my @all = split(/:/, $invitee);
			for $cal (@all) {
			    next if $cal eq $me;
			    my @tkeys = (); push @tkeys, $k;
			    &removeEventMkey($cal, \@tkeys);
			}
		    }
		    my @yourkeys = (keys %yourkeys);
		    if( 0+@yourkeys > 0 and $::calinfo{'dcs'}) {
			%doneHash=(); $doneHash{$me}=1;
			%::dependencyHash =();
			my $file = "$::o{'spooldir'}/.dependency";
			if( -f "$file") {
			    %::dependency=(); doReadFile($file);		    
			    removeFromDependentsMkey($me, \@yourkeys, \%atts, \%doneHash);
			}
		    }
		} else {  # approve
		    %::dependencyHash =();
		    my $file = "$::o{'spooldir'}/.dependency";
		    if( -f "$file") { %::dependency=(); doReadFile($file); }
		    my @mykeys = (keys %mykeys);
		    if(0+@mykeys > 0) {
			for $k (@mykeys) {
			    my $mk = $k; $mk =~ s/_eMe_\d+//g;
			    my $invitee= expandMeetingGroups($mk, $atts{$k}, 1);
			    my @invitee =split(/:/, $invitee);
			    my @tmkeys = (); my ($c);
			    push @tmkeys, $k;
			    %doneHash=(); $doneHash{$me}=1;
			    for $c (@invitee){
				next if $doneHash{$c};
				next if $c eq $me;
				approveDependentsMkey($c, \@tmkeys, \%atts, \%doneHash, "", 1);
			    }
			}		
		    }	
		    my @yourkeys = (keys %yourkeys);
		    %doneHash=(); $doneHash{$me}=1;
		    if(0+@yourkeys > 0 and $::calinfo{'dcs'}) {
			approveDependentsMkey($me, \@yourkeys, \%atts, \%doneHash, "", 0);
		    }
		}
	    }
	}
#=======================================================
	my ($msg, $ar);
	if($action eq 'a') { $msg = "You have approved $cnt event(s)"; $ar="approved";}
	else { $msg = "You have rejected $cnt event(s)"; $ar="rejected";}
	my $d= printDate0($::now{'month'}, $::now{'day'}, $::now{'year'});
	acknowledge($who, $view, $ls, $d, $msg);
	{
	    my ($email, $subject, $k, $msg);
	    for $k (keys %emails) {
		$email = $emails{$k};
		$subject = $subjects{$k};
		$msg =<<END;
Your post to calendar $who regarding
     $subject
has been $ar.
END
    ;
		SimpleMail($::calinfo{'email'}, $email, "Re: your post to calendar $who", $msg);
	    }
	}
	&myexit(0); 
    }
}
#============================================================
sub SimpleMail {
    my ($from, $to, $subject, $msg) = (@_); $subject =~ s/\r?\n//g; $to =~ s/\r?\n//g; $from =~ s/\r?\n//g;
    if($webcalConfig::r{'sendmail'}) {
         if( $ !~ m/MSWin|NT/i ) {
             my $SENDMAIL= $webcalConfig::r{'sendmail'};
             open (MAIL,"|-") || exec($SENDMAIL, "-t", "-oi");
	     my $now_string = &rfc2822_datetime;
             print MAIL "To: $to\015\012";
	     print MAIL "From: $from\015\012";
	     print MAIL "Subject: $subject\015\012";
	     print MAIL "Date: $now_string\015\012";
	     print MAIL "X-Mailer: webCalendar $webCalVersion $patchlevel\015\012";
	     print MAIL "\015\012";
	     print MAIL "$msg\015\012";
             close MAIL;
         }
     } else { # check for smtp server
         if($webcalConfig::r{'smtpto'} and $webcalConfig::r{'smtpfrom'}) {
             my $fromsmtp = $webcalConfig::r{'smtpfrom'};
             my $tosmtp = $webcalConfig::r{'smtpto'};
             my ($status, $error) = &smtplib::SmtpSendMail($from, $fromsmtp, $to, $tosmtp, $subject,$msg,"","");
         } 
     }
}
#============================================================
sub removeEventMkey { 
    my ($cal, $emkeys) = (@_);
    my ($calname, $dfile, $rkey, $href, $tmp); 
    $calname= "$::o{'spooldir'}/$cal";
    $dfile = "$calname/data";
    if( -f $dfile) {
	my $fhzz = gensym;	    
	if(sysopen($fhzz, "$dfile", O_WRONLY | O_CREAT, 0644 ) ) {
	    &webcalLock::doflock( \*$fhzz, LOCK_EX, "$dfile") or
		calerror("Cannot lock file '$dfile': $!\n");     
	    my $nevents= do "$dfile";
	    my $found =0;
	    for $href (@::caldata) {
		if($href->{'mkey'}) {
		    for $rkey (@$emkeys) {if($href->{'mkey'} eq $rkey) { $href->{'deleted'} = 1; $found++;}}
		}
	    }
	    if($found) {
		truncate($fhzz, 0);
		print $fhzz "\@::caldata = (\n";
		for $href (@::caldata) {
		    if( not $href->{'deleted'} ) {
			$tmp = print1Entry($href);
			print $fhzz $tmp;	
		    }		    				
		}
		print $fhzz ");\n$nevents;\n";
	    }
	    &webcalLock::doflock(\*$fhzz, LOCK_UN, "$dfile") or calerror("Cannot unlock '$dfile': $!\n");
	    close $fhzz;
	}
    }
}
#============================================================
sub removeFromDependentsMkey {
    my ($cal, $emkeys, $atts, $doneHash) =(@_);
    my ($deps, @deps, $c, $invitee, $mk, $e);
    $deps = $::dependency{$cal};
    @deps=();
    if($deps) {	@deps = split(/:/,$deps);}
    for $c (@deps) {
	next if $doneHash->{$c} or $c eq $cal;
	my @tmkeys=(); my $cnt=0;
	for $e (@$emkeys) {
	    my $mk = $e; $mk =~ s/_eMe_\d+//g;
	    my $att = expandMeetingGroups($mk, $atts->{$e}, 1);
	    if(not ismember($c, $att)) {
		push @tmkeys, $e; $cnt++;
	    }
	    if($cnt>0) { removeFromDependentsMkey($c, \@tmkeys, $atts, $doneHash); }
	}
    }
    if(! $doneHash->{$cal}) {
	$doneHash->{$cal} = 1;
	&removeEventMkey($cal, $emkeys);
    }
}
#============================================================

sub approveDependentsMkey {
    my ($cal, $emkeys, $atts, $doneHash, $pnd, $level) = (@_);
    my ($deps, @deps, $c);
    if($level > 0) {
	if(not $pnd and  $::moderated{$cal}) {  $pnd = $cal;}
	if(! $doneHash->{$cal}) {
	    $doneHash->{$cal} = 1;
	    &approveEventsMkey($cal, $emkeys, $atts, $pnd);
	}
    }
    $deps = $::dependency{$cal}; 
    if($deps) {
	@deps = split(/:/, $deps);
	for $c (@deps) {
	    next if $doneHash->{$c};
	    approveDependentsMkey($c, $emkeys, $atts, $doneHash, $pnd, 1+$level);
	}
    }
}
#============================================================
sub approveEventsMkey {
    my ($cal, $emkeys, $atts, $pnd) = (@_);
    my ($calname, $dfile, $rkey, $href, $tmp); 
    $calname= "$::o{'spooldir'}/$cal";
    $dfile = "$calname/data";
    if( -f $dfile) {
	my $fhzz = gensym;	    
	if(sysopen($fhzz, "$dfile", O_WRONLY | O_CREAT, 0644 ) ) {
	    &webcalLock::doflock( \*$fhzz, LOCK_EX, "$dfile") or
		calerror("Cannot lock file '$dfile': $!\n");     
	    my $nevents= do "$dfile";
	    my $found =0;
	    for $href (@::caldata) {
		if($href->{'mkey'}) {
		    for $rkey (@$emkeys) {
			if($href->{'mkey'} eq $rkey) {
			    if(not $pnd) { delete $href->{'pnd'};} 
			    elsif($href->{'pnd'}) { $href->{'pnd'} = $pnd;}
			    $found++;
			}
		    }
		}
	    }
	    if($found) {
		truncate($fhzz, 0);
		print $fhzz "\@::caldata = (\n";
		for $href (@::caldata) {
		    $tmp = print1Entry($href);
		    print $fhzz $tmp;	
		}
		print $fhzz ");\n$nevents;\n";
	    }
	    &webcalLock::doflock(\*$fhzz, LOCK_UN, "$dfile") or calerror("Cannot unlock '$dfile': $!\n");
	    close $fhzz;
	}
    }
}

#===============================================================================================

sub reminders_only {
    if($::phr{'CHARSET'}) { print "Content-type: text/html; charset=$::phr{'CHARSET'}\n\n";}
    else { print "Content-type: text/html\n\n";}

    my ($who, $month, $day, $year, $hour, $min); 
    $who = $::calinfo{'w'}; $::calinfo{'v'}=2; $::calinfo{'ls'}=0; $::d{'megaCal'}="";
    $month= $::now{'month'}; $day  = $::now{'day'}; $year = $::now{'year'}; $hour = $::now{'hour'}; $min  = $::now{'min'};
    $::calinfo{'month'} = $month; $::calinfo{'day'} = $day; $::calinfo{'year'} = $year;
    $::calinfo{'hour'} = $hour; $::calinfo{'min'} = $min;
    &readData;
    $::o{'imgdirurl'}=$::o{'fimgdirurl'}; $::o{'cginame'}=$::o{'fcginame'}; 
    $::o{'save_reminding_events'}=1;
    {
        my ($i, $nm, $nd, $ny);
        for($i=0; $i<7; $i++) {
            ($nm, $nd, $nm) = canDate($month, $day+$i, $year);
            getOneDayEvents($nm, $nd, $ny, "", 0); 
        }
    }
    $::o{'save_reminding_events'}=0;
    my (@keys, $key, $html);
    my ($popup, $blink, $chime)=("","","");
    $html= 0; $html=1 if $::calinfo{'html'};

    @keys = (keys %::popupEvents);
    if(scalar(@keys) > 0){for $key (@keys) { $popup .= text_of_event($key, $::popupEvents{$key},$html);}}
    @keys = (keys %::blinkEvents);
    if(scalar(@keys) > 0){for $key (@keys) { $blink .= text_of_event($key, $::blinkEvents{$key},$html);}}
    @keys = (keys %::chimeEvents);
    if(scalar(@keys) > 0){for $key (@keys) { $chime .= text_of_event($key, $::chimeEvents{$key},$html);}}

    my $ans="";
    if($html) {
	if($popup) { $ans .= "<h2>Popup Reminder</h2> <table border=0>$popup</table>";}
	if($blink) { $ans .= "<h2>Blink Reminder</h2> <table border=0>$blink</table>";}
	if($chime) { $ans .= "<h2>Audio Reminder</h2> <table border=0>$chime</table>";}
    } else {
	if($popup) { $ans .= "Popup Reminder\n$popup";}
	if($blink) { $ans .= "Blink Reminder\n$blink";}
	if($chime) { $ans .= "Audio Reminder\n$chime";}
    }

    print $ans, "\n";
    
    # move cache computations to cleanup handler.
    # Since myexit() clears most global variables. The following hash 
    # records the variables needed for computing the cache. 
    %::cache_info=('spooldir'=> $::o{'spooldir'},  'w' => $::calinfo{'w'}, 
                   'v' => $::calinfo{'v'},         'weekstart' =>$::o{'weekstart'},
                   'day' => $::calinfo{'day'}, 'month' => $::calinfo{'month'}, 'year'=> $::calinfo{'year'},
                   'megaCal' => $::d{'megaCal'}, 'dctoc' => $::calinfo{'dctoc'},
                   );
    if($ENV{'MOD_PERL'} and $::this_request) { $::this_request->register_cleanup( \&cacheData ); } 
    else { &cacheData();}
}
sub text_of_event{
    my($key, $value, $html) = (@_);
    my ($mn, $dy, $yr, $tim)=split(/\//, $key); $mn--;
    my ($shr, $smn, $ehr, $emn, $kind) = split(/:/, $tim);if($kind==4){$shr=~ s/^\(\d+\)//;}
    $tim= mdy_swstring($mn,$dy,$yr)." ".hm_string($shr,$smn);
    if(! $html){$value=~ s/<a[^>]+>//ig; $value=~ s/<\/a>//ig; $value=~ s/<img[^>]+>//ig; return fstr($tim, $value, 32);}
    else { return "<tr><td>$tim:</td><td>$value</td></tr>"; }
}
#===============================================================================================
sub getcalvgroup {
    my ($u)=(@_);
    if($::o{'vgroup'}){my $gfile ="$::o{'spooldir'}/$u/vgroup"; $::calinfo{'vgroup'}="";if(-f $gfile){doReadFile($gfile);}}
    return $::calinfo{'vgroup'} || "";
}
sub getcalpvgroup { my $gps=getcalvgroup(@_); if($gps) {my @all = split(/:/,$gps); return $all[0] || "";} return "";}

sub isvgadmin { 
    return 0 if not $::o{'vgroup'};
    my ($u, $w)=(@_); my ($gps, @all, $pgp,$pgw, $gfile);  $pgp = getcalpvgroup($u);
    if($pgp) { 
	if($u eq $w){$pgw=$pgp;} else {$pgw = getcalpvgroup($w);}
	if($pgw and $pgw eq $pgp) {
	    my $gfile="$::o{'spooldir'}/.vgroups/$pgp";
	    if($pgp and -f $gfile){$::vgadmin=""; doReadFile($gfile); return 1 if $::vgadmin eq $u;}
	}
    }
    return 0;
}
sub listvgroups {
    my $gdir ="$::o{'spooldir'}/.vgroups"; my @ans=();
    my $DIRg= gensym; if(opendir($DIRg, $gdir)){ @ans = grep(!/^\./, readdir($DIRg)); closedir($DIRg);}
    return sort {uc($a) cmp uc($b)} @ans; 
}
sub list1vgroup {
    my ($gp)=(@_);
    my $gfile ="$::o{'spooldir'}/.vgroups/$gp"; my @ans=();    
    $::vgadmin=""; @::vgmembers=();
    if( -f "$gfile") { doReadFile($gfile);}
    my $adm = $::vgadmin; my @mems = @::vgmembers;
    return ($adm, @mems);
}
sub updatevgroups {
    my (@allgps,$gp,$adm,@mems);
    (@allgps) = listvgroups;
    foreach $gp (@allgps){($adm, @mems)=list1vgroup($gp); update1vgroup($gp,$adm,@mems);}
}
sub update1vgroup {
    my ($gp, $admin, @members) = (@_);
    my $gdir ="$::o{'spooldir'}/.vgroups";
    if(-d "$gdir" or mkdir("$gdir", 0711)) {
	my ($k,$content, $gfile, @old, %hash,$cnt); $gfile = "$gdir/$gp"; %hash=(); $::vgadmin=""; @::vgmembers=();
	if( -f $gfile) { doReadFile($gfile); @old=@::vgmembers;} else {@old=();}
	$admin =~ s/\s//g; if($admin and ! -f "$::o{'spooldir'}/$admin/data") { $admin ="";}
	$content='$::vgadmin' . "=\'$admin\';\n"; if($admin){$cnt=1;}else{$cnt=0;}
	$content .= '@::vgmembers=(' ;
	for $k (@members){ $k=~ s/\'|\s|\///g; if($k and -f "$::o{'spooldir'}/$k/data") {$cnt++;$content .= "\'$k\',"; }}
	$content .= ");\n1;\n"; 
	if($cnt){write_file($gfile, $content);} else {if(-f $gfile) {unlink($gfile);}}
	for $k (@members){ membervgroup($k,$gp); $hash{$k}=1;}
	for $k (@old) {if(! $hash{$k}) {removemembervgroup($k, $gp);} }
    } else { return 0;}
}
sub membervgroup {
    my($user,$gp)=(@_); my ($content,$gfile);
    $gfile ="$::o{'spooldir'}/$user/vgroup"; if( -f $gfile) { &doReadFile("$gfile"); }
    if($::calinfo{'vgroup'}){$::calinfo{'vgroup'}="$::calinfo{'vgroup'}:$gp";} else {$::calinfo{'vgroup'}="$gp";}
    $content="\$::calinfo{\'vgroup\'}=\"" . unique($::calinfo{'vgroup'}) ."\";\n1;";
    write_file($gfile, $content);
}
sub removemembervgroup {
    my($user,$gp)=(@_); my ($content,$gfile, @gps, $k, $j);
    $gfile ="$::o{'spooldir'}/$user/vgroup"; 
    if( -f $gfile) {
	&doReadFile("$gfile");  @gps=split(/:/,$::calinfo{'vgroup'}); $content=""; $j="";
	for $k (@gps) { if($k ne $gp) {$content .= "$j$k"; $j=":";}}
	if($content) {
	    $content="\$::calinfo{\'vgroup\'}=\"" . $content ."\";\n1;";
	    write_file($gfile, $content);
	} elsif( -f "$gfile") { unlink $gfile;}
    }
}
sub createvgroups {
    my (@vgroups) = (@_); my $cnt=0; 
    my $gdir ="$::o{'spooldir'}/.vgroups";
    if(-d "$gdir" or mkdir("$gdir", 0711)) {
	my $k; for $k (@vgroups){$k=~ s/\'|\s|\/|,|;//g; if(! -f "$gdir/$k") { $cnt++; write_file("$gdir/$k", "1;");}}
    } return $cnt;
} 
sub removefromvgroups { 
    my($cal,$vgps)=(@_); my ($gfile, $gp, @gps, $k, $n);
    @gps=split(/:/,$vgps);
    for $gp (@gps) {
	$gfile ="$::o{'spooldir'}/.vgroups/$gp";
	if( -f $gfile) { 
	    $::vgadmin=""; @::vgmembers=();  doReadFile($gfile);  $n=scalar(@::vgmembers);
	    for($k=0;$k<$n;$k++){ if($::vgmembers[$k] eq $cal) {$::vgmembers[$k]="";}}
	    my $adm = $::vgadmin; my @members = @::vgmembers;
	    update1vgroup($gp, $adm, @members);
	}
    }
}
sub addusertovgroup {
    my ($user, $gp)= (@_); my ($gfile, $dir, $n);  $gfile="$::o{'spooldir'}/.vgroups/$gp"; 
    $::vgadmin=""; @::vgmembers=();  if( -f $gfile) {doReadFile($gfile);}
    my $adm = $::vgadmin; my @members = @::vgmembers; push @members, $user; 
    update1vgroup($gp, $adm, @members);
}
#===============================================================================================
sub dndevent {
    my ($dndsrc,$dndtgt) = (@_);
    my ($scal,$st,$tcal,$tmh,$tdy,$tyr,$thr,$tmn,$msg,$dt,$timeset,$edt,$status,$dura,$trash,$move);
    my $dndconfirmed=0; if($::calinfo{'dndconfirm'}) { $dndconfirmed=$::calinfo{'dndconfirm'};}
    $msg=""; $timeset = 0; $status = 0; $trash=0; $move=0;
    if($dndsrc =~ /^_:([^:]+):t=(\d+):(.*)/) {
	$scal = $1; $st = $2; $edt = $3;
    } else { $msg .= "$::phr{'invalidDnD'} <br><br>[$dndsrc $dndtgt:_]";}
    ($tcal, $dt) = split(/:/,$dndtgt);
    if(not $tcal) { $msg .= "$::phr{'invalidDnD'} <br><br>[$dndsrc $dndtgt:_]" ;}
    ($tmh, $tdy, $tyr, $thr, $tmn, $dura) = split(/\//, $dt);
    my ($month, $day, $year) = canDate($tmh, $tdy, $tyr);
    if($tmh != $month or $tdy != $day or $tyr != $year) {
	$msg .="$::phr{'invalid_date'}. $tmh/$tdy/$tyr != $month/$day/$year";
    }
    if($msg ne "") { return (-8, $msg);}
    if(defined $thr and defined $tmn) { $timeset = 1;}
    if($year==1900){$trash=1; $tcal=$scal;} elsif($year==1901) { if($scal eq $tcal) { return(8, "");} $move=1;}
    # input are all ok
    my $usr=$::d{'remote_user'};
    if($usr ne $tcal) {
	if(not isadmin($usr) and not isre($usr, $tcal, 'editors')){
    	    $msg .= "$::phr{'You'} $::phr{'NotAllowedToModify'} '$tcal' .";
	}
    }
    if($tcal ne $scal) {
	if(not isadmin($usr) and not isre($usr, $scal, 'editors')){	
    	    $msg .= "$::phr{'You'} $::phr{'NotAllowedToModify'} '$scal' .";
	}
    }
    if($msg ne "") { return (-8, $msg);}    

    # preceed to move event
    if($trash and not $dndconfirmed) {
	return(-1, $::phr{'DnDdel'} . "<br><br>" . $::phr{'PlseConfirm'});
    }
    my $recurring=0;
    my $tmp= getinfo($scal, 'ol') || 0;  if($tmp<2 and $dndconfirmed>1) { $tmp=0;} $::calinfo{'aol'}=$tmp;
    my $file= "$::o{'spooldir'}/$scal/data";
    my ($href, $event); $event=undef;
    $month += 1; $::calinfo{'sdate'} = "$month/$day/$year";
    @::caldata=(); doReadFile($file); for $href (@::caldata) {if($href->{'key'} eq "$st") { $event = $href; last;}}
    my $kind = $event->{'kind'}; if($kind == 2 or $kind == 4) {$::calinfo{'aol'}=0;}
    if($move) {$::calinfo{'sdate'} = $event->{'date'};}
    if($timeset) { $::calinfo{'shour'} =$thr;   $::calinfo{'smin'} =$tmn;}
    else {($::calinfo{'shour'}, $::calinfo{'smin'})  = split(/:/, $event->{'start'});}
    if($event->{'repeat'} and $event->{'repeat'} >= 2) {$recurring=1;} # recurreng event, detach and insert.

    if(not $dndconfirmed) {
	my $msg = "";
	if($scal ne $tcal) {
	    $msg = "$::phr{'DnDmove'}<br><blockquote>$scal &nbsp;==>&nbsp; $tcal</blockquote><br>";
	}
	if($recurring) {
	    $msg .= "$::phr{'DnDrecur'} <br><br>"
	}
	if($msg) {
	    $msg .= "$::phr{'PlseConfirm'}";
	    return (-1, $msg);
	}
    }

    # do nothing if drop to itself.
    my $thisdate; if($edt) {$thisdate=$edt;} else { $thisdate=$event->{'date'};}
    if($::calinfo{'sdate'} eq $thisdate and $tcal eq $scal) {
	my ($hr, $mn) = split(/:/, $event->{'start'}); $hr+=0; $mn+=0;
	my $duration = $event->{'duration'} || 0;
	my $utmp=$mn+$duration; my $ehr=0+$hr+int($utmp/60); my $emn =0+($utmp % 60);
	my $edtinfo="$::calinfo{'sdate'}/$hr/$mn/$ehr/$emn";
	if( not $timeset) {  my $te = copyTask($event);  # post time change form
	    return(-3, "", $edtinfo, $te);
	}
	else {
	    my ($hr, $mn) = split(/:/, $event->{'start'});
	    if($hr == $thr and $mn == $tmn) {
		if(!defined($dura)) {my $te = copyTask($event); return(-3, "", $edtinfo, $te);} # drop onto self, request more info
		elsif($duration == $dura) {
		    my $changed=0;
		    if($::calinfo{'dnddescription'}){my $t=$::calinfo{'dnddescription'}; if($t ne $event->{'what'}){ $changed++;}}
		    if($::calinfo{'dndeprivacy'}){my $t= $::calinfo{'dndeprivacy'};if($t ne $event->{'privacy'}){$changed++;}} 
		    if($::calinfo{'dndsroom'}){
			my $t=$::calinfo{'dndsroom'};if(not $event->{'room'} or $t ne $event->{'room'}){ $changed++;} 
		    }
		    if($::calinfo{'dndcat'} and $::calinfo{'dndcat'} !~ /^\s*$/ ){ 
			my $t=$::calinfo{'dndcat'}; if(not $event->{'cat'} or $t ne $event->{'cat'}){ $changed++;} 
		    }
		    return(8, "") if not $changed;
		}
	    }
	}
    }

    # copy event info
    map { if(defined $event->{$_}) {$::calinfo{$_} = $event->{$_};}}
    ('author','detail','cbg','ctp','ctm','cat','kwd','sroom','done','ctd','ctds','bdate','forward',
     'pri','spkr', 'acc','dec','rsvp','seq','rurl');

    my %thash=('kind'=>'k','fg'=>'fgclr','bg'=>'bgclr','cs'=>'css','mme'=>'imme','attendants'=>'mattendants',
	       'duration'=>'oduration','what'=>'description','rem'=>'orem','privacy'=>'eprivacy',);
    map { if(defined $event->{$_}) {my $v=$thash{$_}; $::calinfo{$v} = $event->{$_};}} (keys %thash);
    map { my $k="dnd$_"; if($::calinfo{$k}) {$::calinfo{$_} = $::calinfo{$k};}} ('description','sroom','cat', 'eprivacy');
    
    $::calinfo{'w'} = $scal; $::calinfo{'t'} = $st;    
    if(defined($dura)) {$::calinfo{'oduration'} = $dura;}
    $::calinfo{'donotacknowledge'} = 1; # so doedit returns instead of display the error screen
    my ($ir0, $sr0, $ir1, $sr1);
    if($recurring == 0) { # non-recurring event
	if($scal eq $tcal) {
	    if($trash==0){$::calinfo{'action'} = $::phr{'Modify'};}
	    else {$::calinfo{'action'} = $::phr{'Delete'};}
	    ($ir0, $sr0, $ir1, $sr1)=&doedit;
	} else {
	    $::calinfo{'w'} = $tcal;
	    $::calinfo{'action'} = $::phr{'InsertAsNew'};
	    ($ir0, $sr0, $ir1, $sr1)=&doedit;	    
	    if($ir0 == 20) {
		$::calinfo{'w'} = $scal; $::calinfo{'t'} = $st;
		$::calinfo{'action'} = $::phr{'Delete'};
		($ir0, $sr0, $ir1, $sr1)=&doedit;
	    }
	}
    } else {  # recurring event
	$::calinfo{'w'} = $tcal;
	if($trash==0){
	    $::calinfo{'action'} = $::phr{'InsertAsNew'};
	    ($ir0, $sr0, $ir1, $sr1)=&doedit;
	} else { ($ir0, $sr0, $ir1, $sr1)=(20,"",0,"");}
	if($ir0 == 20) {
	    $::calinfo{'w'} = $scal; $::calinfo{'t'} = $st;
	    $::calinfo{'sdate'} = $edt;
	    $::calinfo{'action'} = $::phr{'DeleteThisOne'};
	    # repeating info
	    my $recurr;
	    my $occurs = $event->{'occurs'}; my $repeat= $event->{'repeat'};
	    ($repeat, $recurr)= &bp_repeat_occur($repeat,$occurs);
	    if($occurs=~/^Z/){$::calinfo{'hidden_occurs'}=$event->{'occurs'};}
	    $::calinfo{'occurs'} =$occurs; $::calinfo{'repeat'} =$repeat; $::calinfo{'orecurr'} = $recurr;
	    if(defined $event->{'exception'}) { 
		my $aref =$event->{'exception'}; my $tmp = '[' . join(',', @$aref) . ']';
		$::calinfo{'oexception'} = "$occurs:$repeat:$tmp";
	    }
	    ($ir0, $sr0, $ir1, $sr1)=&doedit;
	}
    }
    if($ir0 == 20) { $status = 0;}     # succesful 
    elsif($ir0 == 10) {$status = -2;}  # overlap confirmation
    else { $status = -8;}              # all other errors
    $msg .= "$sr0 $sr1";
    return ($status, $msg);
}
#===============================================================================================
sub dodnd {
    my $dndsrc = $::calinfo{'dndsrc'};  my $dndtgt = $::calinfo{'dndtgt'};
    if($::calinfo{'dndself'}) { # modify event date/time. modify dndtgt
	my ($shr,$smn,$ehr,$emn,$date, $mth,$day,$yar, $cal, $rest);
	$shr=$::calinfo{'dndstimehour'}; $smn=$::calinfo{'dndstimemin'}; 
	$ehr=$::calinfo{'dndetimehour'}; $emn=$::calinfo{'dndetimemin'}; 
	if (not $::o{'hourformat'} and defined $::calinfo{'dndetimeampm'}) {
	    if($::calinfo{'dndstimeampm'} eq 'am' and $shr eq 12) { $shr = 24;}
	    elsif($::calinfo{'dndstimeampm'} eq 'pm') { $shr += 12 unless $shr eq 12;}
	    if($::calinfo{'dndetimeampm'} eq 'am' and $ehr eq 12) { $ehr = 24;}
	    elsif($::calinfo{'dndetimeampm'} eq 'pm') { $ehr += 12 unless $ehr eq 12;}
	}
	my $duration = ($ehr - $shr)* 60 + ($emn -$smn); if($duration < 0){ $duration = 0;}
	$date=to_wcal_date($::calinfo{'dndsdate'});
	($mth,$day,$yar)=split(/\//,$date); $mth--;
	($cal, $rest)=split(/:/, $dndtgt);
	$dndtgt="$cal:$mth/$day/$yar/$shr/$smn/$duration";
    }
    my $msg = ""; my $status=0; my $edtinfo=""; my $theE=undef;
    if($dndsrc !~ /^_:.+t=\d+/ or $dndtgt !~ /.+:\d+\/\d+\/\d+/) {
	$status=-8; $msg = "$::phr{'invalidDnD'}. <br><br>[$dndsrc $dndtgt:_]";
    } else { ($status, $msg, $edtinfo, $theE) = dndevent($dndsrc, $dndtgt); }

#    $msg .= "<br><br>[$dndsrc $dndtgt:_]";

    if($status == -3) { #post a tiny form to edit event time/date
	&headers("Webcal DnD","", 0,0,0,"onload=\"window.resizeTo(640,400)\"");	
	my $who = $::calinfo{'w'}; my $confirmed="";
	my($mth,$day,$yar,$shr,$smn,$ehr,$emn)=split(/\//, $edtinfo);
	my $udate = to_native_date("$mth/$day/$yar");
	my $dndstime = select_time("dndstime",$shr,$smn);
	my $dndetime = select_time("dndetime",$ehr,$emn);
	if($::calinfo{'dndconfirm'}) {
	    $confirmed="<input type=hidden name=dndconfirm value=\"$::calinfo{'dndconfirm'}\">";
	}
	my $ek = $theE->{'kind'}; my $ekind=""; my $eclr="";
	if($ek==1){$ekind=$::phr{'Appointment'}; $eclr='tclra';} elsif($ek==2){$ekind=$::phr{'ToDo'};$eclr='tclrt';}
	elsif($ek==3){$ekind=$::phr{'Meeting'}; $eclr='tclrm';}  else{$ekind=$::phr{'Special'};$eclr='tclrs';}
	my $ewhat=$theE->{'what'}; my $ecat=$theE->{'cat'}; my $eroom=$theE->{'room'}; my $catlist=build_catlist($who,'dndcat',-1,$ecat);
	my $epri=$theE->{'privacy'}; my  $dprivacy= select_value("dndeprivacy",$epri,@::privacyList);
	my $scal=linkSmallCal("dndedit.dndsdate",$who,$mth-1,$yar);
	print <<END;
<center><span class="miscTitleSmall"><b>$::phr{'DnD'}</b></span>
<br>
<table border=0><tr><td><blockquote>$::phr{'DnDself'}</blockquote></td></tr></table>
<form name="dndedit" method="post"  action="$::o{'cginame'}">
<input type=hidden name=w value="$who">
<input type=hidden name=c value="dnd">
$confirmed
<input type=hidden name=dndsrc value="$dndsrc">
<input type=hidden name=dndtgt value="$dndtgt">
<input type=hidden name=dndself value="1">
<table border=0><tr><td colspan=4><span class="fmLabel"><font color="$::o{$eclr}"><b>$ekind</b></font></span></td></tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'Date'}:</span></b></td>
<td align=left><input type=text size=10 maxlength=24 name=dndsdate value="$udate" class="fmEntry">$scal</td>
<td align=right><b><span class="fmLabel">$::phr{'What'}:</span></b></td>
<td align=left rowspan=2><textarea wrap=virtual name=dnddescription cols=24 rows=2 class="fmTextS">$ewhat</textarea></td></tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'Start'}:</span></b></td><td align=left> $dndstime</td></tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'End'}:</span></b></td><td align=left>$dndetime</td>
<td align=right><b><span class="fmLabel">$::phr{'Category'}:</span></b></td><td>$catlist</td></tr>
<tr><td align=right><b><span class="fmLabel">$::phr{'Privacy'}:</span></b></td><td>$dprivacy</td>
    <td><b><span class="fmLabel">$::phr{'Location'}:</span></b></td><td>
    <input type=text size=20 maxlength=60 name=dndsroom value="" class="fmEntry"></td></tr>


<tr> <td colspan=4 align=center><br>
<input type=submit name=action class="fmBtnSt" value="$::phr{'Submit'}">&nbsp;&nbsp;
<input type=button class="fmBtnSt" value="$::phr{'Cancel'}" onclick="self.close()">
</td></tr>
</table></form>
</center></body></html>
END
    ;
    } elsif($status < 0) { # human interaction is needed
	my $confirmbutton=""; my $close = $::phr{'Close'};
	my $code = 1;
	if($status >= -2) { # request for confirmation
	    $confirmbutton="<input type=button value=\" $::phr{'Confirm'} \" onclick=\"javascript:dndcfm();\">&nbsp;&nbsp;";
	    $close = $::phr{'Cancel'};
	    if($status == -2) { $code=2;}
	}
	my $curl="$::o{'cginame'}?c=dnd&dndtgt=$dndtgt&dndconfirm=$code&dndsrc=$dndsrc";	
	&headers("Webcal DnD","function dndcfm(){var url=\"$curl\";location.replace(url);}",
		 0,0,0,"onload=\"window.resizeTo(640,400)\"");

	print <<END;
<center><span class="miscTitleSmall"><b>$::phr{'DnD'}</b></span>
<br>
<table border=0><tr><td>
<blockquote><font color="#000099">$msg</font></blockquote></td></tr></table>
<br><br>
<table border=0 cellpadding=2><tr><td>
<form name=confirm method=post><b>
$confirmbutton
<input type=button value=" $close " onclick="javascript:self.close();"></b>
</form></td></tr></table>
</center></body></html>
END
;
    } else { #status=0: sucessful, refresh opener. status>0: failed, abort gracefully. 
	my $onload="";
	if($status == 0) { $onload="onload=\"opener.document.location.reload(1);self.close()\"";}
	else {$onload="onload=\"self.close()\"";}
	&headers("Webcal DnD","",0,0,0,$onload);
	print <<END;
<table border=0><tr><td>
<blockquote><font color="#000099">$msg</font></blockquote></td></tr></table>
<br><br>
<table border=0 cellpadding=2><tr><td><form><b><input type=button value=" $::phr{'Close'} " 
onclick="javascript:opener.document.location.reload(1);self.close();"></b>
</form></td></tr></table>
</center></body></html>
END
;
    }
    myexit(0);      
}

#============================================================================================
sub doblock_move {
    my $command = $::calinfo{'cmd'}; $command='post' if !$command;
    my $who = $::calinfo{'w'};
    my $cal = "$::o{'spooldir'}/$who";
    my $usr = $::d{'remote_user'};
    if(not isadmin($usr) and not isre($usr, $who, 'editors')){
	&calerror("$::phr{'You'} ($::d{'remote_user'}) $::phr{'NotAllowedToEdit'} ($who).", -3);
	myexit(0);
    }

    if($command eq 'post') { # post form
	my $file = "$cal/cats";
	%::cats = ();
	if( -f $file) { &doReadFile("$file"); }
	$::cats{'==All=='} = " ";
	my $category = &select_hash('cat', " ", '', \%::cats);
	&headers('block move');
	my @years=(2000..2020);
	my ($smn, $sdy, $syr, $emn, $edy, $eyr);
	$smn = &select_Month('smn',0);   
	$sdy = &select_Day('sdy',1);
	$syr = &select_option('syr',2004, @years);
	$emn = &select_Month('emn',0);
	$edy = &select_Day('edy',1);
	$eyr = &select_option('eyr',2004, @years);	  
	my $cpathevent = &select_value('cpe',1, (0, 'No', 1, 'Yes'));

	  print <<END;
<font size=1><br></font>
<center>
<table border=0 cellspacing=0 cellpadding=0>
<tr><th><font size=+2>Block Move Events</font></th></tr>
<tr><td width=540>
<blockquote>
<font color="#000066" size=2>
You can only block move simple events. Recurring events or group 
events cannot be moved with block move.
</font>
</blockquote>
</td></tr>
</table>
</center>
<form name="blockmove" action="$::o{'cginame'}" method=post>
<input type=hidden name=c value="bkm">
<input type=hidden name=cmd value="process">
<input type=hidden name=w value="$who">
<center><table border=0 cellspacing=2 cellpadding=0>
<tr><td align=center width=600>
<table border=0>
<tr><td align=right><b>Category:</b></td><td colspan=3 nowrap>$category
&nbsp;&nbsp;
<b>Critical Path Event:</b> $cpathevent
</td></tr>
<tr><td align=right nowrap><br><b>Start Date:</b></td>
<td colspan=3><table border=0><tr>
 <td><font size=1>Month<br></font>$smn</td>
 <td><font size=1>Day<br></font>$sdy</td>
 <td><font size=1>Year<br></font>$syr</td>
 <td><font size=1><br>(inclusive)</font></td>
 </tr></table></td>
</tr>
<tr><td align=right><br><b>End Date:</b></td>
 <td colspan=3><table border=0><tr>
 <td><font size=1>Month<br></font>$emn</td>
 <td><font size=1>Day<br></font>$edy</td>
 <td><font size=1>Year<br></font>$eyr</td>
 <td><font size=1><br>(inclusive)</font></td>
 </tr></table></td>
</tr>

<tr><td align=right><b>Advance:</b></td>
<td colspan=3 nowrap><input type=text name="advance" size=4> <b>Days</b>
<font size=1>(negative means backward)</td></tr>
<tr><td align=right><input type=radio name="avwknd" value="0"> </td>
<td colspan=3><font size=2>Do not distinguish between weakdays and weekends.</font></td></tr>
<tr><td align=right><input type=radio name="avwknd" value="1" checked></td>
<td colspan=3><font size=2>Do not schedule events on weekends, forward 
weekend events to the next weekday (non-reversible). </font> </td></tr>
<tr><td align=right><input type=radio name="avwknd" value="2"></td>
<td colspan=3><font size=2>Ignore weekends completely, count only weekdays</font></td></tr>
<tr><td colspan=4><b>&nbsp;&nbsp;How to Handle Events Scheduled on Weekends?</b></td></tr>
<tr><td align=right><input type=radio name="skwknd" value="0" checked> </td>
<td colspan=3><font size=2>Advance weekend events within the specified date range. </font></td></tr>
<tr><td align=right><input type=radio name="skwknd" value="1"></td>
<td colspan=3><font size=2>Do not advance weekend events.</font> </td></tr>
</table>
</td></tr>
<tr><td align=center><font size=2>
<b><input type=submit value="Submit">&nbsp;&nbsp;
<input type=button value=" Cancel " onclick="javascript:self.close();">
</b></td></tr>
</table></center>
</form></body></html>
END
    ;
	myexit(0);
    } elsif($command eq 'process') { #
	my $info = block_move();
	&headers('Block Move');
	print "<center><br>";
	print "<br><font color=#ff0000>Calendar Updated</font><br><br>";
	print "<br><table border=0><tr><td><font color=#0000cc>$info</font></td></tr></table><br><br>";
	print <<ENBD;
<table border=0 cellpadding=2><tr><td><form><b><input type=button value=" Close " 
onclick="javascript:opener.document.location.reload(1);self.close();"></b>
</form></td></tr></table>
ENBD
;
	print "</center></body></html>";
	exit(0);
    } else { &calerror("Don't know what to do.", -3); }      
}

sub block_move {
    my ($cat, $smn, $sdy, $syr, $emn, $edy, $eyr, $avwknd, $advance, $info, $skwknd);
    $cat = $::calinfo{'cat'};   $avwknd = $::calinfo{'avwknd'}; 
    $smn = $::calinfo{'smn'};   $sdy = $::calinfo{'sdy'};   $syr = $::calinfo{'syr'};
    $emn = $::calinfo{'emn'};   $edy = $::calinfo{'edy'};   $eyr = $::calinfo{'eyr'};
    $advance = $::calinfo{'advance'} || 0; $skwknd = $::calinfo{'skwknd'}; 
    if($advance == 0) { return "No events moved";}
    my $cpe = $::calinfo{'cpe'}; $cpe = "" if not $cpe; 
    my $who = $::calinfo{'w'};
    my $cal = "$::o{'spooldir'}/$who";
    my $file = "$cal/data";
    my ($href, $count, $key);
    $cat =~ s/^\s+|\s+$//g;
    $info = ""; $count = 10000; @::caldata=(); 
    my $ecount = &doReadFile($file); my %hash = ();
    for $href (@::caldata){my $dt=$href->{'date'};my $tag="$dt/0:0:0:$count";$count++;$hash{$tag}=$href;}
    my @keys = (keys %hash);
    $count = 0;
    my ($gcount, $rcount, $wcount, $ccount)=(0,0,0,0);
    my %modified = ();
    for $key (@keys) {
	$href = $hash{$key};
	next if($cat and $cat ne $href->{'cat'});
	if($cpe) { next if not $href->{'cp'};}

	my ($month, $day, $year) = split(/\//, $href->{'date'});
	next if &mdyAafterB($emn,$edy,$eyr,$month,$day,$year)==0;
	next if &mdyAafterB($month,$day,$year,$smn,$sdy,$syr)==0;

	if($href->{'seq'} =~ /^C/) { # corporate events
	    $ccount++;
	    next;
	}

	if(not $href->{'repeat'} or $href->{'repeat'} <= 1 or
	   not $href->{'occurs'} or $href->{'occurs'} eq 'OneTime') {
	    if($skwknd) {
		my $wkd = &wday($month-1,$day,$year);
		if($wkd == 0 or $wkd == 6) {
		    $wcount++;
		    next;
		}
	    }
	    my $att = $href->{'attendants'};
	    if($att) {
		my $mkey = $href->{'mkey'}; $mkey =~ s/_eMe_\d+//g;
		next if $mkey ne $who;
		$att =~ s/[,; ]+/:/g;  $att =~ s/:$//g;
		$att = &expandMeetingGroups($mkey, $att);
		my @list = split(/:/, $att); 
		my $acount=0;
		my $total = scalar @list;
		if($total) {
		    for $att (@list) {
			next if "$att" eq "$who";
			next if not -d "$::o{'spooldir'}/$att";
			$acount++;
		    }
		    if($acount > 0) { 
			$gcount++;
			next;
		    }
		}
	    }
	    # advance event date.
	    my ($nmonth, $nday, $nyear, $wday);
	    if(not $avwknd) { # make no distinction between weekdays and weekends
		($nmonth, $nday, $nyear)=
		    &canDate($month-1,$day+$advance,$year);
	    } elsif($avwknd == 1) { #push forward
		my $delta = 0;
		($nmonth, $nday, $nyear)=
		    &canDate($month-1,$day+$advance,$year);
		$wday = &wday($nmonth,$nday,$nyear);
		if($wday == 0) { 
		    if($advance > 0) { $delta =1;}
		    else { $delta = -2;}
		} elsif($wday == 6) {
		    if($advance > 0) { $delta =2;}
		    else { $delta = -1};
		}
		if($delta) {
		    $advance += $delta;
		    ($nmonth, $nday, $nyear) =
			&canDate($nmonth,$nday+$delta,$nyear);
		}
	    } elsif($avwknd == 2) { # count only weekdays
		($nmonth,$nday,$nyear) = advance_n_weekdays($month-1,$day,$year,$advance);
	    }

	    $nmonth += 1;
	    my $newdate = "$nmonth/$nday/$nyear";
	    my $ekey = $href->{'key'};
	    $modified{$ekey} =  $newdate;
	    $count++;
	} else {
	    $rcount++;
	}
    }
    if($count) {
	my $fhdl = gensym;
	if(sysopen($fhdl, "$file", O_WRONLY | O_CREAT, 0644)) {
	    &webcalLock::doflock( \*$fhdl, LOCK_EX, "$file") or
		&calerror("Cannot lock file '$file': $!\n",1);     
	    my $FHANDLE=\*$fhdl;
	    @::caldata=(); 
	    $ecount= do $file;
            truncate($FHANDLE, 0);
	    print $FHANDLE "\@::caldata = (\n";
	    for $href (@::caldata) {
		my $ekey = $href->{'key'};
		if($modified{$ekey}) {
		    $href->{'date'} = $modified{$ekey};
		    my $enddate = &findEndDateHref($href);
		    if($enddate) { $href->{'end'} = $enddate;}		    
		}
		my $tmp = &print1Entry($href);
		print $FHANDLE $tmp;
	    }
	    print $FHANDLE "\n);\n$ecount;\n";
	    &webcalLock::doflock(\*$fhdl, LOCK_UN, "$file") or
		&wencalSupport::calerror("Cannot lock file '$file': $!\n",1); 
	    close $fhdl;
	}
    }
    if($rcount) { $info .= "$rcount recurrent event(s) ignored.<br>";}
    if($gcount) { $info .= "$gcount group event(s) ignored.<br>";}
    if($wcount) { $info .= "$wcount weekend event(s) ignored.<br>";}
    if($ccount) { $info .= "$ccount corporate event(s) ignored.<br>";}
    return "<font color=#00cc00>" . $info . "</font>$count event(s) has been modified";
} 
# returns the mm/dd/yyyy that is $advance weekdays from the given date
# month: 0--11, day 1-31, year xxxx
sub advance_n_weekdays {
    use integer;
    my ($month,$day,$year,$advance) = (@_);
    my ($wday, $nwks, $frac, $delta, $rem, $sign);
    my ($nmth, $ndy, $nyr, $adv, $wkdays);
    $delta = 0; $rem = 0; $wday = &wday($month,$day,$year);
    if($wday == 0) { $delta = 0; $rem = 0;}
    elsif($wday == 6) { $delta = 1; $rem = 0;}
    else { $rem = 5-$wday;$delta=$rem;$delta+=2 if $advance>$rem;}
    $wkdays=$advance-$rem;$nwks=($wkdays)/5;$rem=$wkdays-$nwks*5;$adv=$nwks*7+$rem; 
    ($nmth, $ndy, $nyr)= &canDate($month,$day+$adv+$delta,$year);
    return ($nmth, $ndy, $nyr);
}    

#===============================================================================================
sub webcal_handler {
  my ($method, $buffer, $command, $username, $calname, $scriptname, $signup, @nvpairs, $pair, $name, $value);
  
  $method=$ENV{'REQUEST_METHOD'} or die("To be used as a CGI-BIN program!");
  $scriptname = $ENV{'SCRIPT_NAME'};

  $ENV{PATH} = "/bin:/usr/bin";
  &initVars;
  &webcalVirtual::initVirtualServer();
  #------------------------------------------------------
  # DND works only for IE 5.5 and up == mzou 07/19/2004
  if($::o{'dnd'}) {
      my $agent = $ENV{'HTTP_USER_AGENT'} || "";
      my $ie55up = 0;
      if($agent =~ /MSIE\s+(\d+\.\d*)/i) {
	  my $version = $1;
	  if($version + 0.0 >= 5.5) { $ie55up=1;}
      }
      $::o{'dnd'} = $ie55up;
  }
  #------------------------------------------------------
  $buffer="";
  if( $scriptname =~ /signup\.cgi$/ and $webcalConfig::r{'cookieAuth'} ==0 ) { $signup = 1;} else { $signup = 0;}
  
  if($method eq 'GET') {if(defined $ENV{'QUERY_STRING'}) { $buffer = $ENV{'QUERY_STRING'};}}
  else { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});}

  if($::o{'logging'})  {&wlog($buffer);}
  if($signup && $method eq 'GET' ) { $buffer=""; }

  # parse query parameters
  @nvpairs = split(/&/, $buffer || "");
  foreach $pair (@nvpairs) {
    ($name, $value) = split(/=/, $pair, 2);
    next if !defined $name or $name eq "";
    $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
    if($name eq 'stopic' or $name eq 'nmotd') { $value = &urldecode($value,0); }
    else {$value = &urldecode($value,1); }
    
    # If they try to include server side includes, erase them.
    #$value =~ s/<!--(.|\n)*-->//g;
    if ( $name eq "d") {
      my ($mn, $dy, $yr, $hr, $min) = split(/\//, $value);
      if($yr< 1900) { if($yr<90) {$yr += 100;}  $yr += 1900;}
      elsif($yr <= 1753) { $yr = 1753;}
      $::calinfo{'year'} = 0+$yr;
      $::calinfo{'month'} = 0+$mn;
      $::calinfo{'day'} = 0+$dy;
      if(defined $hr) {
	  if(!$hr){ $hr = 0;} $::calinfo{'hour'} = 0+$hr;
	  if(! defined($min)) {$min=0;}  $::calinfo{'min'} = 0+$min;
      }
    }
    if ($name =~ /\[\]$/i) {	# [] = array = select_multiple result
      $name =~ s/\[\]$//i;
      if (defined $::calinfo{$name} && $::calinfo{$name} ne "") {
	$::calinfo{$name} = $::calinfo{$name}.":".$value;
      } else {
	$::calinfo{$name} = $value;
      }
    } else {
      $::calinfo{$name} = $value;
    }
  }
  # end of parse

  $command = $::calinfo{'c'};

  # signup
  if($signup or $command eq 'signup' or $command eq 'setup') {
#    if($::o{'create'} == 0) {
	if($webcalConfig::r{'cookieAuth'}) {
	    my $whoami = &readCookie('wcalusername');
	    my $mcookie = 'wcalpassword';
	    my $magic = &readCookie($mcookie);
	    my ($magvalid, $message) = &webcalAuth::VerifyCryptedPassword($whoami,$magic);
	    if($magvalid) {  $::d{'remote_user'} = $whoami;}
	} else {
	    if(exists $ENV{'REMOTE_USER'} and $ENV{'REMOTE_USER'}) {
		$::d{'remote_user'} = $ENV{'REMOTE_USER'};
	    }
	}
#   } 
    &loadLangfile;
    &make_style_sheet(""); 
    &setup(0);
    &myexit(0);
  }

  if($::calinfo{'calendar'}) { $::calinfo{'w'} = $::calinfo{'calendar'};}

  #==== 09072001: mzou
  # code seg moved to webcalSupport.pm
  $command= &authenticate($command, $scriptname);
  #==== 

  #==== 09072001: mzou
  # code seg moved to webcalSupport.pm
  $command = &find_and_set_calendarName($command, $scriptname);
  #==== 

  #==== 09072001: mzou  
  &nobodySignoff($command);
  #==== 


  if (! $::o{'spooldir'} =~ /^(\/[^.]*)$/) {
      &make_style_sheet(""); 
      &loadLangfile;
      &calerror("$::phr{'Invalidspooldir'} $::o{'spooldir'}");
  }
  $username=$::calinfo{'w'};
  if($command eq 'plogin') {   $::calinfo{'c'} = $command = 'get';  }
  $::calinfo{'w'} = $username = &untaintname($username,$::phr{'Invalidusername'});

  $calname="$::o{'spooldir'}/$username";

  if ( -d $calname && -f "$calname/data" ) {

    # read in calendar info
    if( -f "$calname/info") { &doReadFile("$calname/info"); }

    &make_style_sheet(""); 

    $::d{'authResult'} = &doauth();
    if(defined $::calinfo{'ctype'} and $::calinfo{'ctype'} =~ 'public') { 
	if($::d{'remote_user'} ne 'anonymous' and $::d{'remote_user'} ne 'nobody') {
	    $::d{'ispublic'} = 4;
	} elsif($::calinfo{'aap'}) {
	    $::d{'ispublic'} = 4;  $::d{'validuser'} = 1;    
	} else {
	    $::d{'ispublic'} = 0;	    
	}
    }
    else { # need an identity in order to view private calendar
      if($::d{'remote_user'} eq "") {
          &vlogin;
      }
    }

    if($command eq 'dooption') {
      # parse the command args again
      my ($ows, $nws, $odctoc, $ndctoc) = (0,0,0,0);
      $odctoc = $::calinfo{'dctoc'} if exists $::calinfo{'dctoc'};
      $ows = $::calinfo{'weekstart'} if exists $::calinfo{'weekstart'};
      foreach $pair (@nvpairs) {
	($name, $value) = split(/=/, $pair, 2);
	$name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
	if(defined $::opnames{$name}) {
	    if($name ne 'hdr' and $name ne 'ftr') { $value = &urldecode($value,1);}
	     else {
		$value = &urldecode($value,0);
                if($name eq "toffset"){my($h,$m)=split(/:/,$value,2); if(!$m){$m=0;};if(0+$h<0){$value=-(-$h*60+$m);}else {$value=$h*60+$m;}$value *= 60;}
	    }
	    if ($name =~ /\[\]$/i) {	# [] = array = select_multiple result
	      $name =~ s/\[\]$//i;
	      if (defined $::calinfo{$name} && $::calinfo{$name} ne "") {
		  $::calinfo{$name} = $::calinfo{$name}.":".$value;
	      } else {
		$::calinfo{$name} = $value;
	      }
	    } else {
		$::calinfo{$name} = $value;
	    }
       }
	$nws = $::calinfo{'weekstart'} if exists $::calinfo{'weekstart'};
	$ndctoc = $::calinfo{'dctoc'}  if exists $::calinfo{'dctoc'};
	if($nws != $ows or $ndctoc > $odctoc) { $::calinfo{'expirecache'} = 1;}
    }
  }

    #==== 09072001: mzou  
    &setPersonalDisplayParams;
    #==== 

    #==== 09072001: mzou  
    &convertToWcalDatesAll;
    #==== 

    #==== 09072001: mzou  
    &getSetCurrentDateTime();
    #==== 

    # read in the interface phrases
    &loadLangfile;
    
    if($::calinfo{'ls'} and $::calinfo{'ls'} < 0) { # when run under mod_perl, need to restore bgcolor ...
	if(! exists $webcalConfig::r{'backgroundColor_save'}) {
	    $webcalConfig::r{'backgroundColor_save'}=$webcalConfig::r{'backgroundColor'};
        }
	$webcalConfig::r{'backgroundColor'}="#ffffff";
    } else {
	if(exists $webcalConfig::r{'backgroundColor_save'}) {
	    $webcalConfig::r{'backgroundColor'} = $webcalConfig::r{'backgroundColor_save'};
       }
    }

    if ($command eq 'logout')  {
      if($webcalConfig::r{'cookieAuth'}) {
	  &cookieLogout($scriptname); &myexit(0);
      } else {
	  &dologout; &myexit(0);
      }
    }
    elsif ( $command eq 'signoff') { &signoff; &myexit(0);}
    elsif ( $command eq 'cfreq') { &cfreq(0); &myexit(0);}
    elsif ( $command =~ 'showclr') { &popupClrSelect($command); &myexit(0);}
    elsif ( $command eq 'showmgps'){ &showMGroups; &myexit(0);}
    elsif ( $command eq 'getcal'){ &getCalendars(1); &myexit(0);}
    elsif ( $command eq 'listcal'){ &getCalendars(-1); &myexit(0);}
    elsif ( $command eq 'delcal'){ &getCalendars(2); &myexit(0);}
    elsif ($command eq 'getcala'){ &getCalendars(0); &myexit(0);}    
    elsif ( $command eq 'showgmgps'){ &showGMGroups; &myexit(0);}
    elsif ( $command =~ 'smallcal'){ &smallCal; &myexit(0);}
    elsif ( $command eq 'reviewUI') { &reviewUpload; &myexit(0);}
    elsif ( $command eq 'simage') { &showAvailableImages; &myexit(0);}
    elsif ( $command eq 'doReviewUI') { &doReviewUpload; &myexit(0);}
    elsif ( $command eq 'motd') { &motd(0); &myexit(0);}
    elsif ( $command eq 'pending') { &attendPending(0); &myexit(0);}
    elsif ( $command eq 'gEaddr') { $::calinfo{'nhd'}=1; &address('ad'); &myexit(0);}

    if(not $::calinfo{'v'}) {  $::calinfo{'v'} = $::calinfo{'dview'} ?  $::calinfo{'dview'} : 3 ;  }

    if ( $command eq 'ad') { &address('ad');  &myexit(0);}
    elsif ( $command eq 'sad') { &address('sad');  &myexit(0); }
    elsif ( $command eq 'ead') { &address('ead');  &myexit(0); }
    elsif ( $command eq 'dad') { &vlogin; &address('dad'); &myexit(0); }
    elsif ( $command eq 'm2'){ &mailto(0,0,0); &myexit(0);}
    elsif ( $command eq 'fm2'){ &mailto(0,0,1); &myexit(0);}
    elsif ( $command eq 'ec'){ &mailto(0,1,0); &myexit(0);}
    elsif ( $command eq 'vc'){ &dovcal(0); &myexit(0);}
    elsif ( $command eq 'vcard') { &dovcard(0);  &myexit(0); }
    elsif ( $command eq 'dvcard') { &dovcard(1);  &myexit(0); }
    elsif ( $command eq 'dabk') { &exportAddressBook(); &myexit(0); }
    elsif ( $command eq 'gotod') { &dogoto; &myexit(0); }
    elsif ( $command eq 'option')   { &option_admin('o'); &myexit(0); }
    elsif ( $command eq 'dooption') { &vlogin; &dooption; &myexit(0);}
    elsif ( $command eq 'cpair')   { &cpair; &myexit(0); }
    elsif ( $command eq 'admin')    { &option_admin('a'); &myexit(0); }
    elsif ( $command eq 'notes')    { &notes; &myexit(0); }
    elsif ( $command eq 'search')   { &search; &myexit(0); }
    elsif ( $command eq 'warn')     { &dowarn; &myexit(0);}
    elsif ( $command eq 'compare')  { &compare; &myexit(0);}
    elsif ( $command eq 'version' or $command eq 'showVersion') { &showVersion; &myexit(0);}
    elsif ( $command eq 'ctd')      { &showCEvents;  &myexit(0);}
    elsif ( $command eq 'diary')    { &diary('r');  &myexit(0); }
    elsif ( $command eq 'ediary')    { &diary('e');  &myexit(0); }
    elsif ( $command eq 'ndiary')    { &diary('n');  &myexit(0); }
    elsif ( $command eq 'sdiary')    { &diary('s'); &myexit(0);}
    elsif ( $command eq 'wdiary')    {&vlogin; &diary('w');  &myexit(0);}
    elsif ( $command eq 'qa')    { &quickadd(); &myexit(0);}
    elsif ( $command eq 'dnd')    { &dodnd(); &myexit(0);}
    elsif ( $command eq 'bkm')    { &doblock_move(); &myexit(0);}
    elsif ( $command eq 'sum')    { &summary(); &myexit(0); }
    elsif ( $command eq 'dm2'){ 
	if($::calinfo{'action'} eq "$::phr{'Cancel'}") {
            $::calinfo{'c'}='get';  &readData; 
            &calendar; 
        } else {&mailto(1,0,0);  }
        &myexit(0);
    }
    elsif ( $command eq 'dvc'){ 
	# print "Content-type: text/html\n\n";
	# my ($k, $v);foreach $k (keys %::calinfo) { $v = $::calinfo{$k}; print "$k=>$v<br>";}exit 0;
	if($::calinfo{'action'} eq "$::phr{'Cancel'}") {
            $::calinfo{'c'}='get';  &readData; 
            &calendar;
        } else { &dovcal(1);}
        &myexit(0);
    }
   elsif ( $command eq 'task') { 
       if(defined $::calinfo{'mg'} and $::calinfo{'mg'}) {
           my $tmp = $::calinfo{'mg'};
           $::calinfo{'mattendants'} = $tmp;
         }
        &tasks; &myexit(0); 
   }
   elsif ( $command eq 'dim') { 
       &readData;         
       &doimport;   
       &myexit(0);;         
   }
  elsif($command eq 'navigation_table') { 
      &navigation_table();
      &myexit(0);;               
  }

   if ($command eq 'get' )   {
      if(defined $::calinfo{'mg'} and $::calinfo{'mg'}) {
	my $tmp = $::calinfo{'mg'};
	$::calinfo{'mattendants'} = $tmp;
	&docompare('0');
      } else{
        &readData;         
        #do "$calname/data";
        &calendar;
       }
      &myexit(0);
    } elsif($command eq 'remind') { &reminders_only; &myexit(0);}

    if ( $command eq 'ed') {
        &readData;         
	&edit('edit');  &myexit(0); 
    }
    elsif ( $command eq 'ne') {
      if(exists $::calinfo{'action'} and $::calinfo{'action'} eq "Cancel") {
	if(defined $::calinfo{'mg'} and $::calinfo{'mg'}) {
	  my $tmp = $::calinfo{'mg'};
	  $::calinfo{'mattendants'} = $tmp;
	  &docompare('0');
	} else{
            &readData;         
	    #do "$calname/data";
	    &calendar;
	}
      } else { &readData; &edit('nevent'); }
      &myexit(0);
    }
   elsif ( $command eq 'dogoto') {
      my ($mn, $dy, $yr) =  &canDate($::calinfo{'month'},$::calinfo{'day'},$::calinfo{'year'});
      ($::calinfo{'month'},$::calinfo{'day'},$::calinfo{'year'}) = ($mn, $dy, $yr);
      if(defined $::calinfo{'mg'} and $::calinfo{'mg'}) {
	my $tmp = $::calinfo{'mg'};
	$::calinfo{'mattendants'} = $tmp;
	&docompare('0');
      } else {
         &readData;         
         # do "$calname/data";
         &calendar;
      }
      &myexit(0);
   } 
   # 10-11-2001: make these functions do file locking properly. 
   # These four functions are responsible for updating calendar data.
   elsif( $command eq 'docfm'){ &docfmInvitation(); }
   elsif ( $command eq 'etsk'){ &etask(); }
   elsif ( $command eq 'doedit') {&vlogin; &doedit; }

    # read in calendar data.   These functions does not update calendar data
    &doReadFile("$calname/data") or &calerror("Cannot open file '$calname/data': $!\n");
    if ( $command eq 'cfm'){ &cfmInvitation(); }
    elsif ( $command eq 'docompare'){ &docompare('t'); }
    elsif ( $command eq 'doadmin') {
	my $sc = $::calinfo{'ac'};
	if ( $sc eq 'acmerge')  { &doadmin('acmerge'); }
	elsif ( $sc eq 'acdanger') { &doadmin('acdanger'); }	
	elsif ( $sc eq 'acpasswd') { &doadmin('acpasswd'); }
	elsif ( $sc eq 'rspasswd') { &doadmin('rspasswd'); }
	elsif ( $sc eq 'acmtgrp')  { &doadmin('acmtgrp');  }
	elsif ( $sc eq 'acgmtgrp') { &doadmin('acgmtgrp'); }
	elsif ( $sc eq 'download') { &download; }	
	&myexit(0);
    }

    elsif ( $command eq 'greeting') { &greeting(); }
    elsif ( $command eq 'dosearch') {
	if($::o{'search_filter'}) { 

	    &calendar;
	}
	else { &dosearch; }
    } else { &calerror("$::phr{'Unknown_command'} \"$command\"");}
 } else {
    &loadLangfile;
    if ($command eq 'getcal'){ &getCalendars(1); &myexit(0);}
    elsif ($command eq 'getcala'){ &getCalendars(0); &myexit(0);}    
    if($username) {
        if($webcalConfig::r{'cookieAuth'}) {
          &cookieLogin("","$::phr{'Couldnotfindcalendar'} \'$username\'.", "");
        } else {
          &greeting("$::phr{'Couldnotfindcalendar'} \'$username\'.");
        }
    } else {
        if($webcalConfig::r{'cookieAuth'}) {
          &cookieLogin("","$::phr{'Couldnotfindcalendar'} \'$username\'.","");
         } else {
          &greeting("");
         }
     }
  }
  &myexit(0);
}
#===============================================================================================

1;

