/*** simpleFindObj, by Andrew Shearer

Efficiently finds an object by name/id, using whichever of the IE,
classic Netscape, or Netscape 6/W3C DOM methods is available.
The optional inLayer argument helps Netscape 4 find objects in
the named layer or floating DIV. */
function simpleFindObj(name, inLayer) {
	return document[name] || (document.all && document.all[name])
		|| (document.getElementById && document.getElementById(name))
		|| (document.layers && inLayer && document.layers[inLayer].document[name]);
}

/*** Beginning of Clock 2.1.2, by Andrew Shearer
See: http://www.shearersoftware.com/software/web-tools/clock/
Redistribution is permitted with the above notice intact.

Client-side clock, based on computed time differential between browser &
server. The server time is inserted by server-side JavaScript, and local
time is subtracted from it by client-side JavaScript while the page is
loading.

Cookies: The local and remote times are saved in cookies named
localClock and remoteClock, so that when the page is loaded from local
cache (e.g. by the Back button) the clock will know that the embedded
server time is stale compared to the local time, since it already
matches its cookie. It can then base the calculations on both cookies,
without reloading the page from the server. (IE 4 & 5 for Windows didn't
respect Response.Expires = 0, so if cookies weren't used, the clock
would be wrong after going to another page then clicking Back. Netscape
& Mac IE were OK.)

Every so often (by default, one hour) the clock will reload the page, to
make sure the clock is in sync (as well as to update the rest of the
page content).

Compatibility: IE 4.x and 5.0, Netscape 4.x and 6.0, Mozilla 1.0. Mac & Windows.

History:  1.0   2000-05-09 GIF-image digits
          2.0   2000-06-29 Uses text DIV layers (so 4.0 browsers req'd), &
                cookies to work around Win IE stale-time bug
          2.1   2002-10-12 Noted Mozilla 1.0 compatibility; released PHP
                version.
          2.1.1 2002-10-20 Fixed octal bug in the PHP translation; the number
                of minutes & seconds were misinterpretes when less than 10
          2.1.2 2003-08-07 The previous fix had introduced a bug when the
                minutes or seconds were exactly 0. Thanks to Man Bui
                for reporting the bug.
*/
var clockIncrementMillis = 1000;
var localTime;
var clockOffset;
var clockExpirationLocal;
var clockTimerID = null;
var remoteName = "remoteClock";
var localName = "localClock";

var Days = ["Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday"];

var Months = ["January", "February", "March", "April", "May", "June", "July",
              "August", "September", "October", "November", "December"];

function clockInit(localDateObject, serverDateObject)
{
   var origRemoteClock = parseInt(clockGetCookieData(remoteName));
   var origLocalClock = parseInt(clockGetCookieData(localName));
   var newRemoteClock = serverDateObject.getTime();
   // May be stale (WinIE); will check against cookie later
   // Can't use the millisec. ctor here because of client inconsistencies.
   var newLocalClock = localDateObject.getTime();
   var maxClockAge = 60 * 60 * 1000;   // get new time from server every 1hr

   // Now that we're comparing the Remote Clock as numbers, we have to
   // make sure that the cookie value is a number. If not, then set to
   // 0.
   if (isNaN(origRemoteClock)) { origRemoteClock = 0; }
   // Only update the cookie if the server time is after the server
   // time saved in the cookie. This prevents loading earlier values
   // when going back to preloaded pages using the same cookie.
   //if (newRemoteClock != origRemoteClock) {
   if (newRemoteClock > origRemoteClock) {
      // new clocks are up-to-date (newer than any cookies)
      document.cookie = remoteName + "=" + newRemoteClock + "; path=/";
      document.cookie = localName + "=" + newLocalClock + "; path=/";
      clockOffset = newRemoteClock - newLocalClock;
      clockExpirationLocal = newLocalClock + maxClockAge;
      localTime = newLocalClock;  // to keep clockUpdate() happy
   }
   else if (origLocalClock != origLocalClock) {
      // error; localClock cookie is invalid (parsed as NaN)
      clockOffset = null;
      clockExpirationLocal = null;
   }
   else {
      // fall back to clocks in cookies
      clockOffset = origRemoteClock - origLocalClock;
      clockExpirationLocal = origLocalClock + maxClockAge;
      localTime = origLocalClock;
      // so clockUpdate() will reload if newLocalClock
      // is earlier (clock was reset)
   }
   /* Reload page at server midnight to display the new date,
      by expiring the clock then */
//   var nextDayLocal = (new Date(serverDateObject.getFullYear(),
//         serverDateObject.getMonth(),
//         serverDateObject.getDate() + 1)).getTime() - clockOffset;
//   if (nextDayLocal < clockExpirationLocal) {
//      clockExpirationLocal = nextDayLocal;
//   }
   clockUpdate();
}

