/*

Author: Jamie Beck <jbeck@terabit.ca>
Site: www.devcheater.com
Created: 2010-04-14
Modified: 2010-04-14

Example: <div class="count-down" title="Offer extended for a limited time">Fri, 18 Jun 2010 17:55:08 -0400</div>
Note: time should be in ISO 8601 format

*/

$(function(){
	var list = [];
	function _parseTimeLeft(millis){
		var days, hours, minutes, seconds, milliseconds;
		var whatsLeft = millis;
		days = Math.floor(whatsLeft/(24*60*60*1000));
		whatsLeft -= days*(24*60*60*1000);
		hours = Math.floor(whatsLeft/(60*60*1000));
		whatsLeft -= hours*(60*60*1000);
		minutes = Math.floor(whatsLeft/(60*1000));
		whatsLeft -= minutes*(60*1000);
		seconds = Math.floor(whatsLeft/(1000));
		whatsLeft -= seconds*(1000);
		milliseconds = whatsLeft;
		return {days: days, hours: hours, minutes: minutes, seconds: seconds, millis: milliseconds};
	}
	
	function _pad(target, length){
		var origLength = (target+'').length;
		if(origLength < length){
			var pad = '';
			for(i = origLength; i < length; i++){
				pad += '0';
			}
			target = pad.concat(target);
		}
		return target;
	}
	
	function _write(elm, timeLeft){
		$(elm).html(timeLeft.days + ' days ' + timeLeft.hours + ' hours ' + timeLeft.minutes + ' minutes ' + timeLeft.seconds + '.' + _pad(timeLeft.millis, 3) + ' seconds');
	}

	function _tick(){
		var timeLeft, numWrites = 0, now = (new Date()).getTime();
		for(i in list){
			timeLeft = list[i].targetTime - now;
			if(timeLeft > 0){
				_write(list[i].elm, _parseTimeLeft(timeLeft));
				numWrites++;
			}
			else{
				$(list[i].elm).html(list[i].completeText);
			}
		}
		if(numWrites == 0){
			clearInterval(tickHandle);	
		}
	}

	$('.count-down').each(function(i, item){
		var target = Date.parse($(this).text());
		list.push({elm: item, targetTime: target, completeText: this.title});
		this.title = '';
	});
	var tickHandle = setInterval(_tick, 71);
});