#!/usr/bin/perl
#  Copyright 2001-2026 Leslie Richardson

#  This file is part of Open Admin for Schools.


# entry box sizes for input
my $homeworklength = 20;
my $topiclength = 15;
my $maxBlankCounter = 6; # more than 6 blank periods, skip doing back lookups.
my $daylimit = 4; # number of school days to look forward or back.

my %lex = ('Not Assigned' => 'Not Assigned',
	   'Daybook' => 'Daybook',
	   'Main' => 'Main',
	   'Today is a non-cycle Day' => 'Today is a non-cycle Day',
	   'Day' => 'Day',
	   'Term' => 'Term',
	   'Homework Due' => 'Homework Due',
	   'Desc' => 'Desc',
	   'Update' => 'Update',
	   'Please Log In' => 'Please Log In',
	   'User Id' => 'User Id',
	   'Password' => 'Password',
	   'Not Found' => 'Not Found',
	   'Please check configuration file' => 'Please check configuration file',
	   'Error' => 'Error',
	   'Topic' => 'Unit',
	   'Category' => 'Strand',
	   'Period' => 'Period',
	   'Time' => 'Time',
	   'Track' => 'Track',
	   'Previous Week' => 'Previous Week',
	   'Next Week' => 'Next Week',
	   'Select' => 'Select',
	   'Date' => 'Date',
	   'Go' => 'Go',

	   'Cycle' => 'Cycle',
	   

	   );

my $self = 'dbook.pl';

use DBI;
use CGI;
use Time::JulianDay;
use Cwd;


my $q = CGI->new;
my %arr = $q->Vars; # Get passed values


my $prepath = q{../..};
if ( getcwd() =~ /ecgi/ ) { # we are in ecgi
    $prepath = q{..};
}

eval require "$prepath/etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}

# Get current dir so know what CSS to display and shift settings.
if ( getcwd() !~ /tcgi/ ) { # we are in NOT tcgi (native area)
    $tchcss = $css;
    $tchpage = $homepage;
}

if ( getcwd() =~ /ecgi/ ) { # we are in ecgi TA site
    $tchcss = $eacss;
    $tchpage = $eapage;
}


eval require "$prepath/lib/libschedule.pl";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}

print $q->header(-charset, $charset);

my $dsn = "DBI:$dbtype:dbname=$dbase";
$dbh = DBI->connect($dsn,$user,$password);



# Set limits for school year: startjd and endjd
my $schoolstart = $g_MTrackTerm{1}{1}{'start'}; #override global
my $startjd = julian_day( split('-',$schoolstart));
my $endjd = julian_day( split('-', $schoolend));

my (@tim, $year,$month,$day);
@tim = localtime(time);
$year = $tim[5] + 1900;
$month = $tim[4] + 1;
$day = $tim[3];

my $currjd = julian_day($year,$month,$day);
if ( $currjd < $startjd ) {
    $currjd = $startjd;
    ($year, $month, $day) = inverse_julian_day( $currjd );
    
} elsif ( $currjd > $endjd ) {
    $currjd = $endjd;
    ($year, $month, $day) = inverse_julian_day( $currjd );
}


my $userid = $ENV{'REMOTE_USER'};
my $sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");
$sth->execute( $userid );
if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
my ($lastname, $firstname) = $sth->fetchrow;


# Write Updates to Database.
if ( $arr{writeflag} ){  # update records.
    delete $arr{writeflag};
    updateRecords();
}


# load  periods field and default term for this user from staff record
my $sth = $dbh->prepare("select dbkperiods, dbkterm from staff where userid = ?");
$sth->execute( $userid );
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
my ($periods, $defaultterm) = $sth->fetchrow;
eval $periods;
if ( $@ ) {
    print $lex{Error}. " for Teacher Periods: $@<br>\n";
    exit;
}
my %periods12; # periods in 12 hours format;
foreach my $p ( sort keys %periods ) {
    $periods12{$p}{s} = conv24to12( $periods{$p}{s});
    $periods12{$p}{e} = conv24to12( $periods{$p}{e});
#    print qq{<div>$p - $periods12{$p}{s} / $periods12{$p}{e}</div>\n};
};



