/*

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, 14 May 2010 17:55:08 -0400</div>
Note: time should be in ISO 8601 format

*/

	var countDown = {};
	countDown.list = [];
	countDown._parseTimeLeft = function(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};
	}
	
	countDown._pad = function(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;
	}
	
	countDown._write = function(elm, timeLeft){
		var output = '';
		if(timeLeft.days){
			output = output + ' ' + timeLeft.days + ' days';
		}
		if(timeLeft.hours){
			output = output + ' ' + timeLeft.hours + ' hours';
		}
		if(timeLeft.minutes){
			output = output + ' ' + timeLeft.minutes + ' min';
		}
		output = output + ' ' + timeLeft.seconds + ' sec';
		$(elm).html(output);
	}

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

	countDown.apply = function(scope){
		var me = this;
		if(!scope) scope = document;
		$('.count-down', scope).each(function(i, item){
			var target = Date.parse($(this).text());
			me.list.push({elm: item, targetTime: target, completeText: this.title});
			this.title = '';
		});
		this._tick();
		this.tickHandle = setInterval(this._tick, 1000);
	}
	
$(function(){
	countDown.apply();
});
