var refreshInterval = 15;
var ticking = false;

function refreshPage(){
	window.location.reload();
}

function updateScore( json ){
	if( json.html ){
		$('body div').html( json.html );
	} else {
		setTimeout( refreshPage, 5000 );
	}
}

function ajaxScore(){
	$.ajax({
		dataType: 'json',
		success: updateScore,
		url: '/'
	});
	setTimeout( ajaxScore, (refreshInterval * 1000) );
}

function plural( number, word ){
	if( number == 1 ){
		return word;
	} else {
		return word+'s';
	}
}

function updateCountdown(){
	var difference, days, hours, minutes;

	now += refreshInterval;
	
	difference = next-now;
	
	days = Math.floor( difference / 60 / 60 / 24 );
	hours = Math.floor( (difference - days * 60 * 60 * 24) / 60 / 60 );
	minutes = Math.floor( (difference - days * 60 * 60 * 24 - hours * 60 * 60) / 60 );
	
	if( difference < 0 ){
		result = $('#countdown strong').html();
	} else if( days > 0 ){
		result = '<em>'+days+'</em> '+plural(days, 'day')+', <em>'+hours+'</em> '+plural(hours, 'hour')+', <em>'+minutes+'</em> '+plural(minutes, 'minute');
	} else if( hours > 0 ){
		result = '<em>'+hours+'</em> '+plural(hours, 'hour')+', <em>'+minutes+'</em> '+plural(minutes, 'minute');
	} else if( minutes > 0 ){
		result = '<em>'+minutes+'</em> '+plural(minutes, 'minute');
	} else {
		result = $('#countdown strong').html();
	}
	
	$('#countdown strong').html( result );
	
	if( difference >= 0 ){
		// countdown to game - update clock in 15 secs
		ticking = true;
		setTimeout( updateCountdown, (refreshInterval * 1000) );	
	} else if( difference < 0 ){
		// game is being played or waiting for game to start
		$countdown = $('h1#countdown');
		setTimeout( ajaxScore, (refreshInterval * 1000) );
	}
}

// execute js
$(window).load(function(){
	// set up ajax score refresh as long as there is a game happening or coming up
	if( next ) updateCountdown();
});