#!/usr/bin/perl -w
#routine to read in flat file and print out to HTML

use CGI;
use Database;
use File::stat;
use Time::localtime;

my $q = new CGI;
my $version="1.0"; 
my $class = $q->cookie('class');
my $id = $q->cookie('id');

if(($id ne "" and $class ne "")) {
    my $datadir = "/home/www/docs/physics/data/";
    my $filename = "$datadir/$class.$id";
    my $student = Database::open_student($filename);
    $name = $student->{info}{name};
    $email = $student->{info}{email};

    $statusdir = "/home/www/docs/physics/data/status/";
    $statusfile = "$statusdir$class.$id.status"; #use perl dump.pl ../data/Phys1001UMC2000Fall.1442034.status4 to view
    @steparray = ();
    $nsteps=40;                                               #change if increased
    if(!-e $statusfile){                                      #if non-existent, open new file
    $student = Database::open_student($statusfile);           #open new statusfile
    $student->{data}{magic} = $statusfile;                     #write filename to statusfile
    for(my $j = 1; $j <= $nsteps; $j++) {push @steparray, -1;};#init with -1 (undone)
    push @{$student->{data}{steps}}, @steparray;              #push entire array into .status
    $student->{info}{name} = $name;
    $student->{info}{id} = $id;
    $student->{info}{email} = $email;
    Database::save_student($statusfile, $student);            #save using Database.pm
    }else{                                                    #grab step array data
    $student = Database::open_student($statusfile);

    my $step=0;
    if ($q->param('update')){$step = $q->param('update')};
#   if ($step == 0){#not a number, thus do nothing }else{}
    if ($step != 0){
    $student->{data}{steps}[$step]=-1*$student->{data}{steps}[$step];          #toggle -1, 1
    Database::save_student($statusfile, $student);}
    foreach(@{$student->{data}{steps}}){ push @steparray, $_ ;};
  }
}

#my $courseno="1012";
#if($course ne ""){ $courseno=$course; }
#my $ccourse="PHYSICS ".$courseno;

$defaultlink="/physics/1001/";
$subclass = substr($class,0,8);
if($subclass eq "Phys1012"){$defaultlink="/physics/1012/"};
if($subclass eq ""){$subclass="Set/reset cookie";$defaultlink="login.pl?state=Newuser"};

print $q->header;
&header;

my $datafile = "/home/www/data/phys1012.dat"; #use alias to phys1012_spring01.dat
open(LESSONS, $datafile) or die "Error opening datafile."; 

my @lessons = ();
my $ia = 1;
my $ipush = 0;
while(not eof LESSONS) {
my $article = "";
my $iline;
my $beginning;

while(<LESSONS>) { 
        if (/^\#/) {
        $ia++;
        next;
      }
        $ipush++;
        push @lessons, $_;                    
    }
}

chomp @lessons; #remove trailing spaces from each element of lessons array        
close (LESSONS) || die "couldn't close lessons file:  $!";

my $bw = 0;
my $print = 0;
if ($q->param('print')){$print = $q->param('print');}
if ($print>0){$bw=1};

my $font = 0;
if ($q->param('font')){$font = $q->param('font');}

my $fs = "+0";
if ($font<0){$fs="+0";}
if ($font>5){$fs="+5";}
if ($font>0 & $font<6){$fs="+".$font;};

my $color = "";