# Display Date Selections at top of the page.
my ($currdate,$currsdate, $mondayjd, $currjd, $dow );
if ( $arr{date} ) {

    # Generate a list from those dates.
    ($year,$month,$day) = split('-',$arr{date});
    
    $currjd = julian_day($year,$month,$day);
    $dow = day_of_week($currjd);
    $mondayjd = $currjd - ($dow-1);

    if ( $dow == 0 or $dow == 6 ) { # weekend, change to next monday;
	$nextmondayjd = $currjd - ($dow-1) + 7;
	$currjd = $nextmondayjd;
	($year,$month,$day) = inverse_julian_day( $currjd );
	$dow = day_of_week($currjd);
    }
    
    if (length($month) == 1){ $month = "0".$month;}
    if (length($day) == 1){ $day = "0".$day;}
    $currsdate = "$year$month$day"; 
    $currdate = "$year-$month-$day";

} else {
    @tim = localtime(time);
    $year = $tim[5] + 1900;
    $month = $tim[4] + 1;
    $day = $tim[3];

    $currjd = julian_day($year,$month,$day);
    $dow = day_of_week($currjd); # for consumption below also; subj att entry
    $mondayjd = $currjd - ($tim[6]-1); #This will now give Monday of that week.
    if (length($month) == 1){ $month = "0".$month;}
    if (length($day) == 1){ $day = "0".$day;}
    $currdate = "$year-$month-$day";
    $currsdate = "$year$month$day";

} 



# ================= START of TERMS - to be removed; just use defaultterm.
# Figure out the current term for each track.
my ($currterm, %terms, %grade2terms );
my %myterms; # for this staff member.

if ( not $defaultterm ) { # from staff record

    foreach my $trk ( sort {$a <=> $b} keys %g_MTrackTerm ) {
	for my $trm ( sort {$a <=> $b} keys %{ $g_MTrackTerm{$trk}} ) {

	    my $startjd = julian_day( split('-', $g_MTrackTerm{$trk}{$trm}{start}) );
	    my $endjd =  julian_day( split('-', $g_MTrackTerm{$trk}{$trm}{end}) );
	    if ( $currjd >= $startjd and $currjd <= $endjd ) { # we have the term.
		$terms{$trk} = $trm;
		last; # done with this track.
	    }
	}
    }

    # Testing: foreach my $key ( sort keys %terms ) { print "K:$key V:$terms{$key}<br>\n"; }

    foreach my $gr ( keys %g_MTrackTermType ) {
	my $track = $g_MTrackTermType{$gr};
	$grade2terms{$gr} = $terms{$track};
    }


    # Get the grade(s) of this staff member (into %myterms )
    $sth = $dbh->prepare("select field_value from staff as s, staff_multi as sm
    	 where s.userid = sm.userid and s.userid = ? and field_name = 'grade'");
    $sth->execute( $userid );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $grade = $sth->fetchrow ) {
	my $term = $grade2terms{$grade};
	$myterms{$grade} = $term;
    }

    if ( not %myterms ) { # nothing in staff_multi.... check grades from courses.
	my $sth = $dbh->prepare("select distinct grade from subject where teacher = ?");
	$sth->execute( $userid );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $grade = $sth->fetchrow ) {
	    my $term = $grade2terms{$grade};
	    $myterms{$grade} = $term;
	}
    }
    
    # Testing: foreach my $key ( sort keys %grade2terms ) { print "Grade:$key Term:$grade2terms{$key}<br>\n"; }
    
} else { # we have a default term
    $terms{1} = $defaultterm;
    $currterm = $defaultterm;
    # grade2term not possible, unless we just use default term for all grades;
}
#================= END of TERMs section - to be removed, IMO.



# Setup Array and Hash to hold Dates and DOW Dates (Multi-Day Method)
my ($ddref, $dayref) = mkDateData($mondayjd,$weekcount);
my @days = @$dayref;
my %datedata = %$ddref;
    

