/* CountdownClock.js
 * Copyright © 2005 Pinemeadow Golf Products
 * Written by Nathan Humble <nhumble@golfclubs.pinemeadowgolf.com>
 */

function CountdownClock_update() {
	var now = new Date();
	var remaining = this.then - now;
	
	if (remaining < 0) remaining = 0;
		
	// Compute time parts
	var millis = ((remaining % 1000) + "00").slice(0,3); remaining = Math.floor(remaining / 1000);
	var secs   = ("0" + (remaining % 60)).slice(-2);     remaining = Math.floor(remaining / 60);
	var mins   = ("0" + (remaining % 60)).slice(-2);     remaining = Math.floor(remaining / 60);
	var hours  = ("0" + (remaining % 24)).slice(-2);     remaining = Math.floor(remaining / 24);
	var days   = remaining;
	
	if (this.interval >= 1000 && this.crank_it_up && days == 0) {
	  this.interval = this.crank_it_up;
	  this.resolution = this.interval;
	}
	
	this.target.innerHTML = "";
	if (days) this.target.innerHTML += days +  " day" + (days > 1 ? "s" : "") + ", ";
	if (this.resolution < 3600000) {
		this.target.innerHTML += hours + ":" + mins;
		if (this.resolution < 60000) {
			this.target.innerHTML += ":" + secs;
			if (this.resolution < 1000) this.target.innerHTML +=  "." + millis;
		}
	}
	
	// Define a local function so we can set a callback.
	var mySelf = this;
	var timeoutFunc = function() { mySelf.update() };
	
	// Set the callback (until no time is left).
	if (this.then - now) setTimeout(timeoutFunc, this.interval);
}

function CountdownClock(target, then, interval, resolution, crank_it_up) {
  	this.target      = target;
  	this.then        = new Date(then);
  	this.interval    = interval    || 1000; // Update frequency, in milliseconds (defaults to 1 sec).
  	this.resolution  = resolution  || interval;
  	this.crank_it_up = crank_it_up || 0;    // Change the interval to crank_it_up on the last day.
	
	// Don't update more frequently than once/sec in Firefox/Windows
  // if (navigator.userAgent.match(/Windows.+Gecko\/\d+/i)) this.interval = (interval < 1000 ? 1000 : interval);
  
  	if (this.interval > this.resolution) this.resolution = this.interval;
	
	// Methods
	this.update = CountdownClock_update;
	
	// Update self.
	this.update();
}
