﻿// JavaScript Document

// objects with id baseName-(days|hours|minutes|seconds) will be updated with the current countdown
var countdownTimers = new Array();
function CountdownTimer(secondsToEnd, baseName) {

	// Public function to update the end time
	this.updateTimer = function(secondsToEnd) {
		this.initialCountdown = secondsToEnd;
		this.initialTime = new Date();
		this.endCallbackAvailable = true;
	}
	
	this.update = function() {
		now = new Date();

		var timerRemaining = this.initialTime.getTime() + (this.initialCountdown*1000) - now.getTime();
		
		timerRemaining = Math.max(0, timerRemaining);

		daysRemaining = Math.floor(timerRemaining/86400000);
		hoursRemaining = Math.floor(timerRemaining/3600000) % 24;
		minutesRemaining = Math.floor(timerRemaining/60000) % 60;
		secondsRemaining = Math.floor(timerRemaining/1000) % 60;
		
		if ($(this.baseName+'-days')) { $(this.baseName+'-days').innerHTML = daysRemaining };
		if ($(this.baseName+'-hours')) { $(this.baseName+'-hours').innerHTML = hoursRemaining; }
		if ($(this.baseName+'-minutes')) { $(this.baseName+'-minutes').innerHTML = minutesRemaining; }
		if ($(this.baseName+'-seconds')) { $(this.baseName+'-seconds').innerHTML = secondsRemaining; }

		if (timerRemaining == 0 && this.endCallbackAvailable == true && typeof(this.endCallback) == "function") {
			this.endCallback();
			this.endCallbackAvailable = false;
		}
	}

	this.setEndCallback = function(endCallback) {
		this.endCallback = endCallback;
	}

	this.baseName = baseName;
	this.endCallbackAvailable = true;

	this.updateTimer(secondsToEnd);
	countdownTimers[baseName] = this;
	this.updater = new PeriodicalExecuter(function() { countdownTimers[baseName].update(); }, 1);
}
