/**
 * @author Mathias Linkerhand <a href="http://www.proflogic.com">www.proflogic.com</a>
 * @version 2009-06-03
 */
var Countdown = Class.create({
	initialize: function(date, elements){
		this.futureDate = date;
		this.elements = elements;
		this.millisecondsPerSecond = 1000; 
		this.millisecondsPerMinute = this.millisecondsPerSecond * 60; 
		this.millisecondsPerHour = this.millisecondsPerMinute * 60;
		this.millisecondsPerDay = this.millisecondsPerHour * 24;
		
		if(this.elements.all != null && this.elements.second10 != null){
			this.interval = 0.1;
		}else{
			if(this.elements.second != null){
				this.interval = 1;
			}else{
				this.interval = 10;
			}
		}
	},

	start: function(){
		if(this.periodicalExecuter == null){
			this.show();
			this.periodicalExecuter = new PeriodicalExecuter(this.show.bind(this), this.interval);
		}
	},

	stop: function(){
		if(this.periodicalExecuter != null){
			this.periodicalExecuter.stop();
			this.periodicalExecuter = null;
		}
	},

	show: function(){
		var now = new Date();
		var deltaT = this.futureDate.getTime() - now.getTime();
		var dday = Math.floor(deltaT / this.millisecondsPerDay);
		var dhour = Math.floor((deltaT % this.millisecondsPerDay) / this.millisecondsPerHour);
		var dmin = Math.floor(((deltaT % this.millisecondsPerDay) % this.millisecondsPerHour) / this.millisecondsPerMinute);
		var dsec = Math.floor((((deltaT % this.millisecondsPerDay) % this.millisecondsPerHour) % this.millisecondsPerMinute) / this.millisecondsPerSecond);
		var d10sec = Math.floor((((deltaT % this.millisecondsPerDay) % this.millisecondsPerHour) % this.millisecondsPerMinute) % this.millisecondsPerSecond / 100);

		// if on day of occasion
		if(deltaT <= 0){
			if(this.elements.day != null) this.elements.day.update('0');
			if(this.elements.hour != null) this.elements.hour.update('00');
			if(this.elements.minute != null) this.elements.minute.update('00');
			if(this.elements.second != null) this.elements.second.update('00');
			if(this.elements.second10 != null) this.elements.second10.update('0');
			if(this.elements.all != null) this.elements.all.update('0:00:00:00.0');
			this.stop();
		} else {
			if(this.elements.day != null) this.elements.day.update(dday);
			if(this.elements.hour != null) this.elements.hour.update(dhour < 10 ? "0" + dhour : dhour);
			if(this.elements.minute != null) this.elements.minute.update(dmin < 10 ? "0" + dmin : dmin);
			if(this.elements.second != null) this.elements.second.update(dsec < 10 ? "0" + dsec : dsec);
			if(this.elements.second10 != null) this.elements.second10.update(d10sec);
			if(this.elements.all != null) this.elements.all.update(dday + ':' + (dhour < 10 ? "0" + dhour : dhour) + ':' + (dmin < 10 ? "0" + dmin : dmin) + ':' + (dsec < 10 ? "0" + dsec : dsec) + '.' + d10sec);
		}
	},
	
	setInterval: function(interval){
		this.interval = interval;
		if(this.periodicalExecuter != null){
			this.stop();
			this.start();
		}
	}
});
