


var XerxesCountdown = function(config){
	Ext.apply(this, config);
}

XerxesCountdown.prototype = {
	targetEl: null, //Element that the counter is placed in
	pulse: null, //The pulse timer object for animating
	countdown: null, //The date + time we are counting down to (Javascript Date)
	precision: "weeks", //What precision the animation works at. weeks - seconds.
	lables: true, //Do we create weeks, days, etc lables?
	endMessage : "", //Message to display when countdown finishes
	timeUnits: {
		weeks: 604800000,
		days: 86400000,
		hours: 3600000,
		minutes: 60000,
		seconds: 1000
	},
	timeLabels: {
		weeks: "weeks",
		days: "days",
		hours: "hours",
		minutes: "minutes",
		seconds: "seconds"
	},
	digitTemplate: new Ext.XTemplate('<p class="digit {label}">{value} <span class="digitLabel">{label}</span></p>'),
	
	startCounter: function(el,date){
		this.countdown = date;
		this.targetEl = Ext.get(el);
		this.updateCounter();
	},
	
	updateCounter: function(){
		clearTimeout(this.pulse); //Avoid double pulses
		var currentTime = new Date();
		var dateDiff = this.countdown - currentTime;
		var html = "";
		if (dateDiff > 0) {
			switch (this.precision) {
				case "weeks":
					html += this.createDigit(this.timeLabels.weeks, Math.floor(dateDiff / this.timeUnits.weeks));
					dateDiff = dateDiff % this.timeUnits.weeks;
				case "days":
					html += this.createDigit(this.timeLabels.days, Math.floor(dateDiff / this.timeUnits.days));
					dateDiff = dateDiff % this.timeUnits.days;
				case "hours":
					html += this.createDigit(this.timeLabels.hours, Math.floor(dateDiff / this.timeUnits.hours));
					dateDiff = dateDiff % this.timeUnits.hours;
				case "minutes":
					html += this.createDigit(this.timeLabels.minutes, Math.floor(dateDiff / this.timeUnits.minutes));
					dateDiff = dateDiff % this.timeUnits.minutes;
				default:
					html += this.createDigit(this.timeLabels.seconds, Math.floor(dateDiff / this.timeUnits.seconds));
					dateDiff = dateDiff % this.timeUnits.seconds;
			}
			pulse = this.updateCounter.defer(1000, this);
		} else {
			html = this.endMessage;
		}

		//Now lets update the content zone
		this.targetEl.update(html);
	},
	
	createDigit: function(label, value){
		if(!this.lables)label="";
		var params = {"label":label,"value":value};
		return this.digitTemplate.apply(params);
	}
	
}

