//
// Utility functions to support Bill Counts' 2006 October Game Web Site
// http://www.billcounts.com/october06/october.htm
//

/////////////////////////////////////////////////////////////////////////////////////////
// Date functions
//

//
// Global definitions to avoid embedding dependencies on Oct 2006 in the scripts
//
var CgameYear = 2006;
var CgameMonth = 9;     // Jan==0, Oct==9
var CdaysInMonth = 31;
var CfrstDyOfMth = 0;   // Sun==0, Fri==5

//
// Get the current date components as integers
//
function getDateInt()
{
  var dateObj, dateInt;
  dateObj = new Date();
  dateInt = dateObj.getDate();
  return dateInt;
}

function getMonthInt()
{
  var dateObj, dateInt;
  dateObj = new Date();
  dateInt = dateObj.getMonth();
  return dateInt;
}

function getYearInt()
{
  var dateObj, dateInt;
  dateObj = new Date();
  dateInt = dateObj.getFullYear();
  return dateInt;
}

//
// find the name of the current page (to use in a table lookup)
//
function currPageName()
{
  var pageName = location.pathname;
  var start;

  start = pageName.lastIndexOf("/") + 1;
  pageName = pageName.substring(start);

  start = pageName.lastIndexOf("\\") + 1;
  pageName = pageName.substring(start);

  return pageName;
}

//
// lookup the date of the provided page name in the "pages" table
//
function findPageDate(pageName)
{
  var pageDate = -1;
  for (var i = 1; i <= CdaysInMonth; i++) {
    if (pages[i]) {
      if (pageName == pages[i].name)
        {pageDate = i; break;}
    }
  }
  return pageDate;
}

//
// Check date of the page:
//   Is it > 0 and <= number of days in the month?
//   Is there an entry for it in the page table?
//   If current date is after the end of the month show all pages.
//   If still during month allow all pages up till today.
//
function validDate(pageDate)
{
  if (pageDate < 1 || pageDate > CdaysInMonth) return false;
  if (! pages[pageDate]) return false;

  if (getYearInt() > CgameYear) return true;
  if (getMonthInt() > CgameMonth) return true;
  if (getDateInt() >= pageDate) return true;

  return false;
}


//=============================================================================
// A function in the style of UNIX printf - output is to the document.
//
// This version only handles the conversions "%s" and "%%".
// Note that there is no check that the number of arguments
//   matches the template requests.
//
function dprintf(format)
{
  var lenTmp = format.length;
  var sTmp = 0;
  var eTmp = 0;
  var nextArg = 1;
  var buffer = "";
  
  while (eTmp < lenTmp)
  {
    while (eTmp < lenTmp)
    {
      if (format.charAt(eTmp) == "%") {break;} // search for conversion spec
      eTmp++;
    }
    if (eTmp == lenTmp) {break;}  // end of string reached
    if (eTmp+1 == lenTmp) {eTmp++; break;}  // an error: last char in string is "%"

    // copy portion of the format string preceeding the conversion
    // specification (if any) to the output buffer
    if (sTmp < eTmp) {buffer = buffer + format.slice(sTmp, eTmp);}

    // handle the two supported conversions
    switch (format.charAt(eTmp+1))
    {
      // escaped "%" case
      case "%":
        buffer = buffer + "%";
        break;

      // string case
      case "s":
        buffer = buffer + arguments[nextArg++];
        break;

      // ignore unsupported conversions
      default:
        break;
    }

    // advance pointers beyond the conversion specification
    eTmp = eTmp + 2;
    sTmp = eTmp;
  }

  // copy portion of the format string following the final conversion
  // specification (if any) to the output buffer
  if (sTmp < eTmp) {buffer = buffer + format.slice(sTmp, eTmp);}

  document.write(buffer);
}


/////////////////////////////////////////////////////////////////////////////////////////
// functions to build the calendar display for picking earlier dates to view
//

//
// behavior function to open the window
//
function MM_openBrWindow(theURL,winName,features)
{
  window.open(theURL,winName,features);
}

