var countdowns = new Object();

function Countdown(id, toDate)
{
	if (document.getElementById == null || document.getElementById(id) == null) return;
	this.elem = document.getElementById(id);
	this.fromDate = new Date();
	this.toDate = typeof(toDate) == "object" ? toDate : new Date(toDate);
	this.fields = new Array();
	this.timesUp = false;
	
	this.format = function()
	{
		var displayString = "";
		if (!this.timesUp)
			displayString = "%d% days %h% hours %m% minutes %s% seconds";
		else
			displayString = "The date has arrived!";
		return displayString;
	};
	
	this.display = function(base, func)
	{
		this.base = base.toLowerCase();
		if (func != null) this.format = func;
		this.show();
	};
	
	this.show = function()
	{
		this.fromDate = new Date();
		var obj = this;
		var diff = Math.round((this.toDate.getTime() - this.fromDate.getTime()) / 1000);
		
		if (diff < 0)
		{
			this.timesUp = true;
			this.elem.innerHTML = this.format();
			return;
		}
		
		var minuteValue = 60;
		var hourValue = 60 * 60;
		var dayValue = 60 * 60 * 24;
		
		this.fields[0] = Math.floor(diff / dayValue);
		this.fields[1] = Math.floor((diff - this.fields[0] * dayValue) / hourValue);
		this.fields[2] = Math.floor((diff - this.fields[0] * dayValue - this.fields[1] * hourValue) / minuteValue);
		this.fields[3] = Math.floor((diff - this.fields[0] * dayValue - this.fields[1] * hourValue - this.fields[2] * minuteValue));
		
		switch (this.base)
		{
			case "hours":
				this.fields[1] += this.fields[0] * 24;
				this.fields[0] = "n/a";
				break;
			case "minutes":
				this.fields[2] += this.fields[0] * 24 * 60 + this.fields[1] * 60;
				this.fields[0] = this.fields[1] = "n/a";
				break;
			case "seconds":
				this.fields[3] = diff;
				this.fields[0] = this.fields[1] = this.fields[2] = "n/a";
		}
		
		var displayString = this.format();
		displayString = displayString.replace(/%d%/g, this.fields[0]);
		displayString = displayString.replace(/%h%/g, this.fields[1]);
		displayString = displayString.replace(/%m%/g, this.fields[2]);
		displayString = displayString.replace(/%s%/g, this.fields[3]);
		
		this.elem.innerHTML = displayString;
		//setTimeout(function() { obj.show() }, 1000);
		setTimeout("countdowns['" + id + "'].show()", 1000);
	};
	
	countdowns[id] = this;
}

function loadCountdown(interval)
{
	var toDate = new Date();
	toDate.setMinutes(toDate.getMinutes() + interval);
	var futureDate = new Countdown("timer", toDate);
	futureDate.display("minutes", formatResults);
}

function formatResults()
{
	var displayString = "";
	if (!this.timesUp)
		displayString = '%m% minutes %s% seconds';
	else
	{
		displayString = "The page has expired.";
		location.href = "/admin/auto-log-out.asp";
	}
	return displayString;
}