//From prototype.js
var PeriodicalExecuter = new Class({
	// name: 'PeriodicalExecuter',
	initialize: function(callback, frequency) {

		this.callback = callback;
		this.frequency = frequency;
		this.currentlyExecuting = false;

		this.registerCallback();
	},

	registerCallback: function() {

		this.stop();
		this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
		return this;
	},

	execute: function() {

		this.callback(this);
		return this;
	},

	stop: function() {

		if (!this.timer) return this;
		clearInterval(this.timer);
		this.timer = null;
		return this;
	},

	onTimerEvent: function() {

		if (!this.currentlyExecuting) {

			try {

				this.currentlyExecuting = true;
				this.execute();
			} finally {

				this.currentlyExecuting = false;
			}
		}

		return this;
	}
});

var CountDown = new Class({options: {

		date: null,
		onChange: $empty,
		onComplete: $empty
	},
	initialize: function (options) {

		this.setOptions(options);

		this.timer = new PeriodicalExecuter(this.update.bind(this), 1);
	},
	update: function () {

		var time = Math.floor((this.options.date.getTime() - new Date().getTime()) / 1000);

		if(time <= 0) time = 0;

		var stop = time == 0;

		var countdown = {days: Math.floor(time / (60 * 60 * 24)), 'time': time};

		time %= (60 * 60 * 24);

        countdown.hours = Math.floor(time / (60 * 60));
		time %= (60 * 60);
        countdown.minutes = Math.floor(time / 60);
        countdown.second = time % 60;

		this.fireEvent('onChange', countdown);

		if(stop) {

			this.timer.stop();
			this.fireEvent('onComplete');
		}
	},
	Implements: [Options, Events]
});