//
// creates a single day entry
//   note that the string "?fc=yes" is appended to the page name
//
function calendarDay(page, title, wdth, hght, crop)
{
  var availHeight = screen.availHeight;
  if (hght > availHeight)
    {hght = availHeight - Math.floor(availHeight * 0.075);}

  document.writeln("<td width='60' height='60'>");

  dprintf("<a href=\"javascript:;\" " +
          "onclick=\"MM_openBrWindow('%s','%s','scrollbars=yes,width=%s,height=%s')\">",
          (page + "?fc=yes"), title, wdth, hght);

  dprintf("<img src='../images/%s' width='58' height='58' border='0' />", crop);

  document.writeln("</a> </td>");
}

//
// creates a row of day entries
//   note that first week of the month is week==0
//
function calendarWeek(week, lastday)
{
  var firstDay = (week * 7) + 1 - CfrstDyOfMth; // date of Sunday for the week being shown
  var nextWeek = firstDay + 7;                  // date of Sunday for the following week

  document.write("<tr>");
  for (var i = firstDay; i < nextWeek; i++)
  {
    if (i > 0 && i <= lastday && pages[i])
    {
      //
      // only show crop images for dates up through the last day to be shown
      // also check to see if the crop image is listed in the table
      //
      var pgi = pages[i];
      calendarDay(pgi.name, pgi.title, pgi.width, pgi.height, pgi.cropImage);
    }
    else
    {
      //
      // empty date:
      // pad before the first of the month or
      // after the last day to be shown in the calendar
      //
      document.write("<td width='60' height='60'>&nbsp;</td>");
    }
  }
  document.write("</tr>");
}

//
// create the month table
//   only include enough rows of weeks to cover dates through
//   the last day to be shown
//
function calendarMonth()
{
  // find last date to be shown on calendar
  // during the game month -- it will be yesterday's date
  // after the game month -- it will be the last day of the game month
  var lastday;

  if (getYearInt() > CgameYear || getMonthInt() > CgameMonth)
    {lastday = CdaysInMonth;}
  else
    {lastday = getDateInt() - 1;} // yesterday


  // only show calendar after first day of game
  if (lastday > 0)
  {
    // find the last day's week number
    // first week is week==0
    var weekNum = Math.floor((lastday + CfrstDyOfMth) / 7);

    //document.write("<em>Previous pictures:</em><br />");
    document.write("<img src='../images/Oct_06_calendarHeader.jpg' width='391' height='38' /><br />");
    document.write("<table border='0' cellpadding='0' cellspacing='1'>");

    for (var i = 0; i <= weekNum; i++)
      {calendarWeek(i, lastday);}

    document.write("</table>");
  }
}


/////////////////////////////////////////////////////////////////////////////////////////
// functions to determine how the page was opened
//   if opened from october.htm then open as a page-of-the-day with heading and calendar
//   if opened from the calendar do not display the heading and calendar
//   note: the getArgs() function was copied from page 214 of the fouth edition of
//     "JavaScript The Definitive Guide" by David Flanagan
//

/*
 * This function parses comma-separated name=value argument pairs from
 * the query string of the URL.  It stores the name=value pairs in
 * properties of an object and returns the object.
 */
function getArgs()
{
  var args = new Object();
  var query = location.search.substring(1); //Get query string
  var pairs = query.split(",");       // Break at comma

  for (var i = 0; i < pairs.length; i++)
  {
    var pos = pairs[i].indexOf('=');    // Look for "name=value"
    if (pos == -1) continue;

    var argname = pairs[i].substring(0, pos); // Extract the name
    var value = pairs[i].substring(pos+1);    // Extract the value

    args[argname] = unescape(value);    // Store as property
    // in JavaScript 1.5, use decodeURIComponent() instead of unescape()
  }

  return args;
}

function fromCalendar()
{
  var result = false;
  var args = getArgs();

  if (args.fc) result = true;
  return result;
}