$i=0;
foreach(@lessons){
  my $nentries=5;
  my $nep1=$nentries+1;
  my $j=$i*$nentries;
  my $sum=$ia-$i-1;
  my $url="/physics/1001/ntc/";
  my $tablewidth=720;
  my $temp="#dddddd";

  my @tw = ("8%","12%","50%","10%","10%","10%");
  if ($i<1) {
    print "<table width=\"$tablewidth\" border=$bw cellpadding=\"3\">
<tr><th colspan=$nep1 BGCOLOR=\"white\"><h3><font color=\"black\"><a href=\"/physics/1012/lessons/howtouse.html\" onClick=\"window.open('','howto','height=250,width=600,scrollbars=yes')\" target=\"howto\"  ONMOUSEOVER=\"this._tip='See an explanation on how to use this guide by following this link'\">A STEP BY STEP GUIDE</a> FOR ELEMENTARY PHYSICS (<a href=\"$defaultlink\">$subclass</a>) <br><font size=\"-1\">Move the mouse cursor over a column heading for instructions.</font></th></tr>
<tr><td bgcolor=\"$temp\" align=\"center\" width=\"$tw[0]\"><A HREF=\"/physics/cgi-bin/lessongrid.pl\" ONMOUSEOVER=\"this._tip='Follow these steps sequentially to complete the course; select the checkbox to toggle and save your status.'\">STEP</a></td><td align=\"right\" bgcolor=\"$temp\" width=\"$tw[1]\"><A HREF=\"/physics/cgi-bin/lessongrid.pl\" ONMOUSEOVER=\"this._tip='Select the Lesson # to review the lesson summary.'\">LESSON #</td><td align=\"left\" bgcolor=\"$temp\" width=\"$tw[2]\"><A HREF=\"/physics/cgi-bin/lessongrid.pl\" ONMOUSEOVER=\"this._tip='Click on TITLE to download the lesson plan as a PDF<SUP>*</SUP> File'\">LESSON TITLE &nbsp;</A></td><td align=\"center\" bgcolor=\"$temp\" width=\"$tw[3]\"><A HREF=\"/physics/cgi-bin/lessongrid.pl\" ONMOUSEOVER=\"this._tip='Follow the P- link to the computer prelesson exercises, while any L-links will take you to ancilliary pages related to the lesson or lab, and A-links for HTML conversion for accessibility.'\">LINKS</a></td><td bgcolor=\"$temp\" align=\"center\" width=\"$tw[4]\"><A HREF=\"/physics/cgi-bin/lessongrid.pl\" ONMOUSEOVER=\"this._tip='Lesson plans and laboratory worksheets were posted or last updated on these days.'\">POSTED</A></td><td bgcolor=\"$temp\" align=\"center\" width=\"$tw[5]\"><A HREF=\"/physics/cgi-bin/lessongrid.pl\" ONMOUSEOVER=\"this._tip='You should have the associated work done by these reference dates.'\">TARGET</a></td></tr>\n";

#  print "<tr><td align=center>\n";
#  foreach(@tw){print "$_</td><td align=center>";}
#  print "</td></tr>\n";
}

  if($color eq "#eeeeee") {$color = "#dddddd";} else {$color = "#eeeeee";}

  my $urlroot="http://ray.crk.umn.edu/";
  my $istep = $i+1;

  my $text = $lessons[$j+0];
  chop $text;
  my $preplink = "/physics/cgi-bin/login.pl";
  my $prepflag = "&nbsp;";
  my $summaryflag = "&nbsp;";
  my $summarylink = "/physics/cgi-bin/lessongrid.pl";
  my $popup = "false";
  my $l1 = "";
  my $l2 = "";

  if ($text=~ m/^Lesson/){
    $prepflag="P"; 
#$summary="SUMMARY";
    my ($l1,$l2)=split(' ',$text);          
    $summarylink="/physics/1012/lessons/summary$l2.html";
    $popup="true";
  }

  my $accessibilityroot="http://access.adobe.com/perl/convertPDF.pl?url=";
  my $accessibilityflag="&nbsp;";
  my $accessibilitylink="&nbsp;";
  if (($text=~ m/^Lesson/) or ($text=~m/^Lab/)){$accessibilityflag="A";}
  my $statusflag="&nbsp";
  my $statuslink="/physics/cgi-bin/lessongrid.pl";
  my $lessonlink=$lessons[$j+2];
  if ($text=~ m/^Exam/){$lessonlink=""};
  my $extra=$lessons[$j+3];
  my $extraflag="L";
  if ($extra=~ m/nbsp/){$extraflag="&nbsp;"};

#check whereabouts of file e.g. /physics/1012/lessons/lesson1.pdf
  my $file_root = "/home/www/docs";
  my $check_file = $file_root.$lessons[$j+2];
  my $timestamp = "&nbsp;";
#chomp $check_file;
  if (-e $check_file){
    $posted_time = ctime(stat($check_file)->mtime); 
#$timestamp=substr($posted_time,0,-13).substr($posted_time,11,5); 
#includes time stamp, see 235 Core Language
    $timestamp=substr($posted_time,0,-13);
  }
#print "$timestamp\n";
  my $imagedir = "/physics/images/";
  my $checkmark = $imagedir."check.gif"; 
  my $xmark = $imagedir."x.gif";
  my $mark = $xmark;
  my $stp = $steparray[$istep];
  $mark = $checkmark if ($stp && $stp > 0);

  print "<tr><td bgcolor=\"$color\" align=\"right\"><font size=$fs>$istep &nbsp;&nbsp; <a href=\"lessongrid.pl?update=$istep\"><img border=\"0\" src=\"$mark\" alt=\"Select CheckBox to Save Status\"></a> </td>";

  if ($popup eq "true"){
    print <<"E1";
    <td bgcolor="$color" align="right"><a href="$summarylink" onClick="window.open('','summary','height=250,width=600,scrollbars=yes')" target="summary"><font size=\"$fs\">$lessons[$j+0]</a></td>
E1
}else{
  print "<td bgcolor=\"$color\" align=\"right\"><font size=\"$fs\">$lessons[$j+0]</td>";
}
  $accessibilitylink = "&nbsp;";
#if file has been posted...
  if (-e $check_file){
    print "<td bgcolor=\"$color\" align=\"left\"><a href=\"$lessonlink\"><font size=\"$fs\">$lessons[$j+1]</a></td>";
    $accessibilitylink = $accessibilityroot."http://ray.crk.umn.edu".$lessonlink;
  }else{
    print "<td bgcolor=\"$color\" align=\"left\"><font size=\"$fs\">$lessons[$j+1]</td>\n";
   $accessibilityflag="&nbsp;";
}

  print <<"ENT2";
<td bgcolor="$color" align="center"><font size="$fs"><a href="$preplink">$prepflag</a> &nbsp; <a href="$extra">$extraflag</a><a href="$statuslink">$statusflag</a> <a href="$accessibilitylink">$accessibilityflag</a></td>
<td bgcolor="$color" align="center"><font size="$fs">$timestamp</td>
ENT2

#my $targetflag = "&nbsp;";
  my $targetflag = $lessons[$j+4];
  if ($subclass eq "Phys1012"){$targetflag=$lessons[$j+4]};
  print "<td bgcolor=\"$color\" align=\"center\"><font size=\"$fs\">$targetflag</td></tr>\n";

  $i++;
  last if($i+1==$ia);
}

