(function($) {
	$.fn.countdown = function(opts) {
		var defaults = {
			duration: 15, // seconds
			complete: null
		};
		var options = $.extend(defaults, opts);
		
		return this.each(function(i, item) {
			var item = $(item);
			clearInterval($.data(item, 'countdown.timer'));
			$.data(item, 'countdown.seconds', options.duration);
			item.text(options.duration);

			var timer = setInterval(function() {
				var seconds = $.data(item, 'countdown.seconds');
				seconds--;
				if (seconds >= 0) {
					$.data(item, 'countdown.seconds', seconds);
					item.text(seconds);
				} else {
					clearInterval($.data(item, 'countdown.timer'));
					$.removeData(item, 'countdown.timer');
					$.removeData(item, 'countdown.seconds');
					if (options.complete) {
						options.complete(this);
					}
				}
			}, 1000);
			$.data(item, 'countdown.timer', timer);
		});
	};
})(jQuery);

