var JUHPCountdown = Class.create();
JUHPCountdown.prototype = {
	initialize : function(element, options) {
		this.id = element.identify();
		this.element = $(element);
		this.time = parseInt(this.element.innerHTML);

		new PeriodicalExecuter(this.tick.bind(this), 1);
		this.tick();
	},
	tick : function() {
		if (this.time == 0)
			this.time = 86400;

		var dd = this.time % 86400;
		var dm = dd % 3600;
		var ds = dm % 60;

		this.element.update(this.pretty({
			'd' : Math.floor(this.time / 86400),
			'h' : Math.floor(dd / 3600),
			'm' : Math.floor(dm / 60),
			's' : Math.ceil(ds)
		}));

		this.time--;
	},
	pretty : function(obj) {
		return (obj.d==0 ? '' : '<span>' + obj.d + '</span>' + ' dage ') + 
			(obj.h == 0 ? '' : '<span>' + obj.h + '</span>' + (obj.h == 1 ? ' time ' : ' timer ')) + 
			(obj.m == 0 ? '' : '<span>' + obj.m + '</span>' + ' min ') +
			(obj.s == 0 ? '' : '<span>' + obj.s + '</span>' + ' sek');
	}
}

document.observe("dom:loaded", function() {
	$$('[class=juhp-countdown]').each(function(element) {
		zoom = new JUHPCountdown(element);
	});
});