print "</table>\n";
print <<"HTML1";
<p><SUP>*</SUP><a href="http://www.adobe.com/products/acrobat/readstep2.html" ONMOUSEOVER="this._tip='Use this link to grab the latest version of Adobe Acrobat Reader'">Get Adobe Acrobat Reader (if it is not loaded on your machine).</a> or <a href="http://access.adobe.com/">view access information for the visually disabled.</br><hr>
<font size="-2">URL is <a href="http://ray.crk.umn.edu/physics/cgi-bin/lessongrid.pl">http://ray.crk.umn.edu/physics/cgi-bin/lessongrid.pl</a> &nbsp; [<a href="/physics/cgi-bin/lessongrid.pl?print=1">printable version</a>] &nbsp; [<a href="/physics/cgi-bin/lessongrid.pl?font=1">larger font version</a>]
<br>General comments to <a href="mailto:demuth\@umn.edu">D. DeMuth</a>  &nbsp; &nbsp; <p>
</font>

<DIV ID=tipBox>
</DIV>
HTML1

#if ($name ne "") {
#print "<font size=\"-1\">\n";
#print "id is $id, name is $name, email is $email, class is $subclass\n";
##print "<br>statusfile is $statusfile, tmp1=$tmp1, tmp2=$tmp2\n";
#print "</font>\n";
#}

print "</BODY><BR></HTML>\n";

1;

