function sf()
//This function sets the focus of the Google search bar.
{
   document.f.q.focus();
}

/*************************************************************************
**
** User-controlled varibles. Used to make the script look the way
** you choose to make it look.
**
**************************************************************************/

//Set these variables to be the colors you want for the highlights for
//current and next classes as well as the general background color of the
//table. Accepts "named" color constants as well as hex values. ie, white
//is FFFFFF (see backGroundColor for the color black)

var currentColor = "black";
var currentFontColor = "black";
var nextColor = "aqua";
var nextFontColor = "navy";

//var currentColor = "navy";
//var currentFontColor = "orange";
//var nextColor = "aqua";
//var nextFontColor = "black";

var backGroundColor = "black";
var fontColor = "black";

/*Obsolete: This is now derived from the property "row_count" in the time cell*/
//Set this variable to be the number of rows of classes. i.e., this is the
//number of rows with a "8:00am -- 10:00am" in the first column. Don't
//count the row with the day-of-the-week headers or the rows that
//provide descriptions of the highlighted class
//var numberOfRows = 7;

var no_class_description = "Completely Classless";
var no_class_location = "Wandering Afar";
var weekend_description = "Weekend's Here!";
var weekend_location = "A party, most likely :)";

//The id and name attribute of the HTML table. Unless you're weird,
//"myClasses" should work fine.
var tableName = "myClasses";

/*************************************************************************
**
** End the user-controlled variables. Everything else is script-controlled.
** It could also be said to be controlled by the HTML table. But let's not
** get picky.
**************************************************************************/

//Global variables used during the program
var timer = null;                //Allow the script to update once a second
var table = null;                //Store a reference to the myClasses table

var currentClassStart   = -1;    //Store the current state of the table so the
var currentClassEnd     = -1;    //script only updates when it needs to
var currentClassDay     = -1;    //Kind of buggy. It might not always roll
var nextClassStart      = -1;    //over at midnight. Just hit refresh. Why are
var nextClassEnd        = -1;    //you studying a class schedule at midnight
var nextClassDay        = -1;    //anyway?

var animationI         = 0;     //Used in the nifty animination thingie
var animationJ         = 0;     //that doesn't actually exist. Really, these
                                //variables (and this comment) do nothing but
                                //make the file a few lines bigger (it takes 
                                //longer to download) and then take up a few
                                //bytes of memory. I don't know how big a 
                                //Javascript variable is, so I don't know how
                                //much memory is used. It really doesn't
                                //matter.
var numberOfRows = 0;				

/** Ways to change a table cell background color, assuming that cell was found
** using the getCell(r,c) method

//Correct way to set the background color: cell = getCell(x,y);
//                                         cell.setAttribute("style",
//                                                 "background-color:purple");


//IE way of setting background color:  cell = getCell(x,y);
//                                     cell.style.backgroundColor = "purple";

**/


function tillSchool()
{
   var schoolDate;
   var todayDate;

   schoolDate = new Date(2003, 8, 17);
   todayDate = new Date();
   
   return schoolDate - todayDate;
}

function getTime()
//This function returns a string of the current time
{
   var d;
   var hours;
   var minutes;
   var seconds;
   var AMPM;

   d = new Date();
   hours = d.getHours();
   minutes = d.getMinutes();
   seconds = d.getSeconds();

   if (hours > 11)
      AMPM = "PM";
   else
      AMPM = "AM";

   //Account for military time
   hours = hours % 12;

   //Add a 0 in front of the seconds/minutes if it's below ten (so it'll be
   // 3:02:05 instead of 3:02:5
   minutes = ((minutes < 10) ? "0" : "") + minutes
   seconds=((seconds < 10) ? "0" : "") + seconds

   hours = ((hours == 0) ? "12" : hours);
   return hours + ":" + minutes + ":" + seconds + " " + AMPM;
}

function getCell(col, row)
//Allows an HTML table to be easily treated as a two-dimensional array
//Returns the cell in the table that is at col column on row row.
{
   var listRows;              //A list of all the rows in the table
   var listCols;              //A list of all the columns in a row
   var elementRow;            //A single row
   var elementCell;           //A single cell

   //Get all the rows for the table. If the requested row is not
   //out of bounds, fetch it
   listRows = table.getElementsByTagName("tr");
   if(row > -1 && row < listRows.length)
      elementRow = listRows.item(row);
   else
      return null;

   //Get all the cells in the requested row. If the requested cell is not
   //out of bounds, fetch it
   listCols = elementRow.getElementsByTagName("td");
   if(col > -1 && col < listCols.length)
      elementCell = listCols.item(col);
   else
      return null;

   return elementCell;
}

function setTable()
//Sets the varible 'table' to point to the myClasses table
{
   var body = document.getElementsByTagName("body").item(0);
   var listTables = body.getElementsByTagName("table");
   var i;

   for(i = 0; i < listTables.length; i++)
   {
      if(listTables.item(i).getAttribute("id") == tableName)
      {
         table = listTables.item(i);
         break;
      }
   }
}

