var points, board, interval, elCounter;

function init()
{
	interval = setInterval('countDown()', 1000);
	elCounter = document.getElementById('time').firstChild;

	board = new Array();
	var elBoard = document.getElementById('game');
    while(elBoard.hasChildNodes()) elBoard.removeChild(elBoard.firstChild);
	var frozenX, elTr, x;
	for(var y = 0; y < 6; y++) {
		elTr = document.createElement('tr');
		frozenX = Math.floor(Math.random() * 6); //one frozen cell per row
		if (y == 0 && frozenX == 0) frozenX = -1; //start cannot be frozen
		if (y == 5 && frozenX == 5) frozenX = -1; //finish cannot be frozen
		board[y] = new Array();
		for(x = 0; x < 6; x++){
			board[y][x] = elTr.appendChild(makeTd(frozenX == x, y == 0));
		}
		elBoard.appendChild(elTr);
	}
}

if (window.addEventListener)
	window.addEventListener('load', init, false);
else
	window.onload = init;

var gameColors = {liquid: '#f00', solid: '#000', frozenSolid: '#500', frozenLiquid: '#c00', flodded: '#00f'};

function makeTd(frozen, topRow)
{
	var elTd = document.createElement('td');
	//50:50 on solid or liquid, but no solids in top row
	elTd.substance = frozen ? (Math.random() < 0.5 && !topRow ? gameColors.frozenSolid : gameColors.frozenLiquid) : gameColors.liquid;
	elTd.style.width = '40px';
	elTd.style.height = '40px';
	elTd.style.backgroundColor = elTd.substance;
	if (!frozen) {
		if (elTd.addEventListener)
			elTd.addEventListener('click', chk, false);
		else
			elTd.onclick = chk;
	}
	//gameBoard += '<td id="i' + x + 'i' + y + '" onclick="chk(' + x + ',' + y + ')">&nbsp;<\/td>'
	return elTd;
}

function chk()
{
	if (elCounter.nodeValue > 0) { //if is a number - if game is on
		this.substance = this.substance == gameColors.liquid ? gameColors.solid : gameColors.liquid;
		this.style.backgroundColor = this.substance;
	}
}

function countDown()
{
	if(--elCounter.nodeValue == 0){
		points = 0;
		flow(0, 0);
		clearInterval(interval);
		elCounter.nodeValue = board[5][5].substance == gameColors.flodded ? 'Du fik ' + points + ' point!' : 'Du fuldførte ikke!';
	}
}

function flow(x, y) {
	if(x < 0 || y < 0 || x > 5 || y > 5) return false;
	if(board[y][x].substance == gameColors.frozenSolid || board[y][x].substance == gameColors.solid) return false;
	if(board[y][x].substance == gameColors.flodded) return true;
	board[y][x].substance = gameColors.flodded;
	board[y][x].style.backgroundColor = gameColors.flodded;
	points++;
	if(!flow(x, y + 1)){
		flow(x + 1, y);
		flow(x - 1, y);
	}
	return true;
}

