var game;
function initGame(board, xcells, ycells) {
    setTimeout("window.scrollTo(0,1);", 100);
    game = new Game(board, xcells, ycells);
}

function Game(board, width, height) {
    this.board = board;
    this.width = width;
    this.height = height;
    this.cellWidth = Math.floor(board.clientWidth / width - 2 - 2);
    this.cellHeight = Math.floor(board.clientHeight / height - 2 - 2);
    this.cells = new Array(height);
    this.active = 0;
    var thisGame = this;
	for (var y = 0; y < height; y++) {
        this.cells[y] = new Array(width);
		for (var x = 0; x < width; x++) {
            var cell = document.createElement("div");
            cell.setAttribute("class", "cell");
            cell.style.left = x * this.cellWidth;
            cell.style.top = y * this.cellHeight;
            cell.style.width = this.cellWidth;
            cell.style.height = this.cellHeight;
            cell.addEventListener("mousedown", function(){thisGame.cellClick(event);})
            board.appendChild(cell);
            cell.celly = y;
            cell.cellx = x;
            this.cells[y][x] = cell;
        }
    }
	for (var y = 0; y < height; y++) {
		for (var x = 0; x < width; x++) {
            if (Math.random() < 0.5)
				this.flip(x, y);
        }
    }
}

Game.prototype = {
    cellClick: function(event) {
        var targetDiv = event.target;
        var cellx = targetDiv.cellx;
        var celly = targetDiv.celly;
        this.flip(cellx, celly);
        if (this.active == 0) alert("winner!");
    },
    flip: function(x, y) {
        var targetCell = this.cells[y][x];
        if (x > 0)
            this.toggle(this.cells[y][x - 1]);
        if (x < this.width - 1)
            this.toggle(this.cells[y][x + 1]);
        if (y > 0)
            this.toggle(this.cells[y - 1][x]);
        if (y < this.height - 1)
            this.toggle(this.cells[y + 1][x]);
        this.toggle(targetCell);
    },
    toggle: function(cell) {
		if (cell.getAttribute("active") == "true") {
			cell.setAttribute("active", "false");
			this.active--;
		} else {
			cell.setAttribute("active", "true");
			this.active++;
		}
	}
}