# ========= Non-School Days for some classrooms ==========
# Push Teacher Rooms into array
$sth = $dbh->prepare("select field_value from staff as s, staff_multi as sm
  where s.userid = sm.userid and s.userid = ? and field_name = 'homeroom'");
$sth->execute( $userid );
if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
while ( my $homeroom = $sth->fetchrow ) {
    push @hroom, $homeroom;
}


# Load non-school days, if any for these homerooms.
my %nonschoolday;
my $sth = $dbh->prepare("select date, period from dates_homeroom where homeroom = ?");
foreach my $hr ( @hroom ) {
    $sth->execute( $hr );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    while ( my ($date,$period) = $sth->fetchrow ) {
	$nonschoolday{$hr}{$date}{$period} = 1;
#  print "HR:$hr Date:$date Period:$period<br>\n";
    }
}
#======== end of nonschool days section



# Heading of Document
print qq{$doctype\n<html><head><title>$lex{Daybook}</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" type="text/css" media="screen">\n};

# Setup for Calendar popup.
print qq{<link rel="stylesheet" type="text/css" media="all" href="/js/calendar-blue.css" title="blue">\n};
print qq{<script type="text/javascript" src="/js/calendar.js"></script>\n};
print qq{<script type="text/javascript" src="/js/lang/calendar-en.js"></script>\n};
print qq{<script type="text/javascript" src="/js/calendar-setup.js"></script>\n};

print qq{$chartype\n};

print qq{<script language="javascript" type="text/javascript">
function win1() {
  winName=window.open('timetableset.pl',
  'ScheduleWindow','height=700,width=1000,screenX=50,screenY=50');
  winName.focus();
}

function win2() {
  winName=window.open('setDefaultTerm.pl',
  'ScheduleWindow','height=300,width=500,screenX=50,screenY=50');
  winName.focus();
}

window.onbeforeunload = function() {
  return true;
}
</script>\n};
# winName=window.open('../tchschedview.pl?userid=$userid&term=$term',

print qq{</head><body>\n};


print qq{<div style="display:inline;float:left;padding:0.5em;">\n};
print qq{[ <a href="$tchpage">$lex{Main}</a> | \n};
print qq{<a href="javascript:win1()">myTimetable</a> ]\n};

print qq{<span style="font-weight:bold;font-size:120%;margin-left:0.5em;">Day Book</span>\n};

print qq{<span style="margin:0.4em;font-weight:bold;">$firstname $lastname</span>\n};
print qq{</div>\n};



# Weekly Date Calcs - Previous Week / Next Week.
my $prevjd = $mondayjd - 7;
if ( $prevjd < $startjd ){ $prevjd = $startjd;}
my ($prevyear, $prevmonth, $prevday) = inverse_julian_day($prevjd);
my $prevdate = "$prevyear-$prevmonth-$prevday";


print qq{<div style="display:inline;">\n};
print qq{<form action="$self" method="post" style="display:inline;">\n};
print qq{<input type="hidden" name="date" value="$prevdate">\n};
print qq{<input type="hidden" name="page" value="1">\n};
print qq{<input type="submit" value="<= $lex{'Previous Week'}"></form>\n};

my $nextjd = $mondayjd + 7; 
if ($nextjd > $endjd){ $nextjd = $endjd;}
my ($nextyear, $nextmonth, $nextday) = inverse_julian_day($nextjd);
my $nextdate = "$nextyear-$nextmonth-$nextday";

print qq{<form action="$self" method="post" style="display:inline;padding:0.5em;">\n};
print qq{<input type="hidden" name="date" value="$nextdate">\n};
print qq{<input type="hidden" name="page" value="1">\n};
print qq{<input type="submit" value="$lex{'Next Week'} =>"></form>\n\n};


# Pop Up Calendar Date Selector
print qq{<form action="$self" method="post" };
print qq{style="display:inline;background-color:yellow;padding:0.3em 0.5em;border:1px solid gray;">\n};
print qq{<input type="hidden" name="page" value="1">\n};
print qq{<button type="reset" id="date_trigger">$lex{Select} $lex{Date}</button>\n};
print qq{<input type="text" name="date" id="date" size="10">\n};
print qq{<input type="submit" value="$lex{Go}">\n};
print qq{</form><br>\n\n};


my $sth = $dbh->prepare("select id, dayfraction from dates where date = ?");

for my $i ( 1..5 ) { # five days of this week.

    my ($wkyear, $wkmonth, $wkday) = inverse_julian_day($mondayjd);
    my $dow = day_of_week($mondayjd) + 1;
    my $tmpdate = qq{$wkyear-$wkmonth-$wkday};

    # Check for date being fully closed or not (ie ALL DAy).
    # Skip if closed all day.
    $sth->execute( $tmpdate );
    my ( $id, $dayfrac ) = $sth->fetchrow;
    # Logic: Skip for attendance if closed all day.
    if ( $dayfrac > 0.99 ) { # ie. only 1.000, closed all day, skip
	$mondayjd++;
	next;
    }

    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="date" value="$tmpdate">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="submit" value="$dow[$dow] $month[$wkmonth] $wkday"></form>\n};
    $mondayjd++;
}
print qq{</div>\n};


if ( not %periods ) {
    print qq{<h3>No Periods Set!\n};

    print qq{<form action="./confStaffPeriods.pl" method="post" style="display:inline;">\n };
    print qq{<input type="submit" value="Set Your Periods">\n};
    print qq{</form></h3>\n};

    print qq{</body></html>\n};
    exit;
}


# Find DayInCycle
my $dayInCycle = findDayInCycle($currdate, $dbh);


print qq{<br clear="left"><div style="float:left;padding:0.4em;">\n};
my $localdow = $dow + 1;
print qq{<span style="font-weight:bold;font-size:120%;">$dow[$localdow], $currdate</span>\n};
print qq{<span style="font-weight:bold;padding:1em;">$lex{Cycle} $lex{Day} $dayInCycle \n};
print qq{$lex{Term} $defaultterm</span>\n};
print qq{<span style="font-size:80%;font-weight:normal;">};
print qq{[ <a href="javascript:win2()" title="Reset Default Term">Reset myTerm</a> ]</span>\n};
print qq{</div>\n};

print qq{<div style="clear:left;"></div>\n};


# Halt if dayInCycle undefined. (ie. due to being a non-cycle day) ... just above
if ( not $dayInCycle ) {
    print qq{<h3>$lex{'Today is a non-cycle Day'}</h3>\n};
    print qq{</body></html>\n};
    exit;
}


my %ttb; # timetable
 
# Get the Teachers Timetable data from dbktimetable
my $sth = $dbh->prepare("select * from dbktimetable where userid = ? and term = ? and day = ?");
$sth->execute( $userid, $defaultterm, $dayInCycle );
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
while ( my $ref = $sth->fetchrow_hashref ) {
    my %r = %$ref;
    $ttb{ $r{period} }{ $r{crsact} } = 1; # may be more than one.
}  # courseact must be decoded later; either subjsec of course or id of the activity


#======== Form Start ================
# Start the main form.
print qq{<!--  Main Form Entry Starts Here!  -->\n};
print qq{<form action="$self" method="post">\n};

print qq{<input type="submit" value="$lex{Update}" style="font-size:85%;margin:0.2em;">\n};
print qq{<input type="hidden" name="date" value="$currdate">\n};
print qq{<input type="hidden" name="writeflag" value="1">\n};


# Setup Selects for use inside loop.
my $sth2 = $dbh->prepare("select description from subject where subjsec = ?");

my $sth3 = $dbh->prepare("select distinct topic from dbkdata 
 where subjsec = ? and topic != '' order by date desc");

my $sth4 = $dbh->prepare("select distinct category from dbkdata 
 where subjsec = ? and category != '' order by category");

my $sth5 = $dbh->prepare("select * from dbkdata 
 where userid = ? and date = ? and period = ?");

# Activity values
my $sth6 = $dbh->prepare("select * from dbkactivity where id = ?");

my ( %course, %activity );
my $bgcolor;

# Look for dbkdata for date, period
my $sth = $dbh->prepare("select * from dbkdata where userid = ? and date = ? and period = ?");



#========= Periods Loop ================
for my $period ( sort keys %periods ){
    
    if ( $bgcolor eq '#CCC' ) { 
	$bgcolor = '#CCF';
    } else {
	$bgcolor = '#CCC';
    }

    print qq{\n\n<div style="background-color:$bgcolor;border:2px solid black;margin:0.4em;};
    print qq{width:100ch;padding:0.5em;">\n};
    
    # Period# and Time.
    print qq{<div style="padding:0.4em;">$lex{Period} <b>$period</b> };
    print qq{$lex{Time}: <b>$periods12{$period}{s}-$periods12{$period}{e}</b></div>\n};

    
    # Load any dbkdata for this date and period
    my (%currdata, $notes); # this period

    # Load data from dbkdata table.
    $sth->execute( $userid, $currdate, $period );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;

#	print qq{<div><b>Loaded</b><br>\n};
#	foreach my $key ( sort keys %r ) {
#	    if ( $r{$key} ) {
#		print "K:$key VAL:$r{$key}<br>\n";
#	    }
#	}
	
	$currdata{ $r{crsact} } = $ref; # needed to check ttb after displaying these saved record(s).

	my $test = $r{crsact};
	
	if ( $test eq 'notes') { # skip for now
	    $notes = $r{description};
	    next;
	}

	if ( $test =~ m/^\d+$/ ) { # we have  an activity to get it's info

	    # Load Activity Record
	    $sth6->execute( $r{crsact} );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my $ref = $sth6->fetchrow_hashref;
	    my %a = %$ref; # A for activity
	    
	    #  print "Activity", %a, "<br>\n";
	    #foreach my $key ( sort keys %a ) {
	    #  print qq{<div>K:$key VAL:$a{$key}</div>\n};
	    #}

	    print qq{<div style="padding:0.4em;" title="$a{description}"><b>Activity</b> $a{topic}&#9405; };
	    print qq{Topic: <input type="text" name="$period:$r{crsact}:topic" style="width:60ch;" };
	    print qq{value="$r{topic}"></div>\n};

	    print qq{<div><textarea name="$period:$r{crsact}:description" rows="4" cols="120">};
	    print qq{$r{description}</textarea></div>\n};
	
	} else { # a course
	    
	    # Load Course Description
	    $sth2->execute( $r{crsact} );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my $desc = $sth2->fetchrow;
	    
	    print qq{<div style="padding:0.4em;"><span style="font-size:120%;font-weight:bold;">};
	    print qq{$desc</span>\n};
	    # TOPIC
	    print qq{Topic: <input type="text" name="$period:$r{crsact}:topic" style="width:60ch;" };
	    print qq{value="$r{topic}"></div>\n};
	    # DESC
	    print qq{<div><textarea name="$period:$r{crsact}:description" rows="4" cols="120">$r{description}};
	    print qq{</textarea></div>\n};

	}

    } # end of loading loop
    

=head    
	print qq{<b>Curr Data</b><br>\n};
	foreach my $key ( sort keys %currdata ) {
	    if ( $currdata{$key} ) {
		print "K:$key VAL:$currdata{$key}<br>\n";
	    }
	}
=cut    

    
    # Now check the timetable (%ttb) for any assigned activities/courses missed.
    my %test =  %{ $ttb{$period}};
    
    # Note: any ca (crsact) values for activities will have a leading
    # ACTIV, so will not match with data from currdate (which will
    # only be record id of the activity.

#    print "TEST:", %test, "<br>\n";
    
    foreach my $ca ( keys %test ) {  # $ca is the course/activity for this period
	
	$ca =~ s/ACTIV-//; # strip ACTIV

#	print qq{<div>Timetable Testing Section: CA:$ca</div>\n};
	
	if ( not $currdata{$ca} ) { # we have to add this also, since it's scheduled

	    if ( $ca =~ m/^\d+$/ ) { # digit only, record id of an activity
		# Load Activity Record
		$sth6->execute( $ca );
		if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		my $ref = $sth6->fetchrow_hashref;
		my %a = %$ref;
		
		print qq{<div style="padding:0.4em;" title="$a{description}"><b>Activity</b> $a{topic}&#9405; };
		print qq{Topic: <input type="text" name="$period:$a{id}:topic" style="width:60ch;"></div>\n};
		print qq{<div><textarea name="$period:$a{id}:description" rows="4" cols="120">};
		print qq{</textarea></div>\n};

	    } else { # must be a course to check. $ca will be subjsec. Notes are not present in timetable
		# Load Course Description
		$sth2->execute( $ca );
		if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		my $desc = $sth2->fetchrow;
		
		print qq{<div style="padding:0.4em;"><span style="font-size:120%;font-weight:bold;">};
		print qq{$desc</span>\n};
		print qq{Topic: <input type="text" name="$period:$ca:topic" style="width:60ch;">};
		print qq{</div>\n};
		print qq{<div><textarea name="$period:$ca:description" rows="4" cols="120">};
		print qq{</textarea></div>\n};

	    } 
	
	}
    }
    

    # Finally a default NOTES area (without any ttb or possibly saved
    # data) (variable $notes and $noteid from above)
    
    print qq{<div>Other Notes</div>\n};
    print qq{<div><textarea name="$period:notes:description" rows="2" cols="120">$notes};
    print qq{</textarea></div>\n};
    
    print qq{</div>\n};
    
} # end of periods loop

print qq{<input type="submit" value="$lex{Update}" style="font-size:85%;margin:0.2em;">\n};
print qq{</form>\n};

print qq{<script type="text/javascript">
 Calendar.setup({
   inputField  : "date",
   ifFormat    : "%Y-%m-%d",
   button      : "date_trigger",
   singleClick : false,
   step : 1
 });
 </script>\n};


print qq{</body></html>\n};



#----------------
sub updateRecords {
#----------------
    
    my %rec = %arr;
    # Don't mess with %arr hash since this is passed through to display functions.

 #   foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }

    
    my $date = $rec{date};
    delete $rec{date};
    # print "Date:$date<br>\n";

    # Create Data hash, based on period and subjsec
    foreach my $key ( keys %rec ){
	my ($period, $subjsec, $field) = split(':',$key);

	if ( not $rec{$key} ) { next; } # no data, skip
	
	$subjsec =~ s/\s+//g; # strip spaces, just in case.

	$data{"$period:$subjsec"}{$field}= $rec{$key};
     
    }


=head    
    # Test Data;
    foreach my $key ( sort keys %data ) {
	my ($period,$subjsec) = split(':',$key);
	print qq{Period:$period Subjsec:$subjsec<br>\n};
	my %r = %{ $data{$key} }; # now do topic or description
	foreach my $key ( sort keys %r ) {
	    print qq{K:$key V:$r{$key}<br>\n};
	}
	print "<br>\n";
    }
=cut

#    exit;
    

    # Check for existing record
    my $sth = $dbh->prepare("select id from dbkdata 
      where crsact= ? and userid = ? and period = ? and date = ?"); 
    
    # Update the record (only topic and description so far
    my $sth1 = $dbh->prepare("update dbkdata set 
       topic = ?, description = ? where id = ?");   #, homework = ?, hwdate = ?, category = ?  where id = ?"); 

    # Insert a new record
    my $sth2 = $dbh->prepare("insert into dbkdata (userid, date, crsact, period, topic, 
       description )  values (?,?,?,?,?,?)"); # , homework, hwdate, category - not yet.
    

    # Now update it, loop through data hash.
    foreach my $key ( keys %data ) {
	my ($period,$crsact) = split(':',$key);
#	print "K:$key Period:$period CRSACT:$crsact<br>\n";
	
	# Check for existing record
	$sth->execute( $crsact, $userid, $period, $date );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $id = $sth->fetchrow;

	my %r = %{ $data{$key} }; # loop over fields: topic, description so far.

        if ( $id ) { # update the existing record
	    $sth1->execute( $r{topic}, $r{description}, $id ); #  $r{homework}, $r{hwdate}, $r{category}
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	} else { # add a record
	    
	    if ( $r{description} or $r{topic} ) {
#		print qq{<div>Adding Record</div>\n};		
		$sth2->execute( $userid, $date, $crsact, $period, $r{topic}, $r{description} );
		# REMOVED for now $r{homework}, $r{hwdate}, $r{category}
		if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    }
	}
    }

    return;
    
} # End of updateRecords



#-----------
sub findTerm {
#-----------

    my $date = shift; # Passed Date. 
    my $jd = julian_day( split('-', $date));

#    print qq{Passed Date:$date<br>\n};
    
    my %terms;

    foreach my $trk ( sort keys %g_MTrackTerm ) {
	foreach my $trm ( keys %{ $g_MTrackTerm{$trk} } ) {

#	    print qq{Track:$trk - Term:$trm<br>};
	    my $ref = $g_MTrackTerm{$trk}{$trm};

	    my $startjd = julian_day( split('-', $ref->{'start'}) );
	    my $endjd = julian_day( split('-', $ref->{'end'}) );

	    if ( $jd >= $startjd and $jd <= $endjd ) {
#		print qq{Match: TRK:$trk TRM:$trm<br>\n};
		$terms{ $trm } = $trk;
	    }

#	    print qq{Start: $ref->{'start'} - $startjd<br>\n};
#	    print qq{End: $ref->{'end'} - $endjd<br>\n};

	}
    }


    my @temp = keys %terms;
    return @temp;


} # End of findTerm




#-------------
sub mkDateData {
#-------------

    my ($jd, $weeks) = @_;
    my (%datedata, @days);
    
    # Build an array of ISO dates (YYYY-MM-DD) and a hash using them
    # as keys to hash values of 'Mon Jan 6' format.
    # If one week, then just 5 values, if two wk then 10, etc.
    my $counter = 7;
    if ( $weeks == 2 ) { $counter = 14; };

    
    for ( 1..$counter ){
	my ($yr,$mon,$day) = inverse_julian_day($jd);
	if ( length( $mon ) == 1 ) { $mon = '0'. $mon; }
	if ( length( $day ) == 1 ) { $day = '0'. $day; }
	
	my $dow = day_of_week($jd) + 1;
	if ( $dow == 1 or $dow == 7 ) {  # dow function returns 0 and 6
	    $jd++;
	    next; 
	} # skip Saturday, Sunday.
	my $date = qq{$yr-$mon-$day};
	    
	# Check if the school is closed.
	my $sth = $dbh->prepare("select id, dayfraction from dates where date = ?");
	$sth->execute( $date );
	my ( $id, $dayfrac ) = $sth->fetchrow;
	if ( $dayfrac > 0.99 ) {
	    $jd++;
	    next; 
	} # skip if closed all day
	    
	push @days, $date;
	$datedata{"$yr-$mon-$day"} = qq{$s_dow[$dow], $s_month[$mon] $day};
	$jd++;
    }

    # print "DAYS:", @days, "<br>\n";

    return \%datedata, \@days;
    
} # end of mkDateData



#-------------
sub conv24to12 {  # also strips seconds now
#-------------

    my $time = shift;
    if ( not $time ) { return }
    my ($hr, $min, $sec ) = split(':', $time);
    my $ampm = 'AM';
    if ( $hr == 12 ) { $ampm = 'PM'; }
    if ( $hr == 0 ) { $hr = 12; };

    if ( $hr > 12 ) { 
	$hr -= 12;
	$ampm = 'PM';
    }

    return qq{$hr:$min $ampm};

}
