#!/usr/bin/perl 
$color{F}="ff4444";
$color{R}="00aa88";
$color{C}="0000ff";
$color{E}="0000ff";
$color{L}="cc6600";

    @datetime=localtime(time);
    $monimplant='';
    $dayimplant='';
    if($datetime[4]+1 < 10)
    {
	$monimplant='0';
    }
    if($datetime[3]<10)
    {
	$dayimplant='0';
    }
    $today=join('', ($datetime[5]+1900),$monimplant,($datetime[4]+1),$dayimplant,($datetime[3]));
#    $today='20010717';
$var{year}=substr $today,0,4;
   #get the query string
if($ENV{REQUEST_METHOD} eq 'GET')
{
    $query=$ENV{QUERY_STRING};
}
if($ENV{REQUEST_METHOD} eq 'POST')
{
    read(STDIN,$query,$ENV{CONTENT_LENGTH});
}
$query=~s/\+/ /g;
$query=~ s/%(..)/chr(hex($1))/ge ;
   #decode query string into variable list
##### set defalt values #####
$var{loc}=3;

##### get query #########
if (defined($query))
{
    @list=split('&', $query);
    foreach (@list)
    {
	my ($key,$value) = split /=/;
	$var{$key}=$value;
    }
}
$var{myname}=uc $var{myname};
$var{zone}="lt";
sub datediff
{
    ($date1,$date2)=@_;
    $day1=substr $date1, 6,2;
    $day2=substr $date2, 6,2;
    $mon1=substr $date1, 4,2;
    $mon2=substr $date2, 4,2;
    $yr1=substr $date1, 0,4;
    $yr2=substr $date2, 0,4;
    print `../private/julian/j.run $yr1 $mon1 $day1 0 0 0 > junk`;
    open(TIME, "<junk");
    $junk=<TIME>;
    $jday1=<TIME>;
    $jday1=substr $jday1, 5;
    close(TIME);
    print `../private/julian/j.run $yr2 $mon2 $day2 0 0 0 > junk`;
    open(TIME, "<junk");
    $junk=<TIME>;
    $jday2=<TIME>;
    $jday2=substr $jday2, 5;
    close(TIME);
    $daydiff=$jday1-$jday2;
    return($daydiff)
}
##########################################
########### find out personal info #######
##########################################
open(SUS, "<../private/workfiles/emplist");
foreach(<SUS>)
{
    chomp;
    if((!((uc $_)=~m/RETI/))and(!((uc $_)=~m/INIT/)))
    {
	
	($intl,$name,$career,$citiz,$location,$comment)=split('#',$_);
	$cit{uc $intl}=uc $citiz;
    }
}
close(SUS);

$everyone=join(',',keys %cit);
$everyone=join(',',$everyone,"NEVIS1","NEVIS2");



print("Content-type: text/html\n\n");
    
print'<HTML><HEAD><TITLE>HiRes schedule editing site</TITLE></HEAD>';
print '<BODY bgcolor=bbbbbb><TABLE bgcolor=ffaaff>';

################ Help Bar #########################
open(HELP, "<helpbar");
foreach(<HELP>)
{
    chomp;
    if(!($_=~m/sign/)or !($_=~m/href/))
    { 
	print"$_";
    }
    elsif($_ =~m/sign/)
    {
	($first,$second)=split('>',$_);
	print"$first ><FONT color=ff0000>$second ></FONT>";
    }
}
close(HELP);


