#!/usr/bin/perl 
# $Revision: 108 $ $URL: svn://127.0.0.1/petalpushers/trunk/cgi/res $

use lib '/home/145357/users/.home/domains/petalpushers.org/cgi-bin'; 
use MIME::Lite;
use POSIX qw/strftime tzset/;
use Date::Manip;
use File::Temp qw/tempfile/;
use CGI::Auth;
use HTML::Template;
use Digest::MD5;
use Spreadsheet::WriteExcel;
use Net::HTTP;

use strict;
use warnings;
no warnings qw/uninitialized/;

# Change if necessary
my $location ='/cgi-bin/res';
my $resdataprefix ='/home/145357/users/.home/domains/petalpushers.org/html/res';
my $authdir=       "$resdataprefix/auth";
my $adm=0;
my $auth;
my $cookie;
my $show_date;

if((! defined($ENV{'SERVER_NAME'})) || ($ENV{'SERVER_NAME'} eq 'p'))
{
		$resdataprefix ='/home/pp/g/res';
		$authdir=      "$resdataprefix/auth";
		use CGI::Carp qw/fatalsToBrowser/;
		#use CGI::Pretty qw(-debug :cgi -private_tempfiles -nosticky -no_xhtml -newstyle_urls :all *table *div *Tr *td *center *ul *li *comment *noscript :cgi-lib *pre *script);
}
else
{
		use CGI qw(:cgi -private_tempfiles -nosticky -no_xhtml -newstyle_urls :all *table *div *Tr *td *center *ul *li *comment *noscript :cgi-lib *pre *script);
}
$CGI::POST_MAX=1024 * 1000;  # max 1M posts
$CGI::DISABLE_UPLOADS=1;

my $ppdates = "$resdataprefix/ppdates";
my $ppfloats = "$resdataprefix/ppfloats";
my(%floats,@float,@f,%flabels);

# Shift Status 
my($DAY_PENDING,$DAY_APPROVED,$DAY_NOT_APPROVED)=(0,1,2);

use FileHandle;
STDOUT->autoflush(1);
# Set timezone to US/Pacific
$ENV{'TZ'}='US/Pacific';
tzset();

my $show_season_closed;
$show_season_closed = "$resdataprefix/show_season_closed";

# ppdates is Type [Detail Day|Decorating Day]|Start Date Time|Duration
open(PP,$ppdates) || die "Cannot open $ppdates";
my @ppdate;
my(%dates,$date);
my($today)=UnixDate(ParseDate('today 00:00:00'),"\045s");
import_names();