function paintTime()
//Paint the current time.
//Decide if the table cells need to be repainted and repaint them if
//necessary
{
   var tableCell;
   var text;
   var t;

   //Get the time cell, position (0,0)
   tableCell = getCell(0,0);

   //Set the text (the current time) and then replace that cell's
   //text with the time

   tableCell.style.backgroundColor = currentColor;
   tableCell.style.color = currentFontColor;
   tableCell.style.background = "url(aqua_pinstripes.jpg) top left";
   text = document.createTextNode(getTime());
   tableCell.replaceChild(text, tableCell.firstChild);


   t = getTimeInMinutes();

   //Try to decide if the classes need to be repainted. This might be buggy:
   //I have neither the time nor the patience to test it. (actually, I just 
   //don't want to screw up my system clock. You might have to refresh at midnight.
   if(
      (currentClassEnd != 0 && t > currentClassEnd)
      || (t > nextClassStart && nextClassDay <= new Date().getDay())
      || (nextClassStart == -1)
      || (currentClassStart == -1))
   {
      //Clear the background of any residual class colors
      clearColors();
      //Paint the new day of the week
      paintDayOfWeek();
      //Refind the classes (is refind a word? Is now.)
      findClass(new Date().getDay());
   }

   //Call this function every second, the JavaScript way!
   timer = setTimeout("paintTime()", 1000);
}

function clearColors()
{
   //Go through each cell in the table, and set its background color to
   //the original background color
   var i;   //i and j: multi-dimensional array counting variables
   var j;

   for(i = 0; i < numberOfRows + 1; i++)
   {
      for(j = 0; j < 8; j++)
      {
         getCell(j,i).style.backgroundColor = backGroundColor;
         getCell(j,i).style.color = fontColor;
      }
   }

   //set time cell to the "current" color: because it's always the current time! 
   getCell(0,0).style.backgroundColor = currentColor;
   getCell(0,0).style.color = currentFontColor;
   
   //Set the descriptor cells to their assigned colors
   //Uncomment every 4th line to paint the background of the
   //"title" cells (for lack of a better word.
   
//   getCell(0, numberOfRows + 1).style.backgroundColor = currentColor;
   getCell(0, numberOfRows + 1).style.backgroundColor = backGroundColor;
   getCell(1, numberOfRows + 1).style.backgroundColor = currentColor;
   getCell(1, numberOfRows + 1).style.color = currentFontColor;
   getCell(1, numberOfRows + 1).style.background = "url(aqua_pinstripes.jpg) top left";
//   getCell(0, numberOfRows + 2).style.backgroundColor = currentColor;
   getCell(0, numberOfRows + 2).style.backgroundColor = backGroundColor;
   getCell(1, numberOfRows + 2).style.backgroundColor = currentColor;
   getCell(1, numberOfRows + 2).style.color = currentFontColor;
   getCell(1, numberOfRows + 2).style.background = "url(aqua_pinstripes.jpg) top left";
//   getCell(0, numberOfRows + 3).style.backgroundColor = nextColor;
   getCell(0, numberOfRows + 3).style.backgroundColor = backGroundColor;
   getCell(1, numberOfRows + 3).style.backgroundColor = nextColor;
   getCell(1, numberOfRows + 3).style.color = nextFontColor;
   getCell(1, numberOfRows + 3).style.background = "url(aqua_pinstripes.jpg) top left";

//   getCell(0, numberOfRows + 4).style.backgroundColor = nextColor;
   getCell(0, numberOfRows + 4).style.backgroundColor = backGroundColor;
   getCell(1, numberOfRows + 4).style.backgroundColor = nextColor;
   getCell(1, numberOfRows + 4).style.color = nextFontColor;
   getCell(1, numberOfRows + 4).style.background = "url(aqua_pinstripes.jpg) top left";

}