############################
sub header {
#script src="/physics/cgi-bin/4script.js"></script>  

print <<"HTMLheader";
<html>
  <head>
    <title>STEP BY STEP GUIDE FOR ELEMENTARY PHYSICS</title> 
<style type="text/css"><!--A {text-decoration: none} --></style> 
  </head>


<STYLE>
  <!--
  #tipBox {position: absolute; width: 550px; z-index: 100;border: 1pt black solid; background: yellow; visibility: hidden}
  -->
</STYLE>


<SCRIPT language=javascript> 
  <!-- 
  /*  Your are permitted to reuse this code as long as the following copyright 
      notice is not removed: 
 
      This HTML tip handling is copyright 1998 by insideDHTML.com, LLC. More information about this 
      code can be found at Inside Dynamic HTML: HTTP://www.insideDHTML.com 
  */ 
 
 
  // Support for all collection 
  var allSupport = document.all!=null 
 
  function setupEventObject(e) { 
    // Map NS event object to IEs 
    if (e==null) return // IE returns 
    window.event = e 
    window.event.fromElement = e.target 
    window.event.toElement = e.target 
    window.event.srcElement = e.target 
    window.event.x = e.x 
    window.event.y = e.y 
    // Route the event to the original element 
    // Necessary to make sure _tip is set. 
    window.event.srcElement.handleEvent(e); 
  } 
 
 
  function checkName(src) { 
    // Look for tooltip in IE 
    while ((src!=null) && (src._tip==null)) 
      src = src.parentElement 
    return src 
  } 
 
  function getElement(elName) { 
    // Get an element from its ID 
    if (allSupport) 
      return document.all[elName] 
    else 
      return document.layers[elName] 
  } 
 
  function writeContents(el, tip) { 
    // Replace the contents of the tooltip 
    if (allSupport) 
      el.innerHTML = tip 
    else { 
      // In NS, insert a table to work around 
      // stylesheet rendering bug. 
      // NS fails to apply style sheets when writing 
      // contents into a positioned element. 
      el.document.open() 
      el.document.write("<TABLE WIDTH=200 BORDER=1 bordercolor=black><TR><TD WIDTH=100% BGCOLOR=yellow>") 
      el.document.write(tip) 
      el.document.write("</TD></TR></TABLE>") 
      el.document.close() 
    } 
  } 
 
  function getOffset(el, which) { 
    // Function for IE to calculate position  
    // of an element. 
    var amount = el["offset"+which]  
    if (which=="Top") 
      amount+=el.offsetHeight 
    el = el.offsetParent 
    while (el!=null) { 
      amount+=el["offset"+which] 
      el = el.offsetParent 
    } 
    return amount 
  } 
   
 
  function setPosition(el) { 
    // Set the position of an element 
    src = window.event.srcElement 
    if (allSupport) { 
      el.style.pixelTop = getOffset(src, "Top") 
      el.style.pixelLeft = getOffset(src, "Left") 
    } else 
    { 
      el.top = src.y + 20 //window.event.y + 15 
      el.left = src.x //window.event.x 
    } 
  } 
       
  function setVisibility(el, bDisplay) { 
    // Hide or show to tip 
    if (bDisplay) 
      if (allSupport) 
        el.style.visibility = "visible"  
      else 
        el.visibility = "show"; 
    else 
      if (allSupport) 
        el.style.visibility = "hidden" 
      else 
        el.visibility = "hidden" 
  } 
 
 
  function displayContents(tip) { 
    // Display the tooltip.  
    var el = getElement("tipBox") 
    writeContents(el, tip) 
    setPosition(el) 
    setVisibility(el, true) 
  } 
 
 
  function doMouseOver(e) { 
    // Mouse moves over an element 
    setupEventObject(e) 
    var el, tip 
    if ((el = checkName(window.event.srcElement))!=null) 
      if  (!el._display) { 
        displayContents(el._tip) 
        el._display = true 
      } 
  } 
 
  function doMouseOut(e) { 
    // Mouse leaves an element 
    setupEventObject(e) 
    el = checkName(window.event.srcElement) 
    var el, tip 
    if ((el = checkName(window.event.srcElement))!=null) 
      if (el._display) 
        if ((el.contains==null) || (!el.contains(window.event.toElement))) { 
          setVisibility(getElement("tipBox"), false) 
          el._display = false 
        } 
  } 
 
  function doLoad() { 
    // Do Loading 
    if ((window.document.captureEvents==null) && (!allSupport)) 
      return // Not IE4 or NS4 
    if (window.document.captureEvents!=null)  // NS - capture events 
      window.document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT) 
    window.document.onmouseover = doMouseOver; 
    window.document.onmouseout = doMouseOut; 
  } 
 
  window.onload = doLoad 
  // --> 
</SCRIPT> 
 

<body bgcolor="#ffffff" vlink="#444464" link="#000066">

HTMLheader

#<table width="700" border=0 cellspacing=1 cellpadding=4>       
#<tr><th BGCOLOR="white"><h3><font color="black"><a href="howtouse.html" onClick="window.open('','howto','height=250,width=600,scrollbars=yes')" target="howto">A STEP BY STEP GUIDE</a> FOR <a href="/physics/$courseno/">$course</a></th></tr>
#</table>

#see http://www.mpae.gwdg.de/mpae_RZ/online_doc/perl/PerlFAQ.html
#   warn "has nondigits"        if     /\D/;
#   warn "not a whole number"   unless /^\d+$/;
#   warn "not an integer"       unless /^-?\d+$/;  # reject +3
#   warn "not an integer"       unless /^[+-]?\d+$/;  
#   warn "not a decimal number" unless /^-?\d+\.?\d*$/;  # rejects .2
#   warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
#   warn "not a C float"
#       unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;


}




