/* KHV countdown to entry deadline widget */

//Get Current Date in UTC
var d = new Date();
var utcMonth = d.getUTCMonth();
var utcDay = d.getUTCDate();
var utcHours = d.getUTCHours();
var utcMinutes = d.getUTCMinutes();
var utcSeconds = d.getUTCSeconds();

//Set's the current date and the end date based on GMT(aka UTC)  
var startDate = Date.UTC(2012, utcMonth, utcDay, utcHours, utcMinutes, utcSeconds);
var endDate = Date.UTC(2012, 2, 3, 22, 00, 00);

//Convert from milliseconds to seconds and convert to EST time
var timeInSeconds = (endDate - startDate) / 1000;
var estTime = timeInSeconds + 18000;

//Countdown function
var khvCountdown = function() {
	var continueCount = 1;
	
	//If continueCount == 1, continue counting
	function timeSet() {
		document.getElementById('khv-countdown-num').innerHTML = timeOutput();
	}
	
	//If timer equals 1, set continue count to zero to stop timer
	function countdown() {
		if(timeLeft < 1) {
			continueCount = 0;
		}
 
		timeLeft = timeLeft - 1;
	}
	
	//Get the days, hours, minutes, etc... from total seconds left
	function timeOutput() {
		var days = Math.floor(timeLeft / 86400);
		var hours = Math.floor(timeLeft / 3600) % 24;
		var minutes = Math.floor(timeLeft / 60) % 60;
		var seconds = timeLeft % 60;
		
		days = leadingZero(days);
		hours = leadingZero(hours);
		minutes = leadingZero(minutes);
		seconds = leadingZero(seconds);
		
		return '<span>' + days + '</span><span>' + hours + '</span><span>' + minutes + '</span><span>' + seconds + '</span>';
	}
	
	//If countinueCount == 0, function below is run
	function timeEnd() {
		document.getElementById('khv-countdown-widget').innerHTML = '<h1 class="timer-closed">Voting Open!!!</h1>'
	}
	
	// If the number is less than 2 digits, add a leading zero
	function leadingZero(number) {
		if(number.toString().length < 2) {
			return '0' + number;
		} else {
			return number;
		}
	}
	
	return {
		count: function () {
			countdown();
			timeSet();
		},
		timer: function () {
			khvCountdown.count();
 
			if(continueCount) {
				setTimeout("khvCountdown.timer();", 1000);
			} else {
				timeEnd();
			}
		},
		init: function (sec) {
			timeLeft = sec;
			khvCountdown.timer();
		}
	};
}();

//Passes the amount of seconds into above function to begin countdown
khvCountdown.init(estTime);
