// JavaScript Document
function init() {
	game = false;
	total = 0;
	times = 14; 
	speed = 700; 
	possible = 0;
	
	var st = document.getElementById("st");
	st.value = "Start";
	st.onclick = start;
	
	var sc = document.getElementById("score");
	sc.value = 0;
	
	var ti = document.getElementById("time");
	ti.value = times;
	
	gameInit();
}
	
function start() {
	var st = document.getElementById("st"); 
	game = confirm("Are you ready to start the game?!");
	if (game) {
		st.value = "Stop";
		st.onclick = stops;
		gameStart();
	}
}

function stops() {
	var re = document.getElementById("report");
	var correct = document.getElementById("score").value;
	re.innerHTML = "You have scored " + correct + "/" + possible + " from " + total + " clicks";
	init();
}

function gameInit() {
	var boxes = document.getElementsByTagName("td");
	for (var i=0; i<boxes.length; i++) boxes[i].onclick = check;
}
	
function check() {
	if (game) {
		total++;
		var box = this;
		global =box;
		if (box.style.backgroundColor == "yellowgreen") {
			var sc = document.getElementById("score");
			sc.value = parseInt(sc.value) + 1;
		}
		else {
			box.style.backgroundColor = "red";
			setTimeout('global.style.backgroundColor = "white"', 200);
		}
	}
}

function timing() {
	if (game) {
		var ti = document.getElementById("time");
		var t = parseInt(ti.value);
		if (t > 0) {
			ti.value = t -1;
			setTimeout('timing()', 1000);
		}
		else stops();
	}
}

function gameStart() {
	var re = document.getElementById("report");
	re.innerHTML = "";
	setTimeout('timing()', 200);
	setTimeout('highlightBox()', 200);
}
	
function highlightBox()
{
	if (game) {
		possible++;
		var box = getRandom();
		global1 = box;
		box.style.backgroundColor = "yellowgreen";
		setTimeout('global1.style.backgroundColor = "white"',speed);
		setTimeout('highlightBox()',speed);
	}
}

function getRandom() {
	var boxes = document.getElementsByTagName("td");
	var range = boxes.length;
	var t;
	do {
		t = Math.round(Math.random()*range);
	} while ((t<0) || (t>=range));
	return boxes[t];
}

window.onload = init;		
