var timeRemaining;
var countDownTimer;
var refreshTimer;
$(document).ready(function(){
	//console.log('wtf');
	var logToConsole = false;
	var countDownInterval = 1000;

	var logme = function(val) {
		if(logToConsole) {
			console.log(val);
		}
	};
	var addZeroes = function(value) {
		if(value < 10) {
			return "0" + value;
		} else {
			return value;
		}
	};
	refreshHeader = function(timeToRefresh) {
		timeToRefresh = (timeToRefresh) * 1000;
		logme('timeToRefresh: '+timeToRefresh);
		refreshTimer = setTimeout("refreshHeaderNow()", timeToRefresh);
	};
	// actually need this guy ;_;
	refreshHeaderNow = function() {
		//clearTimeout(refreshTimer);
		//clearInterval(countDownTimer);
		logme('refreshHeaderNow called');
		$('#header').empty();
		$('#header').load('/radio/header');
		//setTimeout("$('#ajaxRefresh').click(function(){refreshHeaderNow();return false;});", 0);
	}
	updateTimeRemaining = function(timeToDisplay) {
		var timeMins = addZeroes(Math.floor(timeToDisplay / 60));
		var timeSecs = addZeroes(timeToDisplay % 60);
		timeRemaining = timeRemaining - 1;
		if(timeRemaining < 0) {
			timeRemaining = 30;
			timeMins = '00';
			timeSecs = '30';
		}
		if(timeRemaining == 0) {
			clearInterval(countDownTimer);
		} else {
			//logme('timeRemaining is now: '+timeRemaining);
			$('#timeRemaining').empty();
			$('#timeRemaining').append(timeMins+':'+timeSecs);
		}
	};
	var countingDown = function() {
		logme('countingDown called');
		logme('countDownInterval: '+countDownInterval);
		//if(countDownTimer) { clearInterval(countDownTimer); }
		countDownTimer = setInterval("updateTimeRemaining(timeRemaining)", countDownInterval);
	};
	var resetAll = function() {
		logme('resetAll called');
		clearTimeout(refreshTimer);
		clearInterval(countDownTimer);
		timeRemaining = 0;
		countDownEnabled = false;
		setTimeout("countDownEnabled = parseInt($('#countDownEnabled').val())", 0);
		//logme('reset value -> countDownEnabled: '+countDownEnabled);
		setTimeout("timeRemaining = parseInt($('#timeRemain').val())", 0);
		setTimeout("refreshHeader(timeRemaining)", 0);
		countingDown();
	}

	logme('document is ready');
	var countDownEnabled = parseInt($('#countDownEnabled').val());
	logme('initial value -> countDownEnabled: '+countDownEnabled);
	$("#header").ajaxComplete(resetAll);
	if(countDownEnabled == 1) {
		timeRemaining = parseInt($('#timeRemain').val());
		logme('initial value -> timeRemaining: '+timeRemaining);
		refreshHeader(timeRemaining);
		countingDown();
	}

});