(function ($) {

$.fn.extend ({
	countdown : function (settings) {
		settings = $.extend ({
			'until' : '+1day',
			'locale' : 'es'
		}, settings);

		return this.each (function () {
			$(this).data ('countdown', new $.countdown ($(this), settings));
		});
	}
});

$.countdown = function (elem, until) {
	this.init (elem, until);
};

$.countdownLang = {
	'es' : {
		'days' : 'Días',
		'hours' : 'Horas',
		'mins' : 'Minutos',
		'secs' : 'Segundos'
	},
	'en' : {
		'days' : 'Days',
		'hours' : 'Hours',
		'mins' : 'Minutes',
		'secs' : 'Seconds'
	}
};

$.extend ($.countdown.prototype, {
	'elem' : null,
	'days' : null,
	'hours' : null,
	'mins' : null,
	'secs' : null,
	'until' : null,
	'dateUntil' : null,
	'settings' : {},
	'clock' : {
		'days' : 0,
		'hours' : 0,
		'mins' : 0,
		'secs' : 0
	},
	'init' : function (elem, settings) {
		this.elem = elem;
		this.settings = settings;
		this.markup ();
		this.setUntil (settings.until);
	},
	'markup' : function () {
		this.elem.empty ().addClass ('countdown');
		for (key in this.clock) {
			this.elem.append (
				$('<div>').addClass ('countdown-' + key).append (
					$('<div>').addClass ('countdown-flip'),
					this[key] = $('<div>').addClass ('countdown-' + key + '-text countdown-text').text (00),
					$('<div>').addClass ('countdown-' + key + '-label countdown-label').text ($.countdownLang[this.settings.locale][key])
				)
			);
		}
	},
	'setUntil' : function (until) {
		this.until = until;
		this.dateUntil = new Date (this.until);
		this.refresh ();
	},
	'refresh' : function () {
		var t = this, now = new Date (), value = 0, amount = t.dateUntil.getTime () - now.getTime () + 5;

		clearTimeout (this.timeout);

		if (amount > 0) {
			amount = Math.floor (amount / 1000);
			this.clock.days  = Math.floor (amount / 86400);
			this.clock.hours = Math.floor ((amount %= 86400) / 3600);
			this.clock.mins  = Math.floor ((amount %= 3600) / 60);
			this.clock.secs  = Math.floor (amount %= 60);
		}

		for (key in this.clock) {
			value = this.clock[key];
			this[key].text ((Number (value) < 10 ? '0' : 0) + value);
		}

		this.timeout = setTimeout (function () { t.refresh (); }, 1000);
		this.elem.trigger ({
			'type' : 'countdownrefresh',
			'clock' : this.clock,
			'now' : now
		});
	}
});

})(jQuery);