function clockClear() {
   if (clockTimerID) {
      clearTimeout(clockTimerID);
      clockTimerID = null;
   }
}

function clockTimeString(serverTime) {
   return serverTime == null ? "Unknown" : (Days[serverTime.getDay()] + ', '
      + Months[serverTime.getMonth()] + ' '
      + serverTime.getDate() + ', '
      + serverTime.getFullYear() + ' @ '
      + (serverTime.getHours() < 10 ? "0" : "") + serverTime.getHours()
      + (serverTime.getMinutes() < 10 ? ":0" : ":") + serverTime.getMinutes()
      + (serverTime.getSeconds() < 10 ? ":0" : ":") + serverTime.getSeconds()
      + " " + clockServerTimeZone);
}

function clockDisplayTime(serverTime) {
   clockWriteToDiv("ClockTime", clockTimeString(serverTime));
}

function clockWriteToDiv(divName, newValue) // APS 6/29/00
{
   var divObject = simpleFindObj(divName);
   if (divObject && document.getElementById) {
      /* This is the DOM approved way of updating the text. */
      /* Clear the clock value. */
      while (divObject.firstChild) divObject.removeChild(divObject.firstChild);
      /* Update the clock value. */
      divObject.appendChild(document.createTextNode(newValue));
   }
   else if (divObject && divObject.innerHTML) {
      divObject.innerHTML = newValue;
   }
   else if (divObject && divObject.document) {
      divObject.document.writeln(newValue);
      divObject.document.close();
   }
   // else divObject wasn't found; it's only a clock, so don't bother complaining
}

function clockGetCookieData(label) {
   /* find the value of the specified cookie in the document's
   semicolon-delimited collection. For IE Win98 compatibility, search
   from the end of the string (to find most specific host/path) and
   don't require "=" between cookie name & empty cookie values. Returns
   null if cookie not found. One remaining problem: Under IE 5 [Win98],
   setting a cookie with no equals sign creates a cookie with no name,
   just data, which is indistinguishable from a cookie with that name
   but no data but can't be overwritten by any cookie with an equals
   sign. */
   var c = document.cookie;
   if (c) {
      var labelLen = label.length, cEnd = c.length;
      while (cEnd > 0) {
         var cStart = c.lastIndexOf(';',cEnd-1) + 1;
         /* bug fix to Danny Goodman's code: calculate cEnd, to
         prevent walking the string char-by-char & finding cookie
         labels that contained the desired label as suffixes */
         // skip leading spaces
         while (cStart < cEnd && c.charAt(cStart)==" ") cStart++;
         if (cStart + labelLen <= cEnd && c.substr(cStart,labelLen) == label) {
            if (cStart + labelLen == cEnd) {                
               return ""; // empty cookie value, no "="
            }
            else if (c.charAt(cStart+labelLen) == "=") {
               // has "=" after label
               return unescape(c.substring(cStart + labelLen + 1,cEnd));
            }
         }
         cEnd = cStart - 1;  // skip semicolon
      }
   }
   return null;
}

/* Called regularly to update the clock display as well as onLoad (user
   may have clicked the Back button to arrive here, so the clock would need
   an immediate update) */
function clockUpdate()
{
   var lastLocalTime = localTime;
   localTime = (new Date()).getTime();
   
   /* Sanity-check the diff. in local time between successive calls;
      reload if user has reset system clock */
   if (clockOffset == null) {
      clockDisplayTime(null);
   }
   else if (localTime < lastLocalTime || clockExpirationLocal < localTime) {
      /* Clock expired, or time appeared to go backward (user reset
         the clock). Reset cookies to prevent infinite reload loop if
         server doesn't give a new time. */
      document.cookie = remoteName + '=-; path=/';
      document.cookie = localName + '=-; path=/';
      /* Instead of reloading the page, try running Ajax. */
      //location.reload();      // will refresh time values in cookies
      /* Do Ajax (This will reset the clockLocalStartTime and
         clockServerStartTime variables and reinitialize the clock. */
      AjaxDo(window.location.protocol + '//begghilos2.ath.cx/~jyseto/javascripts/Clock.php');
   }
   else {
      // Compute what time would be on server 
      var serverTime = new Date(localTime + clockOffset);
      clockDisplayTime(serverTime);
      
      // Reschedule this func to run on next even clockIncrementMillis boundary
      clockTimerID = setTimeout("clockUpdate()",
         clockIncrementMillis - (serverTime.getTime() % clockIncrementMillis));
   }
}
