// Note: these functions need to be written for reuse (i.e. given
// two dates, return the difference in days, hours, minutes, hours).
//
// @author g.d.thurman
// @version 2001.02.06-2000.12.30
//
// @updated 2002.04.18 
// if EVENT is null or empty string, then
// return a user-defined DateDiff object
//
// @edu Not ready for lecture.
//

function howlong(WHEN, EVENT) {
   var d = calcDateDiff(WHEN);
   if (null == d) 
      return "";
   if (null == EVENT || "" == EVENT) {
      d.days++;
      return d;
   }
   document.write("<h3 class='alert'>&nbsp;Countdown to " + 
                   WHEN + "&nbsp;</h3>");
   document.write("<blockquote>");
   document.write("According to your computer's clock and this sloppy " +
                  "<a href='/~gdt/js/scripts/howlong.txt'>" +
                  "JavaScript code</a>, it appears <b>" + WHEN + 
                  "</b> (i.e. <i>" + EVENT + "</i>) occurs in <b>");
   document.write(d.days + " day");
   if (d.days == 0 || d.days > 1) document.write("s"); 
   document.write(", ");
   document.write(d.hours + " hour");
   if (d.hours == 0 || d.hours > 1) document.write("s"); 
   document.write(", ");
   document.write(d.minutes + " minute");
   if (d.minutes == 0 || d.minutes > 1)  document.write("s");
   document.write(", ");
   document.write("and " + d.seconds + " second");
   if (d.seconds == 0 || d.seconds > 1) document.write("s");
   document.write("</b>. <font size='1'>[<a href=''" +
                  "onclick='history.go(0); return false;'>" +
                  "click to refresh</a>]</font>");
   document.write("</blockquote>");
}

function calcDateDiff(when) {
   var MILLISECS_PER_SECOND = 1000;
   var SECS_PER_MINUTE = 60;
   var MINUTES_PER_HOUR = 60;
   var HOURS_PER_DAY = 24;
   var SECS_PER_HOUR = SECS_PER_MINUTE * MINUTES_PER_HOUR;
   var SECS_PER_DAY = SECS_PER_HOUR * HOURS_PER_DAY;
   var MILLISECS_PER_MINUTE = SECS_PER_MINUTE * MILLISECS_PER_SECOND;
   var MILLISECS_PER_HOUR = SECS_PER_HOUR * MILLISECS_PER_SECOND;
   var MILLISECS_PER_DAY = SECS_PER_DAY * MILLISECS_PER_SECOND;
   var now = new Date();
   var then = new Date(when);
   if (now > then) return null;
   var diff = then - now;
   var days = Math.floor(diff / MILLISECS_PER_DAY);
   var adj = days * MILLISECS_PER_DAY;
   var hours = Math.floor((diff - adj) / MILLISECS_PER_HOUR);
   adj += hours * MILLISECS_PER_HOUR;
   var minutes = Math.floor((diff - adj) / MILLISECS_PER_MINUTE);
   adj += minutes * MILLISECS_PER_MINUTE;
   var seconds = Math.floor((diff - adj) / MILLISECS_PER_SECOND);
   return new DateDiff(days, hours, minutes, seconds);
}

function DateDiff(d, h, m, s) {
   this.days = d;
   this.hours = h;
   this.minutes = m;
   this.seconds = s;
}