function findClass(day)
{
   //Based on the current day of the week (passed in by day),
   //figure out what classes to highlight


   var t = getTimeInMinutes();      //The current time
   var i = 0;                       //A loop counter
   var cell;                        //The cell we're concerned with
   var foundNext = 0;               //Have we found the next class
   var weekendWrapAround = 0;       //Have we wrapped the weekend?

   day++; //day is zero based, but we're one based

/*   if(day > 5 || day < 1)  //It's the weekend! w00t!
   {
      currentClassStart = 0;
      currentClassEnd = 0;
      currentClassDay = 7;

      setText(1,numberOfRows + 1,weekend_description);
      setText(1,numberOfRows + 2,weekend_location);
   }
   else  //Regular class day
*/     
   {
      //Go through each class for this day
      for(i = 1; i < numberOfRows + 1; i++)
      {
         cell = getCell(day, i);
         //See if we're in the class contained in this cell
         if(t >= cell.getAttribute("starttime") && t <= cell.getAttribute("endtime"))
         {
            //One extra check to make sure that this is a class (probably
            //not needed, but what the heck? )
            if(cell.childNodes.item(0).data != "---")
            {
               //Set the global variables that tell us what class-time we're
               //in
               currentClassStart = cell.getAttribute("starttime");
               currentClassEnd = cell.getAttribute("endtime");
               currentClassDay = day;

               //These are the two description cells for the current class
               setText(1,numberOfRows + 1,cell.getAttribute("description"));
               setText(1,numberOfRows + 2,cell.getAttribute("location"));

               //Highlight this cell
               cell.style.backgroundColor = currentColor;
               cell.style.color = currentFontColor;
               cell.style.background = "url(aqua_pinstripes.jpg) top left";
               //Highlight the time of this class in the very first column
               getCell(0,i).style.backgroundColor = currentColor;
               getCell(0,i).style.color = currentFontColor;
               getCell(0,i).style.background = "url(aqua_pinstripes.jpg) top left";

               //We can ignore the rest of this for
               break;
            }

         }
      }
   }

   //If i is past the number of rows, no class qualified as a current class
   if(i == numberOfRows + 1)
   {
      currentClassStart = 0;
      currentClassEnd = 0;
      currentClassDay = day;

      setText(1,numberOfRows + 1,no_class_description);
      setText(1,numberOfRows + 2,no_class_location);
      i = 0;
   }


   //Accomodate the weekend
/*   if(day > 5)
   {
      day = 0;
      weekendWrapAround = 1;
   }
*/
   //while(true) allows us to loop the next class finder. This is basically
   //so that if we have a day with no classes, it won't trip up on that
   while(true)
   {
      //Check each class in the current day (starting with the actual real day)
      //to see if they qualify as the next class
      for(i++; i < numberOfRows + 1; i++)
      {
         cell = getCell(day, i);
         //Make sure that it's currently a class && that it starts after the
         //current time (otherwise, it's hardly a next class)
         if(cell.childNodes.item(0).data != "---" &&
            cell.getAttribute("starttime") > t)
         {
               nextClassStart = cell.getAttribute("starttime");
               nextClassEnd = cell.getAttribute("endtime");

               if(weekendWrapAround == 1)
                  nextClassDay = 6;
               else
                  nextClassDay = day;

               //These are the descriptors for the next class
               setText(1,numberOfRows + 3,cell.getAttribute("description"));
               setText(1,numberOfRows + 4,cell.getAttribute("location"));

               //Highlight the current class and the time for the class
               cell.style.backgroundColor = nextColor;
               cell.style.color = nextFontColor;
               cell.style.background = "url(aqua_pinstripes.jpg) top left";
               getCell(0,i).style.backgroundColor = nextColor;
               getCell(0,i).style.color = nextFontColor;
               getCell(0,i).style.background = "url(aqua_pinstripes.jpg) top left";               
               //Make sure everyone knows that we found the next class already
               foundNext = 1;
               break;
         }
      }

      //If we've already found the next class, get out of the while
      if(foundNext == 1)
      {
         break;
      }

      //At this part, we wrap around to the next day. Set t = 0 because on the
      //next day, *every* class is after the current time (all > 0).
      t = 0;

      //Go to the next day. If the next day isn't a real day, loop to Sunday
      day++;
      if(day > 6)
      {
         day = 0;
         weekendWrapAround = 1;
      }

      //Start over from the top
      i = 0;
   }
}

function stop()
{
   //Stop the timer
   clearTimeout(timer)
}

function getTimeInMinutes()
{
   //Return the number of minutes into the day
   var d = new Date();
   return (d.getHours() * 60) + d.getMinutes();
}

function start()
{
   var d = new Date().getDay();
   //This *must* be called as the very first instruction because
   //several methods rely on the knowledge that the table variable
   //has already been set. This means that there is no error checking
   //and the script will break.
   setTable();

   //Set the focus to the Google bar: useless unless you have a Google search
   //bar named q in form f. Really, it'll break the script, so take it out if you don't
   //have that type of search bar.

   sf();

   //Highlight Dave's link on Sundays
   if (d == 0)
      document.getElementById("dave").style.color = "red";

   //On Thursday's highlight Cringly's link so I remember to read it
   if (d == 4)
      document.getElementById("cringly").style.color = "red";

   //init numberOfRows
   var tableCell = getCell(0,0);
   numberOfRows = tableCell.getAttribute("row_count");
   numberOfRows = numberOfRows / 1; //JavaScript voodoo: convince JavaScript to convert numberOfRows from string to integer
   
   //Start the tablepainting. Woo-hoo!
   paintTime();
}

function paintDayOfWeek()
//Color the current day of the week
{
   var d = new Date();
   var day = d.getDay();
   var i;
   
   //Only paint the day of the week, if it's Mon-Fri
   if(day >= 0 && day < 7)
   {
      day++; //day is 0 based, but the table is 1 based
      //getCell(day, 0).style.backgroundColor = currentColor;
      getCell(day, 0).style.color = currentFontColor;
      getCell(day, 0).style.background = "url(aqua_pinstripes.jpg) top left";
      
   }
}

function setText(col, row, s)
//s is the string to write
{
   cell = getCell(col,row);
   var text = document.createTextNode(s);
   cell.replaceChild(text, cell.firstChild);
}
