var gamePos = 0;
var goBoard;
var wrapper;

function changeCell(xpos, ypos, newValue) {
	var row = goBoard.childNodes[ypos];
	var cell = row.childNodes[xpos];
	cell.className = newValue;
}

function emptyIntersection(xpos, ypos) {
	if (xpos == 0) {
		if (ypos == 0)
			return "TL";
		if (ypos == 18)
			return "BL";
		return "L";
	}
	if (xpos == 18) {
		if (ypos == 0)
			return "TR";
		if (ypos == 18)
			return "BR";
		return "R";
	}
	if (ypos == 0)
		return "T";
	if (ypos == 18)
		return "B";
	if ((xpos == 3 || xpos == 9 || xpos == 15) && (ypos == 3 || ypos == 9 || ypos == 15))
		return "Star";
	return "NoStar";
}

function changePosition(pos) {
	if (pos < 0)
		pos = 0;
	if (pos > game.length)
		pos = game.length;
	while (gamePos < pos) {
		var k = game[gamePos++];
		changeCell(k.x, k.y, gamePos % 2 ? "Black" : "White");
		if (k.r)
			for (var i = 0; i < k.r.length; ++i)
				changeCell(k.r[i].x, k.r[i].y, emptyIntersection(k.r[i].x, k.r[i].y));
	}
	while (gamePos > pos) {
		var k = game[--gamePos];
		changeCell(k.x, k.y, emptyIntersection(k.x, k.y));
		if (k.r)
			for (var i = 0; i < k.r.length; ++i)
				changeCell(k.r[i].x, k.r[i].y, gamePos % 2 ? "Black" : "White");
	}
}

function updateMouse(event) {
	event = event || window.event;  // IE hack
	if (event.clientY < (goBoard.offsetTop + goBoard.offsetHeight))  // Owen's hack because he was sick of the board changing
		changePosition(Math.floor((event.clientX-20-wrapper.offsetLeft)*game.length/728));  // non-standard
}

function createBoard() {
	wrapper = document.getElementById("wrapper");
	goBoard = document.getElementById("goban");
	for (var i = 0; i < 19; ++i) {
		var row = document.createElement("div");
		row.className = "boardRow";
		for (var j = 0; j < 19; ++j) {
			var cell = document.createElement("div");
			cell.className = emptyIntersection(j,i);
			row.appendChild(cell);
		}
		goBoard.appendChild(row);
	}
	document.onmousemove = updateMouse;  // non-standard
	changePosition(game.length)  // Default to game finished
}

window.onload = createBoard;  // non-standard

