var CountDown = Class.create({
  initialize: function(identifier, date, text, finishedText, alt) {
		this.id = identifier;
		this.toDate = date;
		this.secs = 0;
    
    if (text == '') text = '%%D<span class="countdown-sep">:</span>%%H<span class="countdown-sep">:</span>%%M<span class="countdown-sep">:</span>%%S';
		this.text = text;
		
		if (typeof(finishedText) == 'undefined') finishedText = 'Tävlingen är avslutad.';
		this.finishedText = '<p class="countdown-finished">' + finishedText + '</p>';
	
		var tmp = '';
		if (typeof(alt) != 'undefined') {
			tmp = '<div class="countdown-alt">';
			alt.split(",").each(function(a,x) {
				tmp = tmp + '<span class="a-'+ x + '">' + a + '</span>';
			});
			tmp = tmp + '</div>';
		}
		
		document.write('<div id="countdown-' + this.id +  '"><div class="countdown"></div>' + tmp + '</div>');
			
		this.timer();
  },

  calc: function(num, num2) {
	  s = ((Math.floor(this.secs / num)) % num2).toString();
	  if (s.length < 2) s = "0" + s;
	  return '<span class="countdown-num">' + s + '</span>';
  },
  
  refresh: function() {
  	var e = $('countdown-' + this.id).childElements().first();
  
  	if (this.secs < 0) {
  		e.update(this.finishedText);
  		e.nextSibling.hide();
  		return;
  	}
  	
  	var str = this.text
  	str = str.replace(/%%D/g, this.calc(86400, 100000));
  	str = str.replace(/%%H/g, this.calc(3600,24));
  	str = str.replace(/%%M/g, this.calc(60,60));
  	str = str.replace(/%%S/g, this.calc(1,60));
  	
  	e.update(str);
  	
  	setTimeout(function() { this.refresh(this.secs--); }.bind(this), 1000);
  },
  
  timer: function() {
		var then = new Date(this.toDate.substring(0,4), this.toDate.substring(5,7)-1, this.toDate.substring(8,10), this.toDate.substring(11,13),  this.toDate.substring(14,16));
		var now = new Date();
		var dateDelta = new Date(then - now);
		this.secs = Math.floor(dateDelta.valueOf() / 1000);
		
		this.refresh();
  }
});
