/**
 countdown script

 This script creates a countdown timer


*/

var CountDown = function () {
	var X;
	X = {
		nodePrefix: "countdown",
		endDate: null,
		initialized: false,
		startCount: function (opts) {
			if (X.initialized) {
				return;
			}
			X.initialized = true;
			for (var o in opts) {
				if (typeof(X[o] !== "undefined")) {
					X[o] = opts[o];	
				}
			}
			if (X.endDate !== null) {
				var targetDate = stringToTime(X.endDate);
				if(X.nodePrefix !== null){
					doCountdown(targetDate, X.nodePrefix);
				}
			}
		}
	};
	
	function stringToTime(timeString) {
		var matches = timeString.match(/^([0-9]{4,})-([0-9]{2,})-([0-9]{2,})(\s(([0-9]{2,}):([0-9]{2,}):([0-9]{2,})))?$/);
		if (matches) {
			var datum = new Date(matches[1],matches[2]-1,matches[3], 
				(typeof(matches[6]) == "undefined"?0:matches[6]),
				(typeof(matches[6]) == "undefined"?0:matches[7]),
				(typeof(matches[6]) == "undefined"?0:matches[8]));
			return datum.getTime()/1000;
		} else {
			return false;
		}
	}
	
	return X;
}();

function doCountdown(target, classPrefix) {
	var curr = new Date().getTime() / 1000;
	var timeLeft = target - curr;
	if (timeLeft > 0) { 
		var days = Math.floor((timeLeft)/(60 * 60 * 24));
		timeLeft %=  (60 * 60 * 24);
		var hours = Math.floor((timeLeft)/(60 * 60));
		timeLeft %= (60 * 60);
		var minutes = Math.floor((timeLeft)/(60));
		timeLeft %= 60;
		var seconds = Math.floor(timeLeft);
		document.getElementById(classPrefix + "_days").innerHTML = days;
		document.getElementById(classPrefix + "_hours").innerHTML = hours;
		document.getElementById(classPrefix + "_minutes").innerHTML = minutes;
		document.getElementById(classPrefix + "_seconds").innerHTML = seconds;
		
		setTimeout('doCountdown('+target+',"' + classPrefix + '");',100);
	} else {
		document.getElementById(classPrefix + "_days").innerHTML = 0;
		document.getElementById(classPrefix + "_hours").innerHTML = 0;
		document.getElementById(classPrefix + "_minutes").innerHTML = 0;
		document.getElementById(classPrefix + "_seconds").innerHTML = 0;
	}
}

function addLoadEvent(func) { 
	var oldonload = window.onload; 
	if (typeof window.onload != 'function') { 
		window.onload = func; 
	} else { 
		window.onload = function() { 
			if (oldonload) { 
				oldonload(); 
			} 
			func(); 
		} 
	} 
} 