print'</FORM></TABLE><TABLE>';
print'</FORM></TABLE><TABLE>';
###############################################################################
##################### 1 initial web page, get name and what not ###############
###############################################################################
if (!defined($var{whichrun}))
{   
    print('<FORM method=GET ACTION="signmeup.pl" name="bob">
 <TR><TD width=150></TD><TD>');
    print(`ls ../private/runs > junk`);
    print("<TR><TD>Choose a run by its starting date:</TD><TD>");
    open(RUN, "<junk");
    foreach(<RUN>)
    {
	chop;
	$thisyear=substr $_,0,4;
	$startrun=substr $_,0,8;
	$endrun=substr $_,9,8;
	if($thisyear == $var{year})
	{
	    $yy1=substr $_,0,4;
	    $mm1=substr $_,4,2;
	    $dd1=substr $_,6,2;
	    $yy2=substr $_,9,4;
	    $mm2=substr $_,13,2;
	    $dd2=substr $_,15,2;
	    $ym1=join('',$yy1,$mm1);
	    $ym2=join('',$yy2,$mm2);
	    print'<INPUT type="radio" name="whichrun" value="',$_,'">',"$yy1/$mm1/$dd1-$yy2/$mm2/$dd2";
	    if(((substr $today,0,4)eq $yy1)or((substr $today,0,4)eq $yy2))
	    {
		if(($today<=$endrun)and($today>=$startrun))
		{
		    print' - Current run!';
		}
		$todayym=substr $today,0,6;
		if(($today<$startrun)and($today>$lastendrun)and(($ym1 == $todayym)or($ym1==$todayym+1)))
		{
		    print' -up coming run!';
		}
	    }
	    $lastendrun=$endrun;
	    print'<BR>';
	}
    }
    close(RUN);
    print("</TD></TR></TABLE><TABLE><TR>");
    print('<TD width=300></TD><TD> <INPUT type=submit value="Enter"></TD></TR></TABLE><TABLE><TR><TD><BR>');
    print'</TR></TABLE></FORM><TABLE>';
    print'<TR><TD>------------------------------------------</TD></TR>';
    print'<FORM method=GET ACTION="signmeup.pl">';
    print'<INPUT type="submit" name="year" value="',$var{year}-1,'">';
    print"<-$var{year}->";
    print'<INPUT type="submit" name="year" value="',$var{year}+1,'">';
    print'</FORM>';
    print'<FORM method=GET ACTION="signmeup.pl">';
    print"<TR><TD>The selected year is $var{year}</TD></TR><TR><TD>
If you would like to choose a different year please enter it below</TD></TR><TR><TD>";
    print'<INPUT type="text" size="4" maxlength=4 name="year"><INPUT type="submit" value="Okay">';
    print'</TABLE></FORM></BODY></HTML>';
}
###############################################################################
####################### step 2 display work schedule and ask to change it #####
###############################################################################
if(defined($var{whichrun}))
{
    $nogo=0;
    $addok=1;
    $dropok=1;
################################################
#### get value of next and previous runs #######
################################################
    system"ls ../private/runs/ > junk";
    open(RUNS, "<junk");
    foreach(<RUNS>)
    {
	chomp;
	if((substr $_,0,8)<(substr $var{whichrun},0,8))
	{
	    $previous=$_;
	}
	if(((substr $_,0,8)>(substr $var{whichrun},0,8))and(!defined($next)))
	{
	    $next=$_;
	}
    }
    close(RUNS);

################################################
    $illegal=1;
    $otros=0;
    @datetime=localtime(time);
    $monimplant='';
    $dayimplant='';
    if($datetime[4]+1 < 10)
    {
	$monimplant='0';
    }
    if($datetime[3]<10)
    {
	$dayimplant='0';
    }
    #$today=join('', ($datetime[5]+1900),$monimplant,($datetime[4]+1),$dayimplant,($datetime[3]));
    
    print'<TR>';

##### Helpfull info
    print'<TABLE bgcolor=ffaaff><TR>';
    print("Todays date is: $today<BR>");
    if((defined($var{newdate}))and($var{act} eq "drop"))
    {
	$dist=datediff($var{newdate},$today);
	if($dist<7)
	{
	    $nogo=1;
	    
	    push @reasons, "You cannot drop a date unless there are at least two others signed up!";
	}
    }

#################################
######## color code #############
#################################
#    print"<TABLE><FONT color=$color{F}>FOREIGN NATIONAL</FONT><BR><FONT color=$color{E}>ESCORT</FONT><BR>";
#    print"<FONT color=$color{R}>PERMANENT RESIDENT</FONT><BR><FONT color=$color{C}>CITIZEN</FONT><BR>";
#    print"<FONT color=$color{L}>CLEARANCE LEVEL</FONT></TABLE>";


    print'<TABLE><TR><TD>Switch to </TD><TD>';



################This was what was here before hires3 came about#########
#    print'<TABLE><TR><TD><FORM method=GET ACTION="signmeup.pl">';
#    print'<INPUT type="hidden" name="myname" value="',$var{myname},'">';
#    print'Switch to <INPUT type="hidden" name="whichrun" value="',$var{whichrun},'">';
#    
    
#    if($var{loc} ==1)
#    {
#        print'<INPUT type=hidden name="loc" value="2">';
#	print'<INPUT type="submit" value="HiRes 2">' ;
#    }
#    if($var{loc}==2)
#    {
#	print'<INPUT type=hidden name="loc" value="1">';
#	print'<INPUT type="submit" value="HiRes 1">' ;
#    }
#    print'</FORM></TD>';
########################################################################










    print'<TD> >>>>> <FORM method=GET ACTION="signmeup.pl"><INPUT type=hidden name="whichrun" value="',$next,'"></TD><TD>';
    
    print'<INPUT type="hidden" name="loc" value=',$var{loc},'>';
    print'<INPUT type=submit value="Next Run"></FORM></TD>';
    print'<TD><FORM method=GET ACTION="signmeup.pl"><INPUT type=hidden name="whichrun" value="',$previous,'">';
    print'<INPUT type="hidden" name="loc" value=',$var{loc},'>';
    print'<INPUT type=submit value="Previous Run"></FORM></TD></TR>';
    print"\n\n</TABLE><TABLE><CENTER><B>Run = ",(substr $var{whichrun},0,4),"/",(substr $var{whichrun},4,2),"/";
    print (substr $var{whichrun},6,2);
    print"-",(substr($var{whichrun},9,4)),"/",(substr $var{whichrun},13,2),"/",(substr $var{whichrun},15,2);
    print"</B></CENTER></TABLE>";

#############################################
###### update the runs file if needed #######
#############################################
    if((defined($var{act}))and(defined($var{myname}))and($everyone =~m/$var{myname}/))
    {
       
	$var{myname}=uc $var{myname};
	open(RUNTMP, ">junk");
	open(RUN, "<../private/runs/$var{whichrun}");
	foreach(<RUN>)
	{
	    chop;
	    ($date{lt},$moon{lt},$moon{ut},$length,$jday,$hires{1},$hires{2},$hires{3},$comm,@waste)=split /#/;
	    $dw=substr $moon{lt},0,3;
	    
	    (@hilist1)=split('/',$hires{1});
	    (@hilist2)=split('/',$hires{2});
	    (@hilist3)=split('/',$hires{3}); 
	    if($var{loc} == 3){@templist=@hilist3;} 
############### store info in strings and edit the strings
	   
#######change HiRes schedule 
	    if($date{lt} == $var{adddate})
	    {
		
		if($hires{$var{loc}}=~m/ARMY/)
		{
		    $nogo=1;
		    $dropok=0;
		    $addok=0;
		    push @reasons, "The Army has closed the base for that day";
		}
		if($hilist3[0] eq "NH" && $var{myname} ne "NH")
		{
		    $addok=0;
		    push @reasons, "No student help is needed on $var{adddate}";
                }
     
		if($var{act} eq "ADD")
		{
		    
		    for($l=1; $l<4;$l++)
		    {
			if($hires{$l}=~m/$var{myname}/)
			{
			    $addok=0;
			    push @reasons, "You are allready signed up at HiRes $l on $var{adddate}";
			}
		    }
		    
		    
		    
		    
		    if($addok)
		    {  
			if($var{myname}=~m/ARMY/)
			{
			    unshift @templist, $var{myname};
			}
			if($var{myname} eq "NH")
			{
			    @templist = "NH";
			}
		        if($var{myname}!=~m/ARMY/ && $var{myname} ne "NH")
			{
			    $templist[@templist]=$var{myname};
			}
			open(RECRD, "<../private/workfiles/schedhist");
			open(TMP, ">junk1");
			foreach(<RECRD>)
			{
			    chomp;
			    print TMP "$_\n";
			}
			print TMP "$var{adddate},$today,$var{myname},$var{act},$var{loc}\n";
			close(RECRD);
			close(TMP);
			system"cp junk1 ../private/workfiles/schedhist";
		    }
		}
		    
		if($var{act} eq "DROP")
		{
		    $diff=datediff($date{lt},$today);
		    
		    
		    #### reasons to not permit droppings ####
		    if($diff<6)
		    {
			
			#### enough escorts to cover foriegn nationals ######
			for($i=0;$i<@templist+1;$i++)
			{
			    if(!defined($citsigned{$cit{$templist[$i]}}))
			    {
				$citsigned{$cit{$templist[$i]}}=0;
			    }
			    $citsigned{$cit{$templist[$i]}}++;
			}
			if(($cit{$var{myname}} eq "E")and($citsigned{E}<2)and($citsigned{F}>0))
			{
			    $dropok=0;
			    push @reasons, "Not enough escorts signed up";
			}
			####### end enough escorts
			#if(@templist<3)
			#{
			#    $dropok=0;
			#    push @reasons, "There must be at least 2 people at a site";
			#}
		    }   
$dropok=1;#This is just temporary so we can loosen restrictions on HiRes3.
		    if($dropok)
		    {
			for($i=0;$i<@templist+1;$i++)
			{				
			    my $thisname = pop @templist;
			    if(uc $thisname ne $var{myname})
			    {
				unshift @templist, $thisname;
			    }
			    else
			    {
				open(RECRD, "<../private/workfiles/schedhist");
				open(TMP, ">junk1");
				foreach(<RECRD>)
				{
				    chomp;
				    print TMP "$_\n";
				}
				print TMP "$var{adddate},$today,$var{myname},$var{act},$var{loc}\n";
				close(RECRD);
				close(TMP);
				system"mv junk1 ../private/workfiles/schedhist";
			    }
			    
			}
		    }
		} ########## end drop
		
		
	    } ########### end $var{adddate} == $date 
	    if($var{loc} == 1){@hilist1=@templist;}
	    if($var{loc} == 2){@hilist2=@templist;}    
	    if($var{loc} == 3){@hilist3=@templist;}  

	
	

	
	    
############# print new strings to RUNTMP (the tmp/runs file)
	    $hil1=join('/',@hilist1);
	    $hil2=join('/',@hilist2);
	    $hil3=join('/',@hilist3); 
	    print RUNTMP "$date{lt}#$moon{lt}#$moon{ut}#$length#$jday#$hil1#$hil2#$hil3#$comm\n";
	}
	#########addsomething($hil3# after $hil2#) to the line above this--when I get the RUN files ready(the 8th '#' needs to be inserted into them all)}--done
	
	close(RUN);
	close(RUNTMP);
############ copy the tmp data to the "real" file
	print(`cat junk > ../private/runs/$var{whichrun}`);
    }
    
    print("</TR></TABLE>");
    print"</TABLE>";
###############################################
### unsucsesful adds and drops ################
###############################################
    
    if(!($everyone=~m/$var{myname}/))
    {
	$dropok=0;
	$addok=0;
        push @reasons, "$var{myname} is not on the usual suspects list. Please check spelling for acuracy.";
        #print"<TR><TD><h2><CENTER><a name=$var{target}><FONT color=ff0055>Do you know how to spell your name?<BR>You are not on the usual suspects list, $var{myname}.</FONT></Center></h2><BR><BR> </TD></TR>";
    }  

    if((defined($var{act}))and(($dropok==0)or($addok==0)))
    {
	print"<TABLE>";
	print"<TR><TD><h2><a name=$var{target}>Your attempt to $var{act} <FONT color=$color{$cit{$var{myname}}}>$var{myname}</FONT> on the date $var{adddate}<BR> was <FONT color=ff0055>UNSUCCESFULL </FONT>for the following reasons:</h2></TD></TR>";
	print"<TR><TD><h2>";
	foreach(@reasons)
	{
	    print" - $_<BR>";
	}
	print"</TR><TD>";
	
	print"</TABLE><TABLE>";
	print"<FORM method=POST ACTION=rules.pl>";
	print'<INPUT type=submit value="ADD/DROP rules">';
	print"</FORM>";
	print"</TABLE>";
    }



##################################################
###### decode the runs list file #################
##################################################

    
    print"<TABLE><CENTER><h1>HiRes $var{loc}</h1></CENTER>";
    print("<TR><TD>yyyymmdd </TD><TD> Week Day </TD><TD> Length </TD><TD></TD><TD>1st Runner ||</TD><TD>2nd Runner</TD>\n");
    print("</TD></TR>");
#print("</TABLE><TABLE>");
    $num=0;
    open(RUN, "<../private/runs/$var{whichrun}");    
    foreach(<RUN>)
    {
	$num++;
	($date{lt},$moon{lt},$moon{ut},$length,$jday,$hires1,$hires2,$hires3,$comm,@leftovers)=split /#/;
	($dw,$mnth,$dd,$yy,$hourmin,@rest)=split(' ',$moon{lt});
	($hour,$min)=split(':',$hourmin);
	if($hour<12)
	{
	    if($dw eq "Mon"){$dw="SUN";}
	    if($dw eq "Tue"){$dw="MON";}
	    if($dw eq "Wed"){$dw="TUE";}
	    if($dw eq "Thu"){$dw="WED";}
	    if($dw eq "Fri"){$dw="THU";}
	    if($dw eq "Sat"){$dw="FRI";}
	    if($dw eq "Sun"){$dw="SAT";}
	}
	(@hilist1)=split('/',$hires1);
	(@hilist2)=split('/',$hires2);
	(@hilist3)=split('/',$hires3);
	my($pruner1,$sruner1,@silly1)=split('/',$hires1);
	my($pruner2,$sruner2,@silly2)=split('/',$hires2);
	my($pruner3,$sruner3,@silly3)=split('/',$hires3);
	$others1=join(' ',@silly1);
	$others2=join(' ',@silly2);
	$others3=join(' ',@silly3);
	if($num % 10 == 1)
	{
	    $target=$date{lt};
	}

	$yy=substr $date{lt},0,4;
	$mm=substr $date{lt},4,2;
	$dd=substr $date{lt},6,2;

	print'<FORM method=GET ACTION="moon.pl#',"$yy$mm$dd",'">',"<INPUT type=hidden name=run value=$var{whichrun}>";
	print"<INPUT type=hidden name=day value=$yy$mm$dd>\n";
	print'<TR><TD width=100><A name="',"$yy$mm$dd",'">',"<INPUT type=submit value=$yy/$mm/$dd></A><BR></TD>";
	print"</FORM>";
#	print"<TD>$dw<BR><BR></TD><TD>$length<BR><BR></TD>";
        if($length>5.0)  {
        print"<TD>$dw<BR><BR></TD><TD><FONT size=4 color=33ff00>$length<BR><BR></FONT></TD>";
        }
        else  { 
                print"<TD>$dw<BR><BR></TD><TD>$length<BR><BR></TD>";
        }

	print'<FORM method=POST ACTION="signmeup.pl#',"$target",'"><TD>';
	$diff=datediff($date{lt},$today);
	if($length>3.0 || $diff <0)
	{
	    print"<INPUT type=hidden name=target value=$target>";
	    print'<INPUT type="text" name="myname" size="4">';
	    print'<INPUT type="submit" name="act" value="ADD">';
	}
	if($diff>=0)#originally this was if($diff>5)
	{
	    print'<INPUT type="submit" name="act" value="DROP">';
	    
	}
	elsif((($var{loc}==1)and(@hilist1>2)) or (($var{loc}==2)and(@hilist2>2)) or (($var{loc}==3)and(@hilist3>2)))
	{
	    if($diff>0)
	    { 
		print'<INPUT type="submit" name="act" value="DROP">';
	    }
	}
	print'<INPUT type="hidden" name="adddate" value="',$date{lt},'">';
	print'<INPUT type="hidden" name="whichrun" value="',$var{whichrun},'">';
	print'<INPUT type="hidden" name="loc" value="',$var{loc},'">';
	print'</TD></FORM>';

########### display HiRes 1
	if($var{loc}==1)
	{
	    for($i=0; $i<@hilist1; $i++)
	    {
		print "\n<TD width=130><a href=emplist.pl#$hilist1[$i]><FONT color=$color{$cit{uc $hilist1[$i]}}>$hilist1[$i]</FONT></a></TD>";
	    }
	}
############ display HiRes 2
	
	if($var{loc}==2)
	{
	    for($i=0; $i<@hilist2; $i++)
	    {
		print "\n<TD width=130><a href=emplist.pl#$hilist2[$i]><FONT color=$color{$cit{uc $hilist2[$i]}}>$hilist2[$i]</FONT></a></TD>";
	    }
	}

############ display HiRes 3 
	
	if($var{loc}==3)
	{
	    for($i=0; $i<@hilist3 && $i<2; $i++)
	    {
		if($hilist3[$i] eq "NH")
		{
		    print "\n<TD><FONT color=$color{F}>NO HELP NEEDED</FONT></TD>";
		}
	        else
		{
		    print "\n<TD><a href=emplist.pl#$hilist3[$i]><FONT color=$color{E}>$hilist3[$i]</FONT></a></TD>";
		}    
	    }
	}
    }


    close(RUN);
    print('</TABLE><TABLE><TR><TD><CENTER><a href="signmeup.pl">Go back</a>');
    print'<FORM method=GET ACTION="viewsched.pl">';
    print'<INPUT type="hidden" name="whichrun" value="',$var{whichrun},'">';
    print'<INPUT type="hidden" name="loc" value="',$var{loc},'">';
    print'If you have finished editing, please press ';
    print'<INPUT type="submit" value="Done">';
    print'</FORM>';
    print('</CENTER></TD></TR></TABLE>');
########### end the HTML doc ############################
    print('</BODY></HTML>');
}