# Load dates
while (<PP>)
{
	chomp;
	if(/[#]/) { next }
    
	@ppdate=split(/\|/);
	$date=ParseDate($ppdate[1]);
	$dates{$date}{'daytype'}=$ppdate[0];
	$dates{$date}{'shiftstart'}=$ppdate[1];
	$dates{$date}{'shiftdur'}=$ppdate[2];
	$dates{$date}{'status'}=$ppdate[3];
	$dates{$date}{'display'}=UnixDate($date,"\045A, \045f.\045e.\045Y \045i:\045M\045p - ");
	$dates{$date}{'sec'}=UnixDate($date,"\045s");
	my($dc)=DateCalc($date,$ppdate[2]);
	if($date eq $dc)
	{
		$dates{$date}{'display'}.='Completion';
	}
	else
	{
		$dates{$date}{'display'}.=UnixDate(DateCalc($date,$ppdate[2]),"\045i:\045M\045p");
	}
	$dates{$date}{'display'} =~ s/\s(\s)/$1/g;
	$dates{$date}{'display'} =~ s/:00//g;
	$dates{$date}{'display'} =~ s/(\.)\s(\d)/$1$2/g;
	$dates{$date}{'display'} =~ s/(AM|PM)/\L$1/g;
}
close PP;

my($nextpage)='startpage';
if(defined($Q::nextpage)) { $nextpage=$Q::nextpage }

if(defined($Q::adm))
{
		getLogin();
		$adm=1;
		if(! defined($Q::nextpage)) { $nextpage='startpageadm' }
}

# Main switch
if($nextpage eq 'startpage')
{
	start_page();
	exit;
}
elsif($nextpage eq 'startpageload')
{
		if($Q::load) { loadfile($Q::load)}
		start_page();
		exit;
}
elsif($nextpage eq 'startpageadm' && $adm)
{
	start_page_adm();
	exit;
}
elsif($nextpage eq 'review')
{
	send_approve_page(1);
	exit;
}
elsif($nextpage eq 'send')
{
		# If here, we will send
		if($Q::submit_date eq '') { param(-name=>'submit_date',-value=>ParseDate('now')); }
		param(-name=>'res_version',-value=>'$Revision: 108 $');
		Delete('nextpage');
		#add_dd();
		send_email();
		(defined($Q::load) ? save_boulder_file($Q::load) : save_boulder_file());
		
		if($adm)
		{
			if($Q::load)
			{
			print redirect(-uri=>"$location?adm=1;nextpage=startpageadm;" . $auth->sfparam_name . '=' . $auth->sfparam_value,-status=>301);
			}
			else
			{
			print redirect(-uri=>"$location?adm=1;nextpage=startpage;" . $auth->sfparam_name . '=' . $auth->sfparam_value,-status=>301);
			}
			exit;
		}	
		send_thankyou_page();
		exit;
}
elsif($nextpage eq 'changestatus')
{
		update_requests();
		print redirect(-uri=>"$location?adm=1;nextpage=startpageadm;" . $auth->sfparam_name . '=' . $auth->sfparam_value,-status=>301);
		exit;
}
elsif($nextpage eq 'logout')
{
		$auth->endsession;
		print redirect(-uri=>"$location?adm=1",-status=>301);
		exit;
}
elsif($nextpage eq 'search')
{
		send_search_page();
		exit;
}
elsif($nextpage eq 'resend')
{
		resend_confirmation();
		print redirect(-uri=>"$location?adm=1;nextpage=startpageadm;" . $auth->sfparam_name . '=' . $auth->sfparam_value,-status=>301);
		exit;
}
elsif($nextpage eq 'show_dates')
{
		$cookie=cookie(-name=>'show_dates',-path=>'/cgi-bin/res',-expire=>'+60d',-value=>$Q::show_dates);
		$show_date=$Q::show_dates;
		start_page_adm();
		exit;
}
elsif($nextpage eq 'approved_update')
{
	update_count();
	start_page_adm();
	exit;
}
elsif($nextpage eq 'report')
{
	send_report();
	exit
}

start_page();
exit;

sub start_page
{
		autoEscape(0);
		my($title)=($adm ? 'Petal Pushers&reg; Scheduling System' : 'Petal Pushers&reg; Online Work Request');
        
		print header,start_html({title=>$title,
			-script=>[{-src=>'/res/res.js',-type=>'text/javascript'}
			],
			head=>[
				Link({rel=>'SHORTCUT ICON',href=>'/favicon.ico'}),
				Link({rel=>'StyleSheet',href=>'/res/res.css',type=>'text/css'}),
				Link({rel=>'StyleSheet',href=>'/res/menu.css',type=>'text/css'}),
				Link({rel=>'StyleSheet',href=>'/inc/style.css',type=>'text/css'})
			]});

		my $s = Net::HTTP->new(Host => 'petalpushers.org') || die $@;
		$s->write_request(GET => '/inc/top.php', 'User-Agent' => "Mozilla/5.0");
		my($code, $mess, %h) = $s->read_response_headers;

		while (1) {

			my $buf;
			my $n = $s->read_entity_body($buf, 1024);
			die "read failed: $!" unless defined $n;
			last unless $n;
			print $buf;
		}

		print noscript(div({class=>'err',align=>'center'},'Javascript has been disabled 
		in the browser.<br />This application requires javascript to be enabled in the 
		browser.'));
		autoEscape(1);

		print start_center,start_div({style=>'width: 765px;  margin: 5px'});
		showmenu(2);
		print h3({align=>'center'},'Petal Pushers&reg; Work Schedule Request');
        
        if(-e $show_season_closed) {
        
            print '<div>Registration begins on April 1st.</div>';
        }


		if(! $adm)
		{
		print start_div({class=>'ind'}),
		p('Welcome to the Petal Pushers&reg; online Work Schedule Request form. Just fill-in
		some contact information and choose your volunteer dates.  Some of the fields
		are required.  The required fields are: Number of Adults, Contact Person 1, Email and
		a (Day/Evening/Mobile) phone number.  After you have completed the form,
		click the &ldquo;Approve&rdquo; button at the bottom of the screen.  The next
		screen will be a final review page that shows the information you
		have entered.  On this screen you will be asked to send the
		information to our reservation system.  Upon receiving the information, our system will send a copy of the Work Request to the email address(s) listed in the
		form.  The next step in the reservation process is for Petal Pushers to
		schedule and confirm your dates into the system.  After we shedule the
		request into the system, we will send you a confirmation email.  Please allow three weeks for this process to occur before you contact 
		us with your Work Request status questions.  We will speed up the process
		as the month of December approaches.  Every year we coordinate hundreds of requests representing over 5,000 volunteers.  Thank
		you for your patience.  God Bless.'),
		end_div,
		h5({align=>'center'},'(Please do not over estimate your group size)');
		}

		if($adm)
		{
			print start_form({id=>'theform',onSubmit=>'return validate(1)',action=>$location});
		}
		else
		{
			print start_form({id=>'theform',onSubmit=>'return validate()',action=>$location});
		}

		# Used only for debug'n
		if(! defined($ENV{'SERVER_NAME'}) || $ENV{'SERVER_NAME'} eq 'p')
		{
			print div({align=>'center'},script({type=>'text/javascript'},'makesubmit(\'\',\'Review\',\'\')'));
		}
		print start_div({style=>'padding: 10px 10px'});
		print start_table({class=>'formtbl'});
		print Tr(td(b('Organization: '),input({name=>'orgname',value=>"$Q::orgname",size=>60,onkeypress=>'return handleEnter(this,event)'}))),
	
			Tr(td(b({id=>'num_of_adultsL'},'Adults: '),
			input({name=>'num_of_adults',value=>"$Q::num_of_adults",id=>'num_of_adults',size=>2,maxlength=>3,onkeypress=>'return handleEnter(this,event)'}),
			' (One adult for every five youths ages 13 - 18) ',
			b({id=>'num_of_youthsL'},' Youths: '),
			input({name=>'num_of_youths',id=>'num_of_youths',value=>"$Q::num_of_youths",size=>2,maxlength=>3,onkeypress=>'return handleEnter(this,event)'}),br)),
            
			Tr(
            '<td  style = "text-align: left"><table>
            <tr>
            <td id = "name1L" style = "text-align: right; font-weight: bold">Contact Person 1:&nbsp;</td>
            <td><input size = "40" onkeypress = "return handleEnter(this, event)" name = "name1" value = "' . $Q::name1 . '"/></td>
            </tr>
            <tr>
            <td id = "email1L" style = "font-weight: bold; text-align: right">Email 1:&nbsp;</td>
            <td><input name = "email1" id = "email1" size = "40" onkeypress = "return handleEnter(this, event)" value = "' . $Q::email1 . '"/></td>
            </tr>
            <tr><td colspan = "2">&nbsp;</td></tr>
            <tr>
            <td id = "name2L" style = "text-align: right; font-weight: bold">Contact Person 2:&nbsp;</td>
            <td><input size = "40" onkeypress = "return handleEnter(this, event)" name = "name2" value = "' . $Q::name2 . '"/></td>
            </tr>
            <tr>
            <td id = "email2L" style = "font-weight: bold; text-align: right">Email 2:&nbsp;</td>
            <td><input name = "email2" id = "email2" size = "40" onkeypress = "return handleEnter(this, event)" value = "' . $Q::email2 . '"/></td>
            </tr>            
            <tr><td colspan = "2">&nbsp;</td></tr>
            <tr>
            <td id = "day_phL" style = "text-align: right; font-weight: bold">Day Phone:&nbsp;<span id = "day_phT" style = "display: none">Format: 714-555-1212</span></td>
            <td><input onfocus = "showtip(' . "'day_ph'" . ', 1)" onchange = "showtip(' . "'day_ph'".', 0)" onblur = "showtip(' . "'day_ph'". ', 0)" name = "day_ph" id = "day_ph" value = "' . $Q::day_ph . '" size = "20" onkeypress = "handleEnter(this, event)"/></td>
            </tr>
            <tr>            
<td id = "evening_phL" style = "text-align: right; font-weight: bold">Evening Phone:&nbsp;<span id = "evening_phT" style = "display: none">Format: 714-555-1212</span></td>
            <td><input onfocus = "showtip(' . "'evening_ph'" . ', 1)" onchange = "showtip(' . "'evening_ph'".', 0)" onblur = "showtip(' . "'evening_ph'". ', 0)" name = "evening_ph" id = "evening_ph" value = "' . $Q::evening_ph . '" size = "20" onkeypress = "handleEnter(this, event)"/></td>
            </tr>
            <tr>            
<td id = "mobile_phL" style = "text-align: right; font-weight: bold">Mobile Phone:&nbsp;<span id = "mobile_phT" style = "display: none">Format: 714-555-1212</span></td>
            <td><input onfocus = "showtip(' . "'mobile_ph'" . ', 1)" onchange = "showtip(' . "'mobile_ph'".', 0)" onblur = "showtip(' . "'mobile_ph'". ', 0)" name = "mobile_ph" id = "mobile_ph" value = "' . $Q::mobile_ph . '" size = "20" onkeypress = "handleEnter(this, event)"/></td>            
            </tr>            
            </table></td>'
            ),
			
			Tr(td(
				start_table(),
				Tr(
					td(b({id=>'addr1L'},'Address Line 1:&nbsp;')),
					td(input({id=>'addr1',name=>'addr1',value=>"$Q::addr1",size=>40,onkeypress=>'return handleEnter(this,event)'}))
				),
				Tr(
					td(b({id=>'addr2L'},'Address Line 2:&nbsp;')),
					td(input({id=>'addr2',name=>'addr2',value=>"$Q::addr2",size=>40,onkeypress=>'return handleEnter(this,event)'}))
				),
				Tr(
					td({style=>'text-align: right'},b({id=>'cityL'},'City:&nbsp;')),
					td(
						input({id=>'city',name=>'city',value=>"$Q::city",size=>30,maxlength=>40,onkeypress=>'return handleEnter(this,event)'}),
						b({id=>'stL'},' State:&nbsp;'),
						input({id=>'st',name=>'st',value=>"$Q::st",size=>2,maxlength=>2,onkeypress=>'return handleEnter(this,event)'}),
						b({id=>'zipL'},' Zip:&nbsp;'),
						input({id=>'zip',name=>'zip',value=>"$Q::zip",size=>11,maxlength=>10,onkeypress=>'return handleEnter(this,event)'})
					)
				),
				end_table,
			)),
			Tr(td(
				start_table(),
				Tr(
					td({style=>'vertical-align: top'},b('Comments: ')),
					td(textarea({name=>'comments',id=>'comments',
					onKeyDown=>"textCounter(this,'progressbar1',500)",
					onKeyUp=>"textCounter(this,'progressbar1',500)",
					onFocus=>"showpbar('progressbar1',1);textCounter(this,'progressbar1',500)",
					onBlur=>"showpbar('progressbar1',0)",
					rows=>10,columns=>72,value=>"$Q::comments"}),
					div({id=>'progressbar1',class=>'progress'},undef))
				),end_table,))
		;	
		print end_table;
		print script({type=>'text/javascript'},'textCounter(document.getElementById("comments"),"progressbar1",500)');
		if($adm) { print br; }
		else
		{
		print p({style=>'text-align: center; font-weight: bold'},
        'Petal Pushers&reg; shirts are optional on Detail Days.<br />
		Petal Pushers&reg; shirts from any year are required on Decorating Days.');
        
        print a({name=>'shifts'},'');

		print start_div({class=>'ind'}),
		p('We could especially use your help during the Detail Days and early
		Decorating Days.  While you are looking at your schedule...  How about
		joining us at the ',a({href=>'http://www.petalpushers.org/party_index.php'},'Behind the Scenes Party'),' as an early prelude to your New Year\'s plans?  You will get a chance to &ldquo;Smell the roses&rdquo;, view the finished floats and celebrate with a good meal.  All of the
		proceeds of the party are donated to cover the costs of the float.
		'),
		end_div;
		}
               
		my(%old_dd);
		if($Q::load && $Q::dd)
		{
			foreach (@Q::dd)
			{
				my(@ddline)=split / /;
				# date shift status
				$old_dd{$ddline[0]}{'shift'}=$ddline[1];
				$old_dd{$ddline[0]}{'status'}=$ddline[2];
			}
		}
		
		my(@pa); 
		my($cell)=0;
		my($c1,$c2);

		print start_div({align=>'center'}),start_table({class=>'shifttbl'});
		print Tr(th('Event'),th('Day'),th({colspan=>3},'Shift'),th('Choice'));
		foreach (sort(keys(%dates)))
		{
			@pa=split(/ /,$dates{$_}{'display'});
			print start_Tr({style=>((($cell / 2) % 2) == 1 ? 'background-color: #f0f0f0': '')}),
				td({style=>'text-align: center'},($dates{$_}{'daytype'} == 0 ? 'Detail Day' : 'Decorating Day')),
				td("$pa[0] $pa[1]"),
				td({style=>'text-align: right; padding-right: 0'},$pa[2]),
				td({style=>'padding-left: 2px; padding-right: 2px; margin: 0'},$pa[3]),
				td({style=>'text-align: left; padding-left: 0'},$pa[4])
			;

			$c1=($old_dd{$_}{'shift'} == 1 ? 1 : 0);
			$c2=($old_dd{$_}{'shift'} == 2 ? 1 : 0);

			if($adm)
			{
				autoEscape(0);
				print start_td({align=>'center'}),
					checkbox({override=>1,checked=>$c1,name=>'dd',value=>"$_ 1 " . (defined($old_dd{$_}{'status'}) ? $old_dd{$_}{'status'} :$DAY_PENDING),label=>"<label for=\"cbox$cell\">1st</label>",id=>"cbox$cell",onClick=>'uncheck(\'cbox' . ($cell + 1) . '\')'}),
					checkbox({override=>1,checked=>$c2,name=>'dd',value=>"$_ 2 " . (defined(
					$old_dd{$_}{'status'}) ? $old_dd{$_}{'status'} :$DAY_PENDING),label=>'<label for="' . 'cbox' . ($cell+1) . '">2nd</label>',id=>'cbox' . ($cell + 1),onClick=>'uncheck(\'cbox' . $cell . '\')'});
				autoEscape(1);
				if(defined($old_dd{$_}))
				{
					if(defined($old_dd{$_}{'status'}))
					{
						if($old_dd{$_}{'status'} == $DAY_PENDING) { print ' Pending' }
						elsif($old_dd{$_}{'status'} == $DAY_APPROVED) { print ' Approved'}
						elsif($old_dd{$_}{'status'} == $DAY_NOT_APPROVED) { print ' Not Approved'}
					}
				}
				print end_td;
			}
			else
			{
				if($dates{$_}{'status'} == 0 || $dates{$_}{'sec'} < $today)
				{ print td({style=>'text-align: center'},'Filled'); }
				else
				{
					print start_td({align=>'center'}),
							checkbox({name=>'dd',value=>"$_ 1 $DAY_PENDING",label=>'1st',id=>"cbox$cell",onClick=>'uncheck(\'cbox' . ($cell + 1) . '\')'}),
							checkbox({name=>'dd',value=>"$_ 2 $DAY_PENDING",label=>'2nd',id=>'cbox' . ($cell + 1),onClick=>'uncheck(\'cbox' . $cell . '\')'});
					print end_td;

				}
			}

			print end_Tr;
			$cell += 2;
		}
		print end_table,end_div;

		print end_div;

		if($adm)
		{
			if($Q::load)
			{
				print hidden({name=>'confirmation_sent',value=>param('confirmation_sent')});
				print hidden({name=>'load',value=>$Q::load});
				print hidden({name=>'submit_date',value=>$Q::submit_date});
			}
			print hidden({name=>'adm',value=>1}),hidden({override=>1,name=>$auth->sfparam_name,value=>$auth->sfparam_value});
		}
		print hidden({override=>1,name=>'nextpage',value=>'review'}); 
		print div({align=>'center'},script({type=>'text/javascript'},'makesubmit(\'\',\'Review\',\'\')'));

		print end_form;
		print end_div,end_center;
}

sub varname 
{
	# $0= Date::Manip $date $1=prefix 
		$_=$_[0];
		s/\:/_/g;	
		return "$_[1]$_";
}

sub send_approve_page
{
		# $_[0] is 1 (Print html header) or 0 don't
		autoEscape(0);
		if(defined($_[0]) && $_[0] == 1) { print header; }

		my($title)=($adm ? 'Petal Pushers&reg; Scheduling System' : 'Petal Pushers&reg; Online Work Request');
		print start_html({-base=>1,title=>$title,
			-script=>[{-src=>'/res/res.js',-type=>'text/javascript'}
			],
			head=>[
				Link({rel=>'SHORTCUT ICON',href=>'/favicon.ico'}),
				Link({rel=>'StyleSheet',href=>'/res/res.css',type=>'text/css'}),
				Link({rel=>'StyleSheet',href=>'/res/menu.css',type=>'text/css'}),
				Link({rel=>'StyleSheet',href=>'/inc/style.css',type=>'text/css'})
			]});
		autoEscape(1);
		my $s = Net::HTTP->new(Host => 'petalpushers.org') || die $@;
		$s->write_request(GET => '/inc/top.php', 'User-Agent' => "Mozilla/5.0");
		my($code, $mess, %h) = $s->read_response_headers;

		while (1) {

			my $buf;
			my $n = $s->read_entity_body($buf, 1024);
			die "read failed: $!" unless defined $n;
			last unless $n;
			print $buf;
		}

		print start_center,start_div({style=>'width: 765px;  margin: 5px'});

		if(defined($_[0]) && $_[0] == 1) { showmenu(2) }
		print h3({align=>'center'},'Work Request Review'),
		h4('Volunteer Days');

		my(@pa); 
		my($cell)=0;
		print start_div({align=>'center'}),start_table({class=>'shifttbl'});
		print Tr(th('Event'),th('Day'),th({colspan=>3},'Shift'),th('Choice'));

		my(@ddline);
		foreach (sort by_dd (@Q::dd))
		{
			@ddline=split / /;
			@pa=split(/ /,$dates{$ddline[0]}{'display'});
			print start_Tr({style=>((($cell / 2) % 2) == 1 ? 'background-color: #f0f0f0': '')}),
				td({style=>'text-align: center'},($dates{$ddline[0]}{'daytype'} == 0 ? 'Detail Day' : 'Decorating Day')),
				td("$pa[0] $pa[1]"),
				td({style=>'text-align: right; padding-right: 0'},$pa[2]),
				td({style=>'padding-left: 2px; padding-right: 2px; margin: 0'},$pa[3]),
				td({style=>'text-align: left; padding-left: 0'},$pa[4])
			;

			if($ddline[1] == 1)
			{
				print td({align=>'center'},'1st');
			}
			else
			{
				print td({align=>'center'},'2nd');
			}

			print end_Tr;
			$cell += 2;
		}
		print end_table,end_div;

		print h4('Contact Information');
		print start_div({class=>'ind'});
		my($ci)=$Q::name1;
		if($Q::name2 ne '') { $ci .= "<br />$Q::name2" }
		if($Q::orgname ne '') { $ci .= '<br />' . escapeHTML($Q::orgname) }

		if($Q::addr1 ne '' ||
			$Q::addr2 ne '' ||
			$Q::city ne '' ||
			$Q::st ne '' ||
			$Q::zip ne ''
			)
		{
			$ci .= "<br />$Q::addr1";
			if($Q::addr2 ne '') { $ci .= "<br />$Q::addr2" }
			$ci .= "<br />$Q::city, $Q::st $Q::zip";
		}
		$ci .= "<br />Adults: $Q::num_of_adults";
		if($Q::num_of_youths ne '') { $ci .= "<br />Youths: $Q::num_of_youths" }

		$ci .= '<br />';
		if($Q::day_ph ne '') { $ci .= "<br />Day Phone: $Q::day_ph" }
		if($Q::evening_ph ne '') { $ci .= "<br />Evening Phone: $Q::evening_ph" }
		if($Q::mobile_ph ne '') { $ci .= "<br />Mobile Phone: $Q::mobile_ph" }


		print $ci;
		print end_div;

		print h4('Confirmation Email(s)');
		print start_div({class=>'ind'});
		print escapeHTML("\"$Q::name1\" <$Q::email1>");
		if($Q::email2 ne '') { print br,escapeHTML("\"$Q::name2\" <$Q::email2>") }
		print end_div;

		if($Q::comments ne '')
		{
			print h4('Comments');
			print start_div({class=>'ind'});
			print p($Q::comments);
			print end_div;
		}

		if(defined($_[0]) && $_[0] == 1)
		{
			my(%v);

			Delete('nextpage');
			%v=Vars();


			print start_div({align=>'center'}),start_table({cellpadding=>5}),start_Tr,start_td;
				print start_form({action=>$location});
				foreach (keys(%v)) { print hidden({name=>$_,value=>$v{$_}}) }
				if($adm)
				{
					print hidden({override=>1,name=>'nextpage',value=>'startpage'}),
						hidden({name=>'adm',value=>1}),
						hidden({name=>$auth->sfparam_name,value=>$auth->sfparam_value});
				}	
				print script({type=>'text/javascript'},'makesubmit(\'\',\'Edit\',\'width: 5em\')');
				print '</form>'; 
			print end_td;

			param(-name=>'nextpage',-value=>'send');
			%v=Vars();
			print start_td;
				print start_form({action=>$location});
				foreach (keys(%v)) { print hidden({name=>$_,value=>$v{$_}}); }

				print script({type=>'text/javascript'},'makesubmit(\'\',\'Send\',\'width: 5em\')');
				if($adm)
				{
					print hidden({name=>'adm',value=>1}),
					hidden({name=>$auth->sfparam_name,value=>$auth->sfparam_value});
				}
				print '</form>'; 
			print end_td,end_Tr,end_table,end_div;
		}

		print end_div,end_center;
		print end_html; 
}

sub send_email
{
		my($to)='';

		if($Q::email1 =~ /[@]/) { $to="\"$Q::name1\" <$Q::email1>"; }
		if($Q::email2 =~ /[@]/) { $to .=",\"$Q::name2\" <$Q::email2>"; }

		if($to eq '') { return ;}

		my($sendmail_from)='"Petal Pushers" <Reservations@petalpushers.org>';

		my($cdate)=UnixDate(DateCalc('today','+ 3 weeks'),"\045f.\045e.\045Y");
		$cdate =~ s/ //; 
		my($rdate)=UnixDate(param('submit_date'),"\045A, \045f.\045e.\045Y @ \045i:\045M\045:\045S\045p");
		$rdate =~ s/\s(\s)/$1/g;
		$rdate =~ s/(\.)\s(\d)/$1$2/g;
		$rdate =~ s/(AM|PM)/\L$1/g;

		my($from)=$sendmail_from;
		my($fh,$fname)=tempfile();
		select($fh);
		send_approve_page(0);
		select(STDOUT);
		seek($fh,0,0);

		my($names)="$Q::name1,";
		if($Q::name2 ne '') { $names .=" $Q::name2,";}


	my($data)=<<EOF;
Submit Date:  $rdate

$names

Attached to this email is a copy of the Petal Pushers Volunteer Work Request.

We have received your request.  We will send you a confirmation email after we have scheduled the dates into our system.

Please wait until $cdate before contacting us with your status questions.

Thank you for volunteering with Petal Pushers,

Reservations\@petalpushers.org
EOF

		my($msg) = MIME::Lite->new(
			From    =>$from,
			To 		=>$to,
			Subject =>(($adm && defined($Q::load)) ? 'Updated: Volunteer Work Request' : 'Volunteer Work Request'),
			Type    =>'multipart/mixed'
		);

		$msg->attach(
			Type=>'text/plain',
			Data=>$data
		);

		$msg->attach(
			Type=>'text/html',
			Path=>$fname,
			Disposition =>'attachment',
			Encoding =>'base64',
			Filename=>'WorkRequest.html'
		);

		$msg->send_by_sendmail( BaseArgs=>['-t', '-i'], SetSender=>0);
		unlink($fname);
}

sub send_thankyou_page
{
		autoEscape(0);
		print header,start_html({-base=>1,title=>'Petal Pushers&reg; Online Work Reqest',
			head=>[
				Link({rel=>'SHORTCUT ICON',href=>'/favicon.ico'}),
				Link({rel=>'StyleSheet',href=>'/res/res.css',type=>'text/css'}),
				Link({rel=>'StyleSheet',href=>'/inc/style.css',type=>'text/css'})
			]});
		autoEscape(1);

		print start_div({id=>'container'});

		my $s = Net::HTTP->new(Host => 'petalpushers.org') || die $@;
		$s->write_request(GET => '/inc/top.php', 'User-Agent' => "Mozilla/5.0");
		my($code, $mess, %h) = $s->read_response_headers;

		while (1) {

			my $buf;
			my $n = $s->read_entity_body($buf, 1024);
			die "read failed: $!" unless defined $n;
			last unless $n;
			print $buf;
		}

		$s = Net::HTTP->new(Host => 'petalpushers.org') || die $@;
		$s->write_request(GET => '/inc/sidemenu.php?smcurrent=Volunteer%20Sign%2Dup', 'User-Agent' => "Mozilla/5.0");
		($code, $mess, %h) = $s->read_response_headers;

		while (1) {

			my $buf;
			my $n = $s->read_entity_body($buf, 1024);
			die "read failed: $!" unless defined $n;
			last unless $n;
			print $buf;
		}

		print start_div({id=>'content'});
		print start_div({style=>'margin: 0 2em'}),
			#print start_div({id=>'content',style=>'width: 765px;  margin: 5px'}),
		h3({align=>'center'},'Work Request Completed');
		print start_div({class=>'ind'});
		print p('You Volunteer Work Request has been submitted.  A copy of the request 
		has been sent to the email address(s).  
		Although it generally arrives within a few minutes, please allow a few hours for the email to arrive in your Inbox.'),
		p('Thank you for volunteering with Petal Pushers&reg;.');
		print end_div;
		print end_div;

		print end_div;
		print end_div; # id=container
}
sub save_boulder_file
{
	# Save Boulder (man CGI.pm) data file.

	mkdir("$resdataprefix/data");
	my($resfile);

	if(defined($_[0]))
	{
		$resfile="$resdataprefix/data/$_[0]";
	}
	else
	{
		my($ctx) = Digest::MD5->new;
		$ctx->add(param('submit_date') . $Q::name1);
		$resfile.= "$resdataprefix/data/" . $ctx->hexdigest . '.txt';
	}
	Delete('auth_sessfile');
	Delete('adm');
	Delete('load');

	open(OUT,">$resfile") || die("Can't open $resfile");
	save_parameters(*OUT);
	close OUT;
}

sub getLogin 
{
		my $template = HTML::Template->new(filename=>'login.html',path=>[$authdir],loop_context_vars=>1);
		$template->param(version=>'1.53.1.6');

		$auth = new CGI::Auth({
			-timeout=>28800,
			-authdir=>$authdir,
			-cgiprune,=>1,
			-logintmpl=>$template,
			-formaction=>$location,
			-md5pwd=>1,
			-authfields=> [
				{id => 'user', display => 'User Name:', hidden => 0, required => 1},
				{id => 'pw', display => 'Password:', hidden => 1, required => 1},
			],
		});
		$auth->check;
		$auth->prune;
}

sub start_page_adm
{
		$show_date=($show_date ? $show_date : cookie(-name=>'show_dates')); 
		if(! defined($show_date))
		{
			foreach (sort keys %dates)
			{
				if($today < $dates{$_}{'sec'})
				{
					$show_date=$_;
					last;
				}
			}
		}
		my(%pending);	
		my %names;
		my(%approved);
		my(%shiftsum);
		my(%totals);
		my($pending_people)=0;
		my($orgname,$name1,$who);
		my(@pdd);
		my(@ddline);
		my($found_pending)=0;
		my($q);
		foreach my $file (<$resdataprefix/data/*.txt>)
		{
			open(IN,$file) || die "Cannot open $_";
			$q=new CGI(\*IN);

			$file =~ s#.*/##; 
			# Cycle through dd's and find status.
			# Look through all shift dates for a request.  If at least one
			# pending, we print all requested shifts. 
			@pdd=();
			$found_pending=0;
			foreach ($q->param('dd'))
			{
				@ddline=split / /;
				if($ddline[2] == $DAY_PENDING) { $found_pending=1 }
				if($ddline[2] == $DAY_APPROVED)
				{
					$orgname=$q->param('orgname');
					$name1=$q->param('name1');
					$approved{$ddline[0]}{$orgname}{$name1}{'orgname'}=$orgname;
					$approved{$ddline[0]}{$orgname}{$name1}{'name1'}=$name1;
					$approved{$ddline[0]}{$orgname}{$name1}{'name2'}=$q->param('name2');
					$who=($orgname ne '' ? escapeHTML($orgname) . ', ' : '') .
					escapeHTML($name1) .
					($q->param('name2') ne '' ? ', ' . escapeHTML($q->param('name2')) : '');
					$approved{$ddline[0]}{$orgname}{$name1}{'email1'}=$q->param('email1');
					$approved{$ddline[0]}{$orgname}{$name1}{'email2'}=$q->param('email2');
					@{$approved{$ddline[0]}{$orgname}{$name1}{'floats'}}=$q->param('floats');
					my(@ay);
					foreach ($q->param('floats'))
					{
						@ay=split;
						if($ddline[0] ne $ay[0]) {next}
						$shiftsum{$ddline[0]}{$ay[1]}{$who}{'a'}=$ay[2];
						$shiftsum{$ddline[0]}{$ay[1]}{$who}{'y'}=$ay[3];
					}
					$approved{$ddline[0]}{$orgname}{$name1}{'file'}=$file;
					$approved{$ddline[0]}{$orgname}{$name1}{'num_of_adults'}=($q->param('num_of_adults') eq '' ?0:$q->param('num_of_adults'));
					$approved{$ddline[0]}{$orgname}{$name1}{'num_of_youths'}=($q->param('num_of_youths') eq '' ?0:$q->param('num_of_youths'));
					$approved{$ddline[0]}{$orgname}{$name1}{'num_of_adults_arrived'}=0;
					$approved{$ddline[0]}{$orgname}{$name1}{'num_of_youths_arrived'}=0;
					foreach ($q->param('arrived'))
					{
						my @arrived=split;
						if($ddline[0] ne $arrived[0]) {next}
						$approved{$ddline[0]}{$orgname}{$name1}{'num_of_adults_arrived'}=$arrived[1];
						$approved{$ddline[0]}{$orgname}{$name1}{'num_of_youths_arrived'}=$arrived[2];
					}
					$approved{$ddline[0]}{$orgname}{$name1}{'submit_date'}=$q->param('submit_date');
					$approved{$ddline[0]}{$orgname}{$name1}{'city'}=$q->param('city');
					$approved{$ddline[0]}{$orgname}{$name1}{'st'}=$q->param('st');
					$approved{$ddline[0]}{$orgname}{$name1}{'comments'}=escapeHTML($q->param('comments'));
					$approved{$ddline[0]}{$orgname}{$name1}{'comments'}=~ s#\r\n#<br />#g;
					$approved{$ddline[0]}{$orgname}{$name1}{'confirmation_sent'}=[$q->param('confirmation_sent')];
						{ no warnings;
					$totals{$ddline[0]}+= $q->param('num_of_adults') + $q->param('num_of_youths');
						}
				}
				push(@pdd,$_);
			}
			if($found_pending)
			{
				my($sd)=$q->param('submit_date');
				$pending{$sd}{'dd'}= [ sort(@pdd) ];
				$pending{$sd}{'file'}=$file;
				$pending{$sd}{'choice'}=$ddline[1];
				$pending{$sd}{'orgname'}=$q->param('orgname');
				$pending{$sd}{'name1'}=$q->param('name1');
				$pending{$sd}{'email1'}=$q->param('email1');
				$pending{$sd}{'name2'}=$q->param('name2');
				$pending{$sd}{'email2'}=$q->param('email2');
				$pending{$sd}{'comments'}=escapeHTML($q->param('comments'));
				$pending{$sd}{'comments'}=~ s#\r\n#<br />#g;
				$pending{$sd}{'num_of_adults'}=$q->param('num_of_adults');
				$pending{$sd}{'num_of_youths'}=$q->param('num_of_youths');
					{ no warnings;
				$pending_people+=$pending{$sd}{'num_of_adults'};
				$pending_people+=$pending{$sd}{'num_of_youths'};
					}
			}
			close IN;
		}

		autoEscape(0);
		print header(-cookie=>$cookie),start_html({title=>'Petal Pushers&reg; Scheduling System',
			script=>[
					{-src=>'/res/res.js',-type=>'text/javascript'},
					{-src=>'/res/dock.js',-type=>'text/javascript'},
					{-src=>'/res/overlib.js',-type=>'text/javascript'},
					{-src=>'/res/expandtext.js',-type=>'text/javascript'},
					],
			head=>[
				Link({rel=>'SHORTCUT ICON',href=>'/favicon.ico'}),
				Link({rel=>'StyleSheet',href=>'/res/res.css',type=>'text/css'}),
				Link({rel=>'StyleSheet',href=>'/res/menu.css',type=>'text/css'}),
				meta({-http_equiv =>'PRAGMA',-content=>'NO-CACHE'})
			]});
		autoEscape(1);

		my($d);
		my($c);
		my(%pa);
		my($nd);
		my($tsi)=0;
		my($total)=0;
		my($mailto);
		foreach (keys %totals)
		{
			$total+=$totals{$_}
		}
		foreach (sort keys %dates)
		{
			$nd=ParseDate(UnixDate($_,"\045m/\045d/\045Y"));
			$d=UnixDate($nd,"\045f.\045e");
			$d =~ s/\s(\s)/$1/g;
			$d =~ s/(\.)\s(\d)/$1$2/g;
			$pa{$nd}{'display'}=$d;
			if(! defined($pa{$nd}{'shift'})) {$pa{$nd}{'shift'}=$_}
			if(defined($totals{$_}))
			{
				if(defined($pa{$nd}{'count'}))
				{
					$pa{$nd}{'count'}.="|<a id=\"id$_\">$totals{$_}</a>";
				}
				else
				{
					$pa{$nd}{'count'}="<a id=\"id$_\">$totals{$_}</a>";
				}
			}
			else
			{
				if(defined($pa{$nd}{'count'}))
				{
					$pa{$nd}{'count'}.="|<a id=\"id$_\">0</a>";
				}
				else
				{
					$pa{$nd}{'count'}="<a id=\"id$_\">0</a>";
				}
			}
		}
		my($i)=1;
		print start_div({id=>'topbar'}),start_table({style=>'border-collapse: collapse'});
		print start_Tr;
		print td({class=>'even'},b('Totals: '));
		foreach (sort keys %pa)
		{
			$c=($i++ % 2 == 0 ? 'even' : 'odd');
			print td({class=>$c},a({href=>"#a$pa{$_}{'shift'}"},$pa{$_}{'display'}));
		}
		print end_Tr,start_Tr,td({class=>'even'},a({class=>'nolink',id=>'total'},'&nbsp;&nbsp;&nbsp;'));
		$i=1;
		foreach (sort keys %pa)
		{
			$c=($i++ % 2 == 0 ? 'even' : 'odd');
			print td({class=>$c},$pa{$_}{'count'});
		}
		print end_Tr;
		print end_table,end_div;
		print script({type=>'text/javascript'},"document.getElementById('total').innerHTML=$total+' =';");

		print start_div({style=>'width: 765px;  padding: 5px 5px 24px 5px'});
		showmenu(0,\%approved);

		if(scalar keys %pending)
		{
		print h4({style=>'color: #3366cc'},"Pending Requests ($pending_people)");
		print start_form({name=>'f1',action=>$location});
		my(@changefields);
		my(%labels)=($DAY_PENDING=>'Pending',$DAY_APPROVED=>'Approved',$DAY_NOT_APPROVED=>'Not Approved');
		my($tsindex);
		my(%total_state);
		my($ay_count);
		foreach my $sd (sort keys %pending)
		{
			# Make mailto 
			$mailto  = ($pending{$sd}{'email1'} =~ /[@]/ ? "mailto:\%20$pending{$sd}{'email1'}" : '');
			$mailto .= ($pending{$sd}{'email2'} =~ /[@]/ ? ",$pending{$sd}{'email2'}" : '');
			print start_div,start_table({class=>'pendingtbl'});
			print Tr(
				td({style=>'width: 5%'},'Submit Date: '),
				td({style=>'width: 45%'},a({href=>"$location?adm=1;nextpage=startpageload;load=$pending{$sd}{'file'};" . $auth->sfparam_name . '=' . $auth->sfparam_value},pdate($sd)),
				(length($pending{$sd}{'comments'}) ? 
				a({href=>'javascript:void(0);',onmouseover=>'return overlib(\'' . $pending{$sd}{'comments'} . "',HAUTO,VAUTO,CAPTION,'Comments',FGCOLOR,'#fff8dc',BGCOLOR,'#7f7f7f');",onmouseout=>'return nd();'},
				img({border=>0,alt=>'',align=>'top',src=>'/res/emotionicon-praying-63.gif'})) 
				: '')
				),
				td({style=>'width: 5%'},'Name: '),
				td(($mailto ne '' ? a({href=>$mailto},$pending{$sd}{'name1'}) : $pending{$sd}{'name1'}),
				#td(($pending{$sd}{'email1'} =~ /[@]/ ? a({href=>"mailto:\%20$pending{$sd}{'email1'}"},$pending{$sd}{'name1'}) : $pending{$sd}{'name1'})
				),
				td({style=>'width: 2%'},'Adults: '),
				td({style=>'width: 2%;text-align: left'},$pending{$sd}{'num_of_adults'}),
			);
			print Tr(
				td('Organization: '),
				td(($pending{$sd}{'orgname'} ne '' ? escapeHTML($pending{$sd}{'orgname'}) : '&nbsp;')),
				td('Name: '),
				td(($mailto ne '' ? a({href=>$mailto},$pending{$sd}{'name2'}) : $pending{$sd}{'name2'})),
				#td(($pending{$sd}{'email2'} =~ /[@]/ ? a({href=>"mailto:\%20$pending{$sd}{'email2'}"},$pending{$sd}{'name2'}) : $pending{$sd}{'name2'})),
				td({style=>'width: 2%'},'Youths: '),
				td({style=>'width: 2%;text-align: left'},$pending{$sd}{'num_of_youths'})
			);
			print end_table,end_div;
			print start_div,start_table({class=>'penddatatbl'});
			print Tr(
				th({colspan=>4},'Date'),
				th('Choice'),
				th('Status'),
			);
			%total_state=();
			foreach my $shift (sort by_dd @{$pending{$sd}{'dd'}})
			{
				my(@dd)=split(/ /,$shift);
				my(@pa)=split(/ /,$dates{$dd[0]}{'display'});
				my($date)=$dd[0];
				# {file}{shift date} 
				my($status_radio_name)="$pending{$sd}{'file'} $dd[0]";
				$tsindex=$status_radio_name;
				$tsindex =~ s/ /-/;
				push(@changefields,$status_radio_name);
				$total_state{$tsindex}=($dd[2]==$DAY_APPROVED ? 1 : 0);
					{ no warnings;
				$ay_count=$pending{$sd}{'num_of_adults'} + $pending{$sd}{'num_of_youths'};
					}
				print Tr(
					td(
					"$pa[0] $pa[1]"),
					td({style=>'text-align: right; padding-right: 0'},$pa[2]),
					td({style=>'padding-left: 2px; padding-right: 2px; margin: 0'},$pa[3]),
					td({style=>'text-align: left; padding-left: 0'},$pa[4]),
					td({style=>'text-align: center'},($dd[1] == 1 ? '1st' : '2nd')),
					td({style=>'width: 55%;text-align: center'},
					'<input ' . ($dd[2]== 0 ? 'checked="checked"' : '') . ' id="li' . $pending{$sd}{'file'} . $dd[0] . '0' . "\" type=\"radio\" name=\"$status_radio_name\" value=\"0\" onclick=\"adjTotal('$pending{$sd}{'file'}-$dd[0]',this,'$dd[0]',$ay_count)\" />",label({for=>'li' . $pending{$sd}{'file'} . $dd[0] . '0'},'Pending'),
					'<input ' . ($dd[2]== 1 ? 'checked="checked"' : '') . ' id="li' . $pending{$sd}{'file'} . $dd[0] . '1' . "\" type=\"radio\" name=\"$status_radio_name\" value=\"1\" onclick=\"adjTotal('$pending{$sd}{'file'}-$dd[0]',this,'$dd[0]',$ay_count)\" />",label({for=>'li' . $pending{$sd}{'file'} . $dd[0] . '1'},'Approved'),
					'<input '. ($dd[2]== 2 ? 'checked="checked"' : '') . ' id="li' . $pending{$sd}{'file'} . $dd[0] . '2' . "\" type=\"radio\" name=\"$status_radio_name\" value=\"2\" onclick=\"adjTotal('$pending{$sd}{'file'}-$dd[0]',this,'$dd[0]',$ay_count)\" />",label({for=>'li' . $pending{$sd}{'file'} . $dd[0] . '2'},'Not Approved')
					)
				); 
			}
			print end_table,end_div;
			print start_script({type=>'text/javascript'});
			foreach (keys %total_state)
			{
				print "total_state['$_']='$total_state{$_}';\n";
			}
			print end_script;
		}
		print hidden({name=>'adm',value=>1}),
			hidden({override=>1,name=>$auth->sfparam_name,value=>$auth->sfparam_value}),
			hidden({name=>'changefields',value=>"@changefields"}),
			hidden({override=>1,name=>'nextpage',value=>'changestatus'});

		print div({align=>'center'},script({type=>'text/javascript'},'makesubmit(\'\',\'Send Confirmations\',\'\')'));

		print end_form;
		}

	open(FF,$ppfloats) || die "Cannot open $ppfloats";
	my(%floats,@float,@f,%flabels);
	# Load floats 
	while (<FF>)
	{
		chomp;
		if(/[#]/) { next }
		@float=split(/\|/);
		$floats{$float[1]}{'org'}=$float[2];
		$floats{$float[1]}{'theme'}=$float[3];
		$flabels{$float[1]}="$float[2] - $float[3]";
	}
	@f= sort keys %floats;
	close FF;
	# Print Approved by Date
	my(@csline,$history);
	my($idshift,$son,$oname,$citystate);
	my($floatid)=0;
	my($sfw);

	foreach my $shift (sort keys %approved)
	{
		if($show_date ne '' && $show_date ne 'All' && $shift ne $show_date) { next }

		print h4({class=>'apprlink'},a({id=>"a$shift"},$dates{$shift}{'display'}),
		a({id=>"tid$shift"},"($totals{$shift})"));

		if(defined($shiftsum{$shift}))
		{
			my($id);
			print start_div({align=>'center',style=>'margin-bottom: 2em'}),start_table({class=>'shiftsumtbl'});
			print Tr(
				td(' '),
				th('Adults'),
				th('Youths'),
				th('Totals')
			);
			foreach my $fid (sort keys %{$shiftsum{$shift}})
			{
				print Tr(td({style=>'text-align: left',colspan=>4},b("$floats{$fid}{'org'} - $floats{$fid}{'theme'}")));
				foreach my $who (sort keys %{$shiftsum{$shift}{$fid}}) 
				{
					$sfw=$shiftsum{$shift}{$fid}{$who};
					print Tr(
						td({style=>'text-align: left;padding-left: 2em'},$who),
						td($$sfw{'a'}),
						td($$sfw{'y'}),
						td($$sfw{'a'} + $$sfw{'y'}),
					);
				}
				$id="fl$shift$fid"; 
				$id =~ s/[:]|\.//g;
				print start_Tr;
				print td(' ');
				print td({id=>"$id-a",class=>'last'},' ',
					script({type=>'text/javascript'},'
						floatTotal[\'' . "$id-a" . '\']= new Array();
					')
				);
				print td({id=>"$id-y",class=>'last'},' ',
					script({type=>'text/javascript'},'
						floatTotal[\'' . "$id-y" . '\']= new Array();
					')
				);
				print td({id=>"$id-t",class=>'last'},' ',
					script({type=>'text/javascript'},'
						floatTotal[\'' . "$id-t" . '\']= new Array();
					')
				);
				print end_Tr;
			}
			$id="fl$shift-g"; 
			$id =~ s/[:]|\.//g;
			print Tr(td({colspan=>4},'&nbsp;')),start_Tr();
			print td({style=>'text-align: left'},b('Totals:'));
			print td({id=>"$id-a",class=>'last'},' ',
				script({type=>'text/javascript'},'
					floatTotal[\'' . "$id-a" . '\']= new Array();
				')
			);
			print td({id=>"$id-y",class=>'last'},' ',
				script({type=>'text/javascript'},'
					floatTotal[\'' . "$id-y" . '\']= new Array();
				')
			);
			print td({id=>"$id-t",class=>'last'},' ',
				script({type=>'text/javascript'},'
					floatTotal[\'' . "$id-t" . '\']= new Array();
				')
			);
			print end_Tr;
			print end_table,end_div;
		}

		my(%shiftid);
		print start_div,start_table({class=>'approvedtbl'});
		foreach my $orgname (sort noundef keys %{$approved{$shift}})
		{
			foreach my $name1 (sort keys % {$approved{$shift}{$orgname}})
			{
				# son=$shift$orgname$name
				$son=$approved{$shift}{$orgname}{$name1};
				# Load Email History
				if(scalar $$son{'confirmation_sent'} )
				{
					$history=undef;
					foreach (@{$$son{'confirmation_sent'}})
					{
						@csline=split /\|/;
						$history.=escapeHTML(pdate($csline[0])) . ' ' .escapeHTML($csline[1]) . '<br />';
					}
				}
				# Make mailto 
				$mailto  = ($$son{'email1'} =~ /[@]/ ? "mailto:\%20$$son{'email1'}" : '');
				$mailto .= ($$son{'email2'} =~ /[@]/ ? ",$$son{'email2'}" : '');

				$idshift="form$$son{'file'}$shift"; 
				$idshift =~ s/[:]|\.//g;
				if($orgname eq '')
				{
					$oname=($$son{'city'} ne ''? "$$son{'city'}, $$son{'st'}" : ' ')
				}
				else
				{
					$oname=($$son{'city'} ne ''? escapeHTML($orgname) . "<br />$$son{'city'}, $$son{'st'}" : escapeHTML($orgname))
				}
				
				$citystate=($$son{'city'} ne '' ? escapeHTML("$$son{'city'}, $$son{'st'}") : '');
				print start_Tr;
				print start_td({class=>'approvedtbltd'});
					print start_table;
					print Tr(
						td({style=>'width: 5%'},'Submit Date: '),
						td({style=>'width: 45%'},a({href=>"$location?adm=1;nextpage=startpageload;load=$approved{$shift}{$orgname}{$name1}{'file'};" . $auth->sfparam_name . '=' . $auth->sfparam_value},pdate($approved{$shift}{$orgname}{$name1}{submit_date}))
						,
						a({href=>"$location?adm=1;nextpage=resend;load=$$son{'file'};" . $auth->sfparam_name . '=' . $auth->sfparam_value,onmouseover=>"return overlib('Resend Email Confirmation',WRAP,HAUTO,VAUTO,FGCOLOR,'#fff8dc',BGCOLOR,'#7f7f7f');",onmouseout=>'return nd();'}, img({alt=>'',align=>'middle',src=>'/res/envelope.gif'})) 
						,(defined($history) ? 
						a({href=>'javascript:void(0);',onmouseover=>"return overlib('$history',WRAP,HAUTO,VAUTO,CAPTION,'Confirmation Sent Date &amp; Email Address',FGCOLOR,'#fff8dc',BGCOLOR,'#7f7f7f');",onmouseout=>'return nd();'}, img({border=>0,alt=>'',align=>'top',src=>'/res/nailbiting-42.gif'})) 
						: '')
						,(length($$son{'comments'}) ? 
						a({href=>'javascript:void(0);',onmouseover=>"return overlib('$$son{'comments'}',WRAP,CAPTION,'Comments',HAUTO,VAUTO,FGCOLOR,'#fff8dc',BGCOLOR,'#7f7f7f');",onmouseout=>'return nd();'},
						img({border=>0,alt=>'',align=>'top',src=>'/res/emotionicon-praying-63.gif'})) 
						: '')
						),
						td({style=>'width: 5%'},'Name: '),
						td(($mailto ne '' ? a({href=>$mailto},$$son{'name1'}) : $$son{'name1'}))
					);
					print Tr(
						td({style=>'vertical-align: top'},'Organization: '),
						td($oname),
						td('Name: '),
						td(($mailto ne '' && $$son{'name2'} ne '' ? a({href=>$mailto},$$son{'name2'}) : $$son{'name2'} . '&nbsp;'))
					);
					print end_table;
				print end_td;
				print start_td({class=>'approvedtbltd',style=>'width: 5%'});
					print table({class=>'approvedtl',onclick=>"expandcontent('$idshift')"},
						Tr(
							td(' '),
							th('Exp'),
							th('Arv'),
							th('Asn')
						),
						Tr(
							td('Adults:'),
							td(($$son{'num_of_adults'} eq ''? ' ':$$son{'num_of_adults'})),
							td({id=>"flarv-a-$idshift"},' ',
								script({type=>'text/javascript'},'
									floatTotal[\'' . "flarv-a-$idshift" . '\']= new Array();
								')
							),
							td({id=>"flasn-a-$idshift"},' ',
								script({type=>'text/javascript'},'
									floatTotal[\'' . "flasn-a-$idshift" . '\']= new Array();
								')
							)
						),
						Tr(
							td('Youths:'),
							td(($$son{'num_of_youths'} eq ''? ' ':$$son{'num_of_youths'})),
							td({id=>"flarv-y-$idshift"},' ',
								script({type=>'text/javascript'},'
									floatTotal[\'' . "flarv-y-$idshift" . '\']= new Array();
								')
							),
							td({id=>"flasn-y-$idshift"},' ',
								script({type=>'text/javascript'},'
									floatTotal[\'' . "flasn-y-$idshift" . '\']= new Array();
								')
							)
						),
						Tr(
							td('Totals:'),
							td($$son{'num_of_adults'}+$$son{'num_of_youths'}+0),
							td({id=>"flarv-t-$idshift"},' ',
								script({type=>'text/javascript'},'
									floatTotal[\'' . "flarv-t-$idshift" . '\']= new Array();
								')
							),
							td({id=>"flasn-t-$idshift"},' ',
								script({type=>'text/javascript'},'
									floatTotal[\'' . "flasn-t-$idshift" . '\']= new Array();
								')
							)
						)
					);
				print end_td;
				print end_Tr;
				print start_Tr;
				print start_td({style=>'padding-top: 0;margin-top: 0;border-bottom: 1px solid #346436',colspan=>2});
					print start_div({align=>'center',id=>$idshift,class=>'switchcontent'});
						print start_form({style=>'display: inline',name=>"form$idshift",onsubmit=>"return ffloatValidate('$idshift')",action=>$location}),
							script({type=>'text/javascript'},"floatValidate['$idshift']= new Array()");
						print start_table({class=>'apprformtbl'});
							print Tr(td({colspan=>4,align=>'center'},'Assign 0 to Adult &amp; Youth counts to delete the float assignment.<br />Change &amp; Save one work request at a time.'));
							print Tr(
								td(' '),
								th('Adults'),
								th('Youths'),
								th('Totals')
							);
							print start_Tr,
								td({style=>'text-align: right'},'Arrived:');
								print td(
								textfield({id=>"fl$floatid",
									onblur=>'updateFloatTotal(\'fl' . ($floatid + 2) . " flarv-a-$idshift flarv-t-$idshift')",
									override=>1,name=>'num_of_adults_arrived',value=>($$son{'num_of_adults_arrived'}==0?'': "$$son{'num_of_adults_arrived'}"),size=>2,maxlength=>3}),
								script({type=>'text/javascript'},"floatValidate['$idshift'].push('fl".$floatid++.'\')')
								);
								print td(textfield({id=>"fl$floatid",
									onblur=>'updateFloatTotal(\'fl' . ($floatid + 1) . " flarv-y-$idshift flarv-t-$idshift')",
									override=>1,name=>'num_of_youths_arrived',value=>($$son{'num_of_youths_arrived'}==0?'' : "$$son{'num_of_youths_arrived'}"),size=>2,maxlength=>3}),
								script({type=>'text/javascript'},"floatValidate['$idshift'].push('fl".$floatid++.'\')'));
								print start_td({align=>'center',id=>'fl'.$floatid++}),' ';
								print script({type=>'text/javascript'},'
									floatTotal[\'fl' . ($floatid - 1) . '\']= new Array();
									floatTotal[\'fl' . ($floatid - 1) . '\'].push(\'fl' . ($floatid - 3) . '\');
									floatTotal[\'' . "flarv-a-$idshift" . '\'].push(\'fl' . ($floatid - 3) . '\');
									floatTotal[\'' . "flarv-t-$idshift" . '\'].push(\'fl' . ($floatid - 3) . '\');
									floatTotal[\'fl' . ($floatid - 1) . '\'].push(\'fl' . ($floatid - 2) . '\');
									floatTotal[\'' . "flarv-y-$idshift" . '\'].push(\'fl' . ($floatid - 2) . '\');
									floatTotal[\'' . "flarv-t-$idshift" . '\'].push(\'fl' . ($floatid - 2) . '\');
									updateFloatTotal(\'fl' . ($floatid - 1) . " flarv-a-$idshift flarv-y-$idshift flarv-t-$idshift" . '\'); 
								');
								print end_td;
							print end_Tr;
							my(@fl,%current_floats);
							foreach (@{$$son{'floats'}})
							{
								@fl=split / /;
								$current_floats{"$fl[0] $fl[1]"}=1;
								if($fl[0] ne $shift) { next }

								my($shiftid)="fl$shift-g"; 
								$shiftid =~ s/[:]|\.//g;
								my($id)="fl$shift$fl[1]"; 
								$id =~ s/[:]|\.//g;
								print start_Tr;
								print td("$floats{$fl[1]}{'org'} - $floats{$fl[1]}{'theme'}",hidden(-override=>1,-name=>'floats',-value=>"$fl[0] $fl[1]"));
								print td(
									textfield({id=>"fl$floatid",
										onblur=>'updateFloatTotal(\'fl' . ($floatid + 2) . " flasn-a-$idshift flasn-t-$idshift $id-a $id-t $shiftid-a $shiftid-t')",
										override=>1,name=>"num_of_adults_$fl[1]",value=>$fl[2],size=>2,maxlength=>3}),
									script({type=>'text/javascript'},"floatValidate['$idshift'].push('fl".$floatid++.'\')')

								),
								td(
									textfield({id=>"fl$floatid",
										onblur=>'updateFloatTotal(\'fl' . ($floatid + 1) . " flasn-y-$idshift flasn-t-$idshift $id-y $id-t $shiftid-y $shiftid-t')",
										override=>1,name=>"num_of_youths_$fl[1]",value=>$fl[3],size=>2,maxlength=>3}),
									script({type=>'text/javascript'},"floatValidate['$idshift'].push('fl".$floatid++.'\')')
								);
								print start_td({align=>'center',id=>'fl'.$floatid++}),' ';
								print script({type=>'text/javascript'},'
									floatTotal[\'fl' . ($floatid - 1) . '\']= new Array();
									floatTotal[\'fl' . ($floatid - 1) . '\'].push(\'fl' . ($floatid - 3) . '\');
									floatTotal[\'' . "flasn-a-$idshift" . '\'].push(\'fl' . ($floatid - 3) . '\');
									floatTotal[\'' . "flasn-t-$idshift" . '\'].push(\'fl' . ($floatid - 3) . '\');
									floatTotal[\'' . "$id-a" . '\'].push(\'fl' . ($floatid - 3) . '\');
									floatTotal[\'' . "$id-t" . '\'].push(\'fl' . ($floatid - 3) . '\');
									floatTotal[\'' . "$shiftid-a" . '\'].push(\'fl' . ($floatid - 3) . '\');
									floatTotal[\'' . "$shiftid-t" . '\'].push(\'fl' . ($floatid - 3) . '\');
									floatTotal[\'fl' . ($floatid - 1) . '\'].push(\'fl' . ($floatid - 2) . '\');
									floatTotal[\'' . "flasn-y-$idshift" . '\'].push(\'fl' . ($floatid - 2) . '\');
									floatTotal[\'' . "flasn-t-$idshift" . '\'].push(\'fl' . ($floatid - 2) . '\');
									floatTotal[\'' . "$id-y" . '\'].push(\'fl' . ($floatid - 2) . '\');
									floatTotal[\'' . "$id-t" . '\'].push(\'fl' . ($floatid - 2) . '\');
									floatTotal[\'' . "$shiftid-y" . '\'].push(\'fl' . ($floatid - 2) . '\');
									floatTotal[\'' . "$shiftid-t" . '\'].push(\'fl' . ($floatid - 2) . '\');
									updateFloatTotal(\'fl' . ($floatid - 1) . " flasn-a-$idshift flasn-y-$idshift flasn-t-$idshift $id-a $id-y $id-t $shiftid-a $shiftid-y $shiftid-t" . '\'); 
								');
								print end_td;
								print end_Tr;
							}
							my(@fcleaned);
							foreach (@f)
							{
								if(defined($current_floats{"$shift $_"})) { next }
								push(@fcleaned,"$shift $_");
							}
							foreach (keys %flabels)
							{
								$flabels{"$shift $_"}=$flabels{"$_"};
							}
							if(scalar @fcleaned > 0)
							{
								print start_Tr;
								print start_td;
								print popup_menu({name=>'new_float',values=>\@fcleaned,labels=>\%flabels,default=>"$shift lhf"});
								print end_td;
								print td(textfield({id=>"fl$floatid",
										onblur=>'updateFloatTotal(\'fl' . ($floatid + 2) . " flasn-a-$idshift flasn-t-$idshift')",
									override=>1,name=>'num_of_adults_float',size=>2,maxlength=>3}),
									script({type=>'text/javascript'},"floatValidate['$idshift'].push('fl".$floatid++.'\')'));
								print td(textfield({id=>"fl$floatid",
										onblur=>'updateFloatTotal(\'fl' . ($floatid + 1) . " flasn-y-$idshift flasn-t-$idshift')",
									override=>1,name=>'num_of_youths_float',size=>2,maxlength=>3}),
									script({type=>'text/javascript'},"floatValidate['$idshift'].push('fl".$floatid++.'\')'));
								print start_td({align=>'center',id=>'fl'.$floatid++}),' ';
								print script({type=>'text/javascript'},'
									floatTotal[\'fl' . ($floatid - 1) . '\']= new Array();
									floatTotal[\'fl' . ($floatid - 1) . '\'].push(\'fl' . ($floatid - 3) . '\');
									floatTotal[\'' . "flasn-a-$idshift" . '\'].push(\'fl' . ($floatid - 3) . '\');
									floatTotal[\'' . "flasn-t-$idshift" . '\'].push(\'fl' . ($floatid - 3) . '\');
									floatTotal[\'fl' . ($floatid - 1) . '\'].push(\'fl' . ($floatid - 2) . '\');
									floatTotal[\'' . "flasn-y-$idshift" . '\'].push(\'fl' . ($floatid - 2) . '\');
									floatTotal[\'' . "flasn-t-$idshift" . '\'].push(\'fl' . ($floatid - 2) . '\');
									updateFloatTotal(\'fl' . ($floatid - 1) . " flasn-a-$idshift flasn-y-$idshift flasn-t-$idshift" . '\'); 
								');
								print end_td;
								print end_Tr;
							}
						print end_table;
						print hidden({override=>1,name=>'adm',value=>1}),
						hidden({override=>1,name=>$auth->sfparam_name,value=>$auth->sfparam_value}),
						hidden({override=>1,name=>'shift',value=>$shift}),
						hidden({override=>1,name=>'nextpage',value=>'approved_update'}),
						hidden({override=>1,name=>'load',value=>$$son{'file'}}),
						div({align=>'center',style=>'margin-top: 3px;margin-bottom: 3px'},script({type=>'text/javascript'},'makesubmit(\'\',\'Save\',\'\')')),
						end_form;
					print end_div;
				print end_td;
				print end_Tr;
			}
		}
		print end_table,end_div;
	}

	# page div
	print end_div;
	print '&nbsp;';
	print end_html;

	sub print_form
	{
						# Here is the form
	}
}

sub loadfile
{
	my $file= "$resdataprefix/data/" . param('load');
	open(IN,"$file") || die("cannot open $file");
	restore_parameters(*IN);
	close IN;
	import_names();
}

sub showmenu
{
		if(! defined($Q::adm)) { return }
		my(@items)=(
			'Home',"$location?adm=1;" . $auth->sfparam_name . '=' . $auth->sfparam_value,
			'Rapid Entry',"$location?adm=1;nextpage=startpage;" . $auth->sfparam_name . '=' . $auth->sfparam_value,
			'Search',"$location?adm=1;nextpage=search;" . $auth->sfparam_name . '=' . $auth->sfparam_value,
			'Spreadsheet Report',"$location?adm=1;nextpage=report;" . $auth->sfparam_name . '=' . $auth->sfparam_value,
#			'Archive','#',
			'Logout',"$location?adm=1;nextpage=logout;". $auth->sfparam_name . '=' . $auth->sfparam_value,
		);
		print start_div({id=>'navcontainer'}), start_ul({id=>'navlist'});
		for(my($i)=0;$i< $#items; $i+=2)
		{
			if($i == $_[0]) { print li({id=>'active'},a({id=>'current',href=>$items[$i+1]},$items[$i])); }
			else
			{ print li(a({href=>$items[$i+1]},$items[$i])); }
		}
		print end_ul;
		if(defined($_[1]))
		{
			my(@a)=('All');
			my(%l);
			foreach my $t (sort keys %{$_[1]})
			{
				push(@a,$t);
				$l{$t}=$dates{$t}{'display'};
			}
			print start_div({style=>'float: right'}),start_form({name=>'show_dates',
			action=>$location}),'Show Date(s): ',
			popup_menu({style=>'margin-top: 3px',
				name=>'show_dates',
				values=>\@a,
				default=>($show_date ne ''? $show_date: 'All'),
				labels=>\%l,
				onchange=>'document.show_dates.submit()'
				}),
				hidden(-override=>1,-name=>'nextpage',-value=>'show_dates'),
				hidden(-name=>'adm',-value=>'1'),
				hidden(-name=>$auth->sfparam_name,-value=>$auth->sfparam_value),
			end_form,end_div;
		}
		print end_div;
	}

sub resend_confirmation
{
			open(IN,"+<$resdataprefix/data/$Q::load") || die "Cannot open $resdataprefix/data/$Q::load";
			my($q)=new CGI(\*IN);
			send_confirmation($q);
			seek(IN,0,0) || die "Cannot seek in $resdataprefix/data/$Q::load";
			$q->save(\*IN);
			close IN;
}

sub update_requests
{
		my($q,%changefields);
		my(@fields)=split(/ /,param('changefields'));
		# Create hash of new status
		for(my $i=0 ;$i < $#fields; $i+=2)
		{
			# {filename}{shiftdate}=newstatus
			$changefields{$fields[$i]}{$fields[$i+1]}=param("$fields[$i] $fields[$i+1]")
		}
		my(@ddline);
		my($noPending);
		foreach my $file (keys(%changefields))
		{
			open(IN,"+<$resdataprefix/data/$file") || die "Cannot open $resdataprefix/data/$file";
			$q=new CGI(\*IN);
			my(@newdd);
			$noPending=1;
			foreach ($q->param('dd'))
			{
				@ddline=split / /;
				# Record Layout is Timestamp, Choice (1st or 2nd), and Status 
				if(defined($changefields{$file}{$ddline[0]}))
				{
					push(@newdd,"$ddline[0] $ddline[1] $changefields{$file}{$ddline[0]}");
					if($changefields{$file}{$ddline[0]}==$DAY_PENDING)
					{
						$noPending=0;
					}
				}
			}
			$q->param(-name=>'dd',-values=>\@newdd);
			if($noPending)
			{
				# Send Email Confirmation
				send_confirmation($q);
			}
			seek(IN,0,0) || die "Cannot seek in $resdataprefix/data/$file";
			$q->save(\*IN);
			close IN;
		}
}

sub send_confirmation
{
		# $1 is CGI.pm object

		my(%ph)=$_[0]->Vars;
		my($to)='';

		if($ph{'email1'} =~ /[@]/) { $to="\"$ph{'name1'}\" <$ph{'email1'}>" }
		if($ph{'email2'} =~ /[@]/) { $to .=",\"$ph{'name2'}\" <$ph{'email2'}>"; }

		if($to eq '')
		{ return; }
		else
		{ $_[0]->append(-name=>'confirmation_sent',-values=>[ParseDate('now') . '|' . $to]) }

		my($sendmail_from)='"Petal Pushers" <Reservations@petalpushers.org>';

		my($from)=$sendmail_from;
		my($fh,$fname)=tempfile();
		select($fh);

		send_confirmation_page(0,\%ph);
		select(STDOUT);
		seek($fh,0,0);

		my($names)="$ph{'name1'},";
		if($ph{'name2'} ne '') { $names .=" $ph{'name2'},"}


		my($data)=<<EOF;

$names

Attached to this email is a Confirmation of Volunteer Dates.  Please carefully review the dates.  Some of the dates may not have been approved because of a full schedule.

Thank you for volunteering with Petal Pushers,

Reservations\@petalpushers.org
EOF

		my($msg) = MIME::Lite->new(
			From    =>$from,
			To 		=>$to,
			Subject => 'Confirmation of Volunteer Dates',
			Type    =>'multipart/mixed'
		);

		$msg->attach(
			Type=>'text/plain',
			Encoding =>'base64',
			Data=>$data
		);

		$msg->attach(
			Type=>'text/html',
			Encoding =>'base64',
			Path=>$fname,
			Disposition =>'attachment',
			Filename=>'Confirmation.html'
		);

		$msg->send_by_sendmail( BaseArgs=>['-t', '-i'], SetSender=>0);
		unlink($fname);
}

sub send_confirmation_page
{
		# $0 is 0 or 1 to print the html header 
		# $1 is the CGI object paramater hash form the CGI::Vars() method

		autoEscape(0);
		if($_[0]) { print header; }
		# ph is a hashref, therefore $$ph{'stuff'} is correct
		my($ph)=$_[1];

		my($title)='Petal Pushers&reg; Confirmation of Volunteer Dates';
		print start_html({-base=>1,title=>$title,
			-script=>[{-src=>'/res/res.js',-type=>'text/javascript'}],
			head=>[
				Link({rel=>'SHORTCUT ICON',href=>'/favicon.ico'}),
				Link({rel=>'StyleSheet',href=>'/res/res.css',type=>'text/css'})
			]});
		autoEscape(1);

		print start_div({style=>'width: 765px;  margin: 5px'});

		print h3({align=>'center'},'Confirmation of Volunteer Dates');
		print start_div({class=>'ind'});
		print p('Here is your Petal Pushers&reg; confirmation.  If you need
		to change any information, simply send an email to ',a({href=>'mailto:%20Reservations@petalpushers.org'},'Reservations@petalpushers.org'),'.'),
		p('In addition to reviewing the dates, please complete the following tasks before your visit:'),
		ol(
			li('Review the ',a({href=>'http://petalpushers.org/confirmation.php'},'Confirmation Information'),' page.'),
			li('If you are a group, fill-out a ',a({href=>'http://petalpushers.org/PizzaForm.php'},'Pizza Order Form'),'.'),
			li('Print out a ',a({href=>'http://petalpushers.org/map.php'},'map'),' and locate the parking area.'),
		),
		p('Thank you for volunteering with Petal Pushers&reg;.');

		print end_div,
		h4('Approved Dates');

		my(@pa); 
		my($cell)=0;
		print start_div({align=>'center'}),start_table({class=>'shifttbl',style=>'width: 575px'});
		print Tr(th('Event'),th('Day'),th({colspan=>3},'Shift'),th('Choice'),th('Status'));

		my(@ddline);
		my(@dd)=split("\0",$$ph{'dd'});
		foreach (sort by_dd (@dd))
		{
			@ddline=split / /;

			if($ddline[2] != $DAY_APPROVED) { next }
			@pa=split(/ /,$dates{$ddline[0]}{'display'});
			print start_Tr({style=>((($cell / 2) % 2) == 1 ? 'background-color: #f0f0f0': '')}),
				td({style=>'text-align: center'},($dates{$ddline[0]}{'daytype'} == 0 ? 'Detail Day' : 'Decorating Day')),
				td("$pa[0] $pa[1]"),
				td({style=>'text-align: right; padding-right: 0'},$pa[2]),
				td({style=>'padding-left: 2px; padding-right: 2px; margin: 0'},$pa[3]),
				td({style=>'text-align: left; padding-left: 0'},$pa[4])
			;

			if($ddline[1] == 1)
			{ print td({align=>'center'},'1st') }
			else
			{ print td({align=>'center'},'2nd') }

			print td({align=>'center'},'Approved');

			print end_Tr;
			$cell += 2;
		}
		print end_table,end_div;

		$cell=0;
		print h4('Not Approved Dates');
		print start_div({align=>'center'}),start_table({class=>'shifttbl',style=>'width: 575px'});
		print Tr(th('Event'),th('Day'),th({colspan=>3},'Shift'),th('Choice'),th('Status'));

		foreach (sort by_dd (@dd))
		{
			@ddline=split / /;

			if($ddline[2] == $DAY_APPROVED) { next }
			@pa=split(/ /,$dates{$ddline[0]}{'display'});
			print start_Tr({style=>((($cell / 2) % 2) == 1 ? 'background-color: #f0f0f0': '')}),
				td({style=>'text-align: center'},($dates{$ddline[0]}{'daytype'} == 0 ? 'Detail Day' : 'Decorating Day')),
				td("$pa[0] $pa[1]"),
				td({style=>'text-align: right; padding-right: 0'},$pa[2]),
				td({style=>'padding-left: 2px; padding-right: 2px; margin: 0'},$pa[3]),
				td({style=>'text-align: left; padding-left: 0'},$pa[4])
			;

			if($ddline[1] == 1)
			{ print td({align=>'center'},'1st') }
			else
			{ print td({align=>'center'},'2nd') }

			print td({align=>'center'},($ddline[2] == $DAY_NOT_APPROVED?'Not Approved':'Pending'));

			print end_Tr;
			$cell += 2;
		}
		print end_table,end_div;

		print h4('Contact Information');
		print start_div({class=>'ind'});
		my($ci)=$$ph{'name1'};
		if($$ph{'name1'} ne '') { $ci .= "<br />$$ph{'name2'}" }
		if($$ph{'orgname'} ne '') { $ci .= '<br />' . escapeHTML($$ph{'orgname'}) }

		if($$ph{'addr1'} ne '' ||
			$$ph{'addr2'} ne '' ||
			$$ph{'city'} ne '' ||
			$$ph{'st'} ne '' ||
			$$ph{'zip'} ne ''
			)
		{
			$ci .= "<br />$$ph{'addr1'}";
			if($$ph{'addr2'} ne '') { $ci .= "<br />$$ph{'addr2'}" }
			$ci .= "<br />$$ph{'city'}, $$ph{'st'} $$ph{'zip'}";
		}
		$ci .= "<br />Adults: $$ph{'num_of_adults'}";
		if($$ph{'num_of_youths'} ne '') { $ci .= "<br />Youths: $$ph{'num_of_youths'}" }

		$ci .= '<br />';
		if($$ph{'day_ph'} ne '') { $ci .= "<br />Day Phone: $$ph{'day_ph'}" }
		if($$ph{'evening_ph'} ne '') { $ci .= "<br />Evening Phone: $$ph{'evening_ph'}" }
		if($$ph{'mobile_ph'} ne '') { $ci .= "<br />Mobile Phone: $$ph{'mobile_ph'}" }

		print $ci;
		print end_div;

		print h4('Confirmation Email(s)');

		if($$ph{'email1'} =~ /[@]/)
		{
			print start_div({class=>'ind'});
			print escapeHTML("\"$$ph{'name1'}\" <$$ph{'email1'}>");
			if($$ph{'email2'} ne '') { print '<br />' . escapeHTML("\"$$ph{'name2'}\" <$$ph{'email2'}>") }
			print end_div;
		}

		if($$ph{'comments'} ne '')
		{
			print h4('Comments');
			print start_div({class=>'ind'});
			print p($$ph{'comments'});
			print end_div;
		}

		print end_div;
		print end_html; 
}

sub by_dd
{
		my(@a)=split(/ /,$a);	
		my(@b)=split(/ /,$b);	
		# Sort by shift then date stamp
		($a[1] <=> $b[1]) || ($a[0] cmp $b[0]);
}

sub send_search_page
{
		my(%files);	
		my $orgname;
		my $name1;
		my($q);
		foreach my $file (<$resdataprefix/data/*.txt>)
		{
			open(IN,$file) || die "Cannot open $_";
			$q=new CGI(\*IN);
			$file =~ s#.*/##; 
			$orgname=$q->param('orgname');
			$name1=$q->param('name1');
			$files{$orgname}{$name1}{'file'}=$file;
			$files{$orgname}{$name1}{'submit_date'}=$q->param('submit_date');
			$files{$orgname}{$name1}{'orgname'}=$orgname;
			$files{$orgname}{$name1}{'name1'}=$name1;
			$files{$orgname}{$name1}{'email1'}=$q->param('email1');
			$files{$orgname}{$name1}{'name2'}=$q->param('name2');
			$files{$orgname}{$name1}{'email2'}=$q->param('email2');
			$files{$orgname}{$name1}{'comments'}=escapeHTML($q->param('comments'));
			$files{$orgname}{$name1}{'comments'}=~ s#\r\n#<br />#g;
			$files{$orgname}{$name1}{'num_of_adults'}=$q->param('num_of_adults');
			$files{$orgname}{$name1}{'num_of_youths'}=$q->param('num_of_youths');
			close IN;
		}

		autoEscape(0);
		print header,start_html({title=>'Petal Pushers&reg; Scheduling System',
			script=>[{-src=>'/res/overlib.js',-type=>'text/javascript'}],
			head=>[
				Link({rel=>'SHORTCUT ICON',href=>'/favicon.ico'}),
				Link({rel=>'StyleSheet',href=>'/res/res.css',type=>'text/css'}),
				Link({rel=>'StyleSheet',href=>'/res/menu.css',type=>'text/css'})
			]});
		autoEscape(1);
		print start_div({style=>'width: 765px;  margin: 5px'});
		showmenu(4);
		print br;
		my($mailto);
		print start_div,start_table({class=>'filestbl'});
		foreach my $orgname (sort noundef (keys %files))
		{
			foreach my $name1 (sort keys %{$files{$orgname}} )
			{
				# Make mailto 
				$mailto  = ($files{$orgname}{$name1}{'email1'} =~ /[@]/ ? "mailto:\%20$files{$orgname}{$name1}{'email1'}" : '');
				$mailto .= ($files{$orgname}{$name1}{'email2'} =~ /[@]/ ? ",$files{$orgname}{$name1}{'email2'}" : '');

				print Tr(
					td({style=>'width: 5%'},'Submit Date: '),
					td({style=>'width: 45%'},a({href=>"$location?adm=1;nextpage=startpageload;load=$files{$orgname}{$name1}{'file'};" . $auth->sfparam_name . '=' . $auth->sfparam_value},pdate($files{$orgname}{$name1}{submit_date})),


				(length($files{$orgname}{$name1}{'comments'}) ? 
				a({href=>'javascript:void(0);',onmouseover=>"return overlib('$files{$orgname}{$name1}{'comments'}',HAUTO,VAUTO,CAPTION,'Comments',FGCOLOR,'#fff8dc',BGCOLOR,'#7f7f7f');",onmouseout=>'return nd();'},
				img({border=>0,alt=>'',align=>'top',src=>'/res/emotionicon-praying-63.gif'})) 
				: '')),

					td({style=>'vertical-align: top;width: 5%'},'Name: '),
					td(($files{$orgname}{$name1}{'email1'} =~ /[@]/ ? a({href=>$mailto},escapeHTML($files{$orgname}{$name1}{'name1'}) . " ($files{$orgname}{$name1}{'email1'})") : $files{$orgname}{$name1}{'name1'})
					),
					td({style=>'width: 2%'},'Adults: '),
					td({style=>'width: 2%;text-align: right'},$files{$orgname}{$name1}{'num_of_adults'}),
				);
				print Tr(
					td({class=>'filestblbtm',style=>'vertical-align: top'},'Organization: '),
					td({class=>'filestblbtm'},($files{$orgname}{$name1}{'orgname'} ne '' ? escapeHTML($files{$orgname}{$name1}{'orgname'}) : '&nbsp;')),
					td({class=>'filestblbtm',style=>'vertical-align: top'},'Name: '),
					td({class=>'filestblbtm'},($files{$orgname}{$name1}{'email2'} =~ /[@]/ ? a({href=>$mailto},escapeHTML($files{$orgname}{$name1}{'name2'}). " ($files{$orgname}{$name1}{'email2'})") : $files{$orgname}{$name1}{'name2'})),
					td({class=>'filestblbtm',style=>'width: 2%'},'Youths: '),
					td({class=>'filestblbtm',style=>'width: 2%;text-align: right'},$files{$orgname}{$name1}{'num_of_youths'})
				);
			}
		}
		print end_table,end_div;
		print end_div;
		print end_html;
}
sub pdate
{
		$_=UnixDate($_[0],"\045f.\045e.\045Y, \045i:\045M\045p");
		s/\s(\s)/$1/g;
		s/(\.)\s(\d)/$1$2/g;
		s/(AM|PM)/\L$1/g;
		return $_;
}
sub noundef
{
	if(length($a) == 0) { return 1 }
	if(length($b) == 0) { return -1 }
	$a cmp $b;
}
sub update_count
{
	# load file
	# save ay arrived
	# load assignments hash 
	# for each float, if ay==0, delete from hash
	# if present, update to new totals
	# write new_float and new ay totals
	# write new hash
	open(F,"+<$resdataprefix/data/$Q::load") || die "Cannot open $resdataprefix/data/$Q::load";
	my($q)=new CGI(\*F);

	# Update Arrived Adult & Youth Counts
	if($Q::num_of_adults_arrived ne '' || $Q::num_of_youths_arrived ne '')
	{
		my($a)=($Q::num_of_adults_arrived ne '' ? $Q::num_of_adults_arrived : 0);
		my($y)=($Q::num_of_youths_arrived ne '' ? $Q::num_of_youths_arrived : 0);
		my(%arrived,@aline);
		print STDERR "ay $a $y $Q::shift\n";
		foreach ($q->param('arrived'))
		{
			@aline=split / /;
			$arrived{$aline[0]}="$aline[1] $aline[2]"
		}
		if(($a + $y) > 0)
		{
			$arrived{$Q::shift}="$a $y";
		}
		else
		{
			delete $arrived{$Q::shift};
		}
		@aline=();
		foreach (sort keys %arrived)
		{
			push(@aline,"$_ $arrived{$_}");
		}
		(scalar @aline == 0 ? $q->delete('arrived') : $q->param(-name=>'arrived',-values=>\@aline));
	}
	my(%floats,@fline);
	foreach ($q->param('floats'))
	{
		# fline 0=shift 1=floatid 2=adults 3=youths
		@fline=split / /;
		$floats{"$fline[0] $fline[1]"}{'adults'}=$fline[2];
		$floats{"$fline[0] $fline[1]"}{'youths'}=$fline[3];
	}
	my($a,$y);
	foreach (param('floats'))
	{
		@fline=split / /;
		if(! defined($floats{"$fline[0] $fline[1]"})) { next }
		$a=param("num_of_adults_$fline[1]");
		$y=param("num_of_youths_$fline[1]");
		if($a==0 && $y==0)
		{
			delete $floats{"$fline[0] $fline[1]"};
		}
		else
		{
			{ no warnings;
		$floats{"$fline[0] $fline[1]"}{'adults'}=$a + 0;
		$floats{"$fline[0] $fline[1]"}{'youths'}=$y + 0;
			}
		}
	}

		{ no warnings;
	if(
		($Q::num_of_adults_float ne '' || $Q::num_of_youths_float ne '') &&
		($Q::num_of_adults_float + $Q::num_of_youths_float > 0)
	)
	{
		$floats{$Q::new_float}{'adults'}=$Q::num_of_adults_float + 0;
		$floats{$Q::new_float}{'youths'}=$Q::num_of_youths_float + 0;
	}
		}

	@fline=();
	foreach (keys %floats)
	{
		push(@fline,"$_ $floats{$_}{'adults'} $floats{$_}{'youths'}");
	}
	seek(F,0,0) || die "Cannot seek in $resdataprefix/data/$Q::load";

	(scalar @fline == 0 ? $q->delete('floats') : $q->param(-name=>'floats',-values=>\@fline));
	$q->save(\*F);
	close F;
}
sub send_report
{   
   my $filename=UnixDate(ParseDate('today'),"PetalPushersRpt-\045Y\045m\045d\045H\045M.xls");
   print "Content-type: application/vnd.ms-excel\n";
   print "Content-Disposition: attachment; filename=$filename\n\n";
   my $wb= Spreadsheet::WriteExcel->new("-");

   my $ws= $wb->add_worksheet('Work Schedule');
   #$ws->hide_gridlines(0);
   $ws->set_landscape();

	my(%shift,$onn,$phs);
	my(%floats);
	my(@ddline);
	my($q);
	foreach my $file (<$resdataprefix/data/*.txt>)
	{
		open(IN,$file) || die "Cannot open $_";
		$q=new CGI(\*IN);
		foreach ($q->param('dd'))
		{
			@ddline=split / /;
			if($ddline[2] != $DAY_APPROVED) { next }
			$onn=($q->param('orgname') ne '' ? $q->param('orgname') : '');
			$onn.=($q->param('name1') ne '' ? ( length($onn) == 0 ? $q->param('name1') : "\n" . $q->param('name1')) : '');
			$onn.=($q->param('name2') ne '' ? ', ' . $q->param('name2') : '');
			$phs=(($_=$q->param('day_ph')) ne '' ? "D:$_" : '');
			$phs.=(($_=$q->param('evening_ph')) ne '' ? (length($phs) > 0 ? "\nE:$_" : "E:$_") : '');
			$phs.=(($_=$q->param('mobile_ph')) ne '' ? (length($phs) > 0 ? "\nM:$_" : "M:$_") : '');
			$shift{$ddline[0]}{$onn}{'phs'}=$phs;
				{ no warnings ;
			$shift{$ddline[0]}{$onn}{'exp'}=$q->param('num_of_adults') + $q->param('num_of_youths');
				}
			$shift{$ddline[0]}{$onn}{'arv'}=0;
			foreach ($q->param('arrived'))
			{
				my @ar=split;
				if($ddline[0] ne $ar[0]) {next}
				$shift{$ddline[0]}{$onn}{'arv'}=$ar[1] + $ar[2];
			}
			$shift{$ddline[0]}{$onn}{'cityst'}=($q->param('city') ne '' ? $q->param('city') . ', ' . $q->param('st') : '');
			foreach ($q->param('floats'))
			{
				my @f=split;	
				if($ddline[0] ne $f[0]) {next}
					{ no warnings ;
				$floats{$f[0]}{$f[1]}{$onn}{'arv'}=$f[2] + $f[3];
					}
			}
		}
		close IN;
	}
   # Write to the workbook
   # row,col
   my($r,$c)=0;
	my $wrap = $wb->add_format(text_wrap => 1, align => 'top');
	my($hidden) = $wb->add_format(hidden => 0);
	my($top) = $wb->add_format(align => 'top');
	my($bold) = $wb->add_format('bold' => 1);
	my($num) = $wb->add_format(align=>'top', num_format => '#,###', align => 'center');
	my($bnum) = $wb->add_format(align=>'top','num_format' =>'#,###','align'=>'center','bold'=>1);
	my($cacross)= $wb->add_format(align=>'center_across');
	my($center) = $wb->add_format();
	$center->set_align('center');
	$center->set_align('top');
	$ws->freeze_panes(1,1);
	$ws->fit_to_pages(1,0);
	$ws->repeat_rows(0,1);
	$ws->set_margins_LR('.5'); $ws->set_header('&CPetal Pushers Work Schedule');
	$ws->set_footer('&L&D, &T&RPage &P of &N');
	$ws->set_column($c,$c,33) ; $ws->write_string($r,$c++,'Shift:'); 
   $_='Contact:' ; $ws->set_column($c,$c,40,$wrap) ; $ws->write_string($r,$c++,$_); 
   $_='Phone:' ; $ws->set_column($c,$c,16,$wrap) ; $ws->write_string($r,$c++,$_); 
   $_='City:' ; $ws->set_column($c,$c,16,$wrap) ; $ws->write_string($r,$c++,$_); 
   $_='Expected:' ; $ws->set_column($c,$c,9);$ws->write_string($r,$c++,$_,$center); 
   $_="Arrived:" ; $ws->set_column($c,$c,5,$center);$ws->write_string($r,$c++,$_,$cacross); 
	$ws->set_column($c,$c,5,$center) ; $ws->write_blank($r,$c,$cacross);
	$ws->write_blank(++$r,0);

	$c=0;
	$r++;
	my($r_shift_start)=$r;
	foreach my $s (sort keys %shift) 
	{
		foreach my $o (sort keys %{$shift{$s}}) 
		{
			$c=0;
			$ws->write_string($r,$c++,$dates{$s}{'display'},$top);
			$ws->write_string($r,$c++,$o,$wrap);
			$ws->write_string($r,$c++,$shift{$s}{$o}{'phs'});
			$ws->write_string($r,$c++,$shift{$s}{$o}{'cityst'},$top);
			$ws->write_number($r,$c++,$shift{$s}{$o}{'exp'},$num);
			$ws->write_number($r,$c++,$shift{$s}{$o}{'arv'},$num);
			$r++;
		}
			$ws->write_string($r,0,'Shift Sub Total:',$bold);
			$ws->write_formula($r++,$c,'SUM(F' . $r_shift_start . ':F' . $r . ')',$bnum);
			$r_shift_start=($r + 1);
	}
	$r++;
	$ws->write_string($r,0,'Totals:',$bnum);
	$ws->write_formula($r,4,'SUM(E3:E' . $r . ')',$bnum);
	$ws->write_formula($r,5,'SUM(F3:F' . $r . ')',$bnum);
	# Floats Worksheet
	$r=0;
	$c=0;

   $ws= $wb->add_worksheet('Float Assignments');
   $ws->set_landscape();
	$ws->freeze_panes(1,1);
	$ws->fit_to_pages(1,0);
	$ws->repeat_rows(0,1);
	$ws->set_margins_LR('.5'); $ws->set_header('&CPetal Pushers Float Assignments');
	$ws->set_footer('&L&D, &T&RPage &P of &N');

   $_='Shift:' ; $ws->set_column($c,$c,40,$wrap) ; $ws->write_string($r,$c++,$_); 
   $_='Float:' ; $ws->set_column($c,$c,40,$wrap) ; $ws->write_string($r,$c++,$_); 
   $_='Contact:' ; $ws->set_column($c,$c,40,$wrap) ; $ws->write_string($r,$c++,$_); 
   $_='Assigned:' ; $ws->set_column($c,$c,5,$center) ; $ws->write_string($r,$c++,$_,$cacross); 
	$ws->set_column($c,$c,5,$center) ; $ws->write_blank($r,$c++,$cacross);
	$ws->set_column($c,$c,5,$center) ; $ws->write_blank($r,$c,$cacross);
	$ws->write_blank(++$r,0);
	$c=0;
	$r++;
	my $r_fl_start=$r;
	$r_shift_start=$r;
	# Load floats 
	open(FF,$ppfloats) || die "Cannot open $ppfloats";
	while (<FF>)
	{
		chomp;
		if(/[#]/) { next }
		@float=split(/\|/);
		$flabels{$float[1]}="$float[2]\n$float[3]";
	}
	close FF;

	foreach my $s (sort keys %floats)
	{
		foreach my $f (sort keys %{$floats{$s}})
		{
			foreach my $o (sort keys %{$floats{$s}{$f}})
			{
				$c=0;
				$ws->write_string($r,$c++,$dates{$s}{'display'},$top);
				$ws->write_string($r,$c++,$flabels{$f},$wrap);
				$ws->write_string($r,$c++,$o,$wrap);
				$ws->write_number($r,$c++,$floats{$s}{$f}{$o}{'arv'},$num);
				$r++;
			}
			$ws->write_string($r,0,'Float Sub Total:',$bold);
			$ws->write_formula($r++,$c,'SUM(D' . $r_fl_start . ':D' . $r . ')',$bnum);
			$r_fl_start=($r + 1);
		}
		$ws->write_string($r,0,'Shift Sub Total:',$bold);
		$ws->write_formula($r++,($c + 1),'SUM(D' . $r_shift_start . ':D' . $r . ')',$bnum);
		$r_shift_start=($r + 1);

	}
	$r++;
	$ws->write_string($r,0,'Totals:',$bnum);
	$ws->write_formula($r,3,'SUM(D3:D' . $r . ')',$bnum);
}
# vi: set shiftwidth=3 tabstop=3: 

