var animCount = 0;
var interval;
var animInProgress = false;

var gridGame = {
	init : function () {
		var cells = document.getElementById('grid').getElementsByTagName('span');
		var y=0;
		var x=0;
		if (!historyPage) {
			for (var i=0; i<cells.length; i++) {
				cells[i].coordX = x;
				cells[i].coordY = y;
				cells[i].id = 'x' + x + 'y' + y;
				if (gridState[x][y] == 0)
					cells[i].className = 'white';
				else
					cells[i].className = 'black';
				x++;
				if ((i+1)%32 == 0) {
					y++;
					x = 0;
				}
				cells[i].onclick = function (e) {
					document.getElementById('coordX').value = this.coordX;
					document.getElementById('coordY').value = this.coordY;
					document.getElementById('gridForm').submit();
				};
			}
		} else {
			for (var i=0; i<cells.length; i++) {
				cells[i].coordX = x;
				cells[i].coordY = y;
				cells[i].id = 'x' + x + 'y' + y;
				x++;
				if ((i+1)%32 == 0) {
					y++;
					x = 0;
				}
			}
			document.getElementById('playHistory').onclick = function (e) {gridGame.replay(); return false;};
			for (var i=1; i<gridHistory.length; i++) {
				if (document.getElementById('x' + gridHistory[i].x + 'y' + gridHistory[i].y).className == 'white')
					document.getElementById('x' + gridHistory[i].x + 'y' + gridHistory[i].y).className = 'black';
				else 
					document.getElementById('x' + gridHistory[i].x + 'y' + gridHistory[i].y).className = 'white';
			}
		}
		document.getElementById('goals').onchange = function (e) {
			if (this.value != 'current') {
				document.getElementById('goalForm').action = "/games/grid/history/" + this.value;
				document.getElementById('goalForm').submit();
			}
		};
	},
	
	replay : function () {
		var cells = document.getElementById('grid').getElementsByTagName('span');
		for (var i=0; i<cells.length; i++) {
			cells[i].className = "white";
		}
		if (!animInProgress) {
			var cells = document.getElementById('grid').getElementsByTagName('span');
			animCount = 1;
			animInProgress = true;
			interval = window.setInterval(gridGame.animate,200);
		}	
	},
	
	animate : function () {
		// Set color from history
		
		if (document.getElementById('x' + gridHistory[animCount].x + 'y' + gridHistory[animCount].y).className == 'white')
			document.getElementById('x' + gridHistory[animCount].x + 'y' + gridHistory[animCount].y).className = 'black';
		else 
			document.getElementById('x' + gridHistory[animCount].x + 'y' + gridHistory[animCount].y).className = 'white';
			
		document.getElementById('move_by').innerHTML = 'Move ' + animCount + ' by ' + gridHistory[animCount].who;

		animCount++;
		if (animCount == gridHistory.length) {
			clearInterval(interval);
			animInProgress = false;	
		}
	}
}

gridGame.init();
