/* JQuery Countdown Script By Adam McCann <adam.mccann@videogamer.com>
 * Options:
 *  - countTo: Target date
 * 	- detail: Which level of detail to show (1 = weeks, 2 = days, 3 = hours, 4 = mins, 5 = secs)
 *	- prefix: Prefix of class to update the counter
 *  - callback: Optional callback function to execute once countdown has reached zero
 */
jQuery.fn.countdown = function(options) {
	if(!options) return;
	if(!options.detail) options.detail = 5; // default max detail
	if(!options.prefix) options.prefix = 'countdown';
	var obj = this;
	var countTo = (options.countTo / 1000);
	var timeNow = ((new Date()).getTime() / 1000); 
	var secs = Math.round(countTo - timeNow);
	var weeks,days,hours,mins,secs;
	
	// break out and execute callback (if any)
	if (secs < 0 || secs == 'undefined') {
		if(options.callback) eval(options.callback);
		return null;
	}
	// extract various units from seconds (such as hours)
	function extractDate(period) {
		var unit = Math.floor(secs / period);
		secs -= unit * period;
		return unit;
	}
	// pad number with zeros
	function pad(value, length) {
		value = String(value);
		length = parseInt(length) || 2;
		while (value.length < length)
			value = '0' + value;
		if (value<1) value = '00';
		return value;
    }; 

	// recursive countdown
	window.setTimeout(
		function() {
			$('.' + options.prefix + 'Weeks').html( (options.detail==5) ? pad(extractDate(604800), 2) : 0 );
			$('.' + options.prefix + 'Days').html( (options.detail>=4) ? pad(extractDate(86400), 2) : 0 );
			$('.' + options.prefix + 'Hours').html( (options.detail>=3) ? pad(extractDate(3600), 2) : 0 );
			$('.' + options.prefix + 'Mins').html( (options.detail>=2) ? pad(extractDate(60), 2) : 0 );
			$('.' + options.prefix + 'Secs').html( (options.detail>=1) ? pad(extractDate(1), 2) : 0 );
			secs--;
			jQuery(obj).countdown(options);
		}
		, 980
	);
	
    return this;
}