/**
 * Countdown
 */

(function($){

	var MS_DAYS = 86400000,
		MS_HOURS = 3600000,
		MS_MINS = 60000,
		MS_SEC = 1000;
	
	function Countdown(node, settings) {
		this.date = settings.to;

		this.days = $('div.days', node);
		this.hours = $('div.hours', node);
		this.minutes = $('div.min', node);
//		this.seconds = $('span.seconds', node);

		var self = this;
		setInterval(function(){
			self.tick();
		}, 1000);

		this.tick();
	}

	Countdown.prototype = {
		tick:function() {
			var now = new Date();
			var remaining = Math.max(this.date - now, 0);

			var days = Math.floor(remaining / MS_DAYS);   remaining -= days * MS_DAYS;
			var hours = Math.floor(remaining / MS_HOURS); remaining -= hours * MS_HOURS;
			var mins = Math.floor(remaining / MS_MINS);   remaining -= mins * MS_MINS;
			//var sec = Math.floor(remaining / MS_SEC);

			this.days.html(this.pad(days));
			this.hours.html(this.pad(hours));
			this.minutes.html(this.pad(mins));
			//this.seconds.html(this.pad(sec));
		},

		pad:function(nr, l) {
			return /[0-9]{2}$/.exec('00' + nr)[0];
		}
	}

	$.fn.countdown = function(settings) {
		for(var i=0; i<this.length; i++) {
			new Countdown(this[i], settings);
		}
		return this;
	}

})(jQuery);