var tick_length, run_time, start_bufer, end_buffer, tick, secsleft, height, errorTimer;

// Function to display the timer
function timer()
{
	run_time++;

	tick=Math.floor(run_time/tick_length);

	secsleft = ((tick+1)*tick_length) - run_time;

	hrs = Math.floor(secsleft/3600);
	min = Math.floor(secsleft/60) % 60;
	sec = secsleft % 60;

	if (secsleft <= end_buffer || tick_length - start_buffer <= secsleft)
	{
		document.getElementById("timer").style.color='red';
	}

	else
	{
		document.getElementById("timer").style.color='white';
	}

	document.getElementById('tick').innerHTML = tick;
	document.getElementById('hours').innerHTML = hrs;
	document.getElementById('minutes').innerHTML = (min < 10) ? "0"+min : min;
	document.getElementById('seconds').innerHTML = (sec < 10) ? "0"+sec : sec;

}

// Initial function to set variables and start timer
function startTimer(tick, run, start, end)
{
	// Set variables passed from server
	tick_length = tick;
	run_time = run;
	start_buffer = start;
	end_buffer = end;

	// Start timer
	timer();
	setInterval(timer, 1000);

	// Periodically correct the timer if ajax supported
	setTimeout(UpdateTimer, 10000);
	setInterval(UpdateTimer, 600000);
	
	// Periodically check for new comms if in game
	if (document.getElementById("comms") != null)
	{
		setInterval('UpdatePage("comms", "/comms_check.php")', 60000);
	}
}

// Function to update the timer
function UpdateTimer()
{
	var ajax = new CreateAjaxObject();
	ajax.onreadystatechange = function()
	{
		if(ajax.readyState == 4 && ajax.status == 200)
		{
			run_time = ajax.responseText;
		}
	}
	
	ajax.open("GET", "/timer.php", true);
	ajax.send(null);
}

// Function to return an Ajax object
function CreateAjaxObject()
{
	try
	{
		// Firefox, Opera 8.0+, Safari
		return new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			return new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			return new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
}

function UpdatePage(id, page)
{
	var ajax = new CreateAjaxObject();
	original = document.getElementById(id).innerHTML;
	// Display ajax loader if not a comm check
	if (page != "/comms_check.php")
	{
		document.getElementById(id).innerHTML = '<img src="/media/icons/ajax.gif" alt="please wait">';
	}

	ajax.onreadystatechange = function()
	{
		// Detect when server response received
		if(ajax.readyState == 4)
		{
			// Detect any response errors
			if (ajax.status != 200)
			{
				reportError('Error : Status '+ajax.status+' returned.<br/>'+ajax.responseText);
				document.getElementById(id).innerHTML = original;
			}

			// Get the reply and break it into tvs components
			text = ajax.responseText;
			line = text.split("</tvs>");

			// Show an error if the reply is not in tvs format
			if (line.length == 1)
			{
				reportError("There is an error in the response:<br/>"+text);
				document.getElementById(id).innerHTML = original;
			}

			// Process each component
			for (var i = 0; i < line.length - 1; i++)
			{
				// Determine element id
				component = line[i].substr(0, line[i].indexOf("="));

				// Display any errors
				if (component == "error")
				{
					reportError(line[i].substr(line[i].indexOf("=") + 1));
					continue;
				}

				// Show error if element does not exist
				if (document.getElementById(component) == null)
				{
					reportError("element " + component + " does not exist<br/>"+text);
					document.getElementById(id).innerHTML = original;
				}

				// Update the element
				document.getElementById(component).innerHTML = line[i].substr(line[i].indexOf("=") + 1);
			}

			// Remove ajax image if page has loaded
			if (document.getElementById(id).innerHTML.toLowerCase() == '<img src="/media/icons/ajax.gif" alt="please wait">') document.getElementById(id).innerHTML = original;
		}
	}

	ajax.open("GET", page, true);
	ajax.send(null);
}

// Function to display an error message
function reportError(text)
{
	// Set the error text
	document.getElementById("error").innerHTML = text;
	if (document.getElementById("error").scrollHeight > 350)
	{
		document.getElementById("error").style.overflowY = 'scroll';
	}
	height = 0;

	// Display the error
	moveError(1);
}

// Function to close a displayed error message
function closeError()
{
	clearTimeout(errorTimer);
	moveError(-1);
}

// Function to animate an error message
function moveError(interval)
{
	// Adjust the height each iteration
	height += interval;

	// Set the div to the new height
	document.getElementById("error").style.height = height+'px';

	// Determine the target height
	target = (document.getElementById("error").scrollHeight > 350) ? 350 : document.getElementById("error").scrollHeight;

	// Continue loop until offscreen or at the display height
	if (height > 0 && height < target)
	{
		errorTimer = window.setTimeout('moveError('+interval+')', 5);
	}
}

// Prevent ajax being used in the mobile version
if (window.$)
{
	$(document).bind("mobileinit", function() { $.mobile.ajaxEnabled = false; } );
}

