/**
* JS Minesweeper
*
* © Peter Bonnett 2006
* www.pete-b.co.uk
*/
//Initial Vars
var endGame = false;
var GRID_SIZE = 9;
var NUM_MINES = 10;
var BLANK = "\u00a0";
var IE_BLANK = "&nbsp;";
var flag = false;
var total = 0;
var start = false;
var timerID = null;
var clockTimer = 0;

var colors = new Array();
colors[0] = "";
colors[1] = "Blue";
colors[2] = "Green";
colors[3] = "Red";
colors[4] = "#000080";
colors[5] = "#800000";
colors[6] = "#008080";
colors[7] = "#000000";
colors[8] = "#808080";


var squaresLeft = (GRID_SIZE*GRID_SIZE) - NUM_MINES;
//Create the grid
var grid = new Array(GRID_SIZE);

//Initialise the grid fully
function resetGrid() {
	for(var i=0; i<grid.length; i++) {
		grid[i] = new Array(GRID_SIZE);
		for(var j=0; j<grid[i].length; j++) {
			grid[i][j] = " ";
		}
	}
	//var buttonGrid = document.getElementById("gameArea");
	for (i=0; i<GRID_SIZE; i++) {
		for (j=0; j<GRID_SIZE; j++) {
			var button = document.getElementById("B" + i + "," + j);
			button.value = BLANK;
			button.firstChild.nodeValue = BLANK;
			button.disabled=false;
			button.style.color = colors[0];
			
		}
	}
	alterTotal(-total);
	placeMines();
}

//Create the array of buttons
function prepareBoard() {
	var buttonGrid = document.getElementById("gameArea");
	for (i=0; i<GRID_SIZE; i++) {
		for (j=0; j<GRID_SIZE; j++) {
			var button = document.createElement("BUTTON");
			button.setAttribute("value", BLANK);
			button.setAttribute("id", "B" + i + "," + j);
			var text = document.createTextNode("");
			button.appendChild(text);
			//Adds event listeners using browser detect
			if(button.attachEvent) {
				button.attachEvent("onclick", guess);
			} else {
				button.addEventListener("click", guess, false);
			}
			buttonGrid.appendChild(button);
		}
		var lineBreak = document.createElement("BR");
		buttonGrid.appendChild(lineBreak);
	}
	
	
	resetGrid();
	alterTotal(0);
	document.getElementById("clock").value = clockTimer;
}

function alterTotal(add) {
	total += add;
	document.getElementById("mineTally").firstChild.nodeValue = total + "/" + NUM_MINES;
}

function placeMines() {
	//alert(NUM_MINES);
	//Randomly place the mines
	for(var i=0; i<NUM_MINES; i++) {
		var x = -1;
		var y = x;
		//Make sure the mines are going where a mine already exists
		while((x == -1) || (grid[x][y] == "X")) {
			x = Math.floor(Math.random() * GRID_SIZE);
			y = Math.floor(Math.random() * GRID_SIZE);
		}
		grid[x][y] = "X";
	}
	
	//Work out how many mines are near each location
	for(var i=0; i<grid.length; i++) {
		for(var j=0; j<grid[i].length; j++) {
			//Skip if it's a mine
			if(grid[i][j] == "X") {
				continue;
			}
			var count = 0;
			
			//Work out what is in each square around i,j
			for(var x=-1; x<2; x++) {
				for(var y=-1; y<2; y++) {
					if((x==0 && y==0) || ((i+x)<0) || ((y+j)<0) || ((i+x)>=GRID_SIZE) || ((j+y)>=GRID_SIZE)) {
						continue;
					}
					if(grid[(i+x)][(j+y)] == "X") {
						count++;
					}
				}
			}
			grid[i][j] = count;
		}
	}			
}

//Build the grid with mines and mine location details
function debugGrid(game) {
	//Output the grid
	game.grid.value = "";
	for(var i=0; i<grid.length; i++) {
		for(var j=0; j<grid[i].length; j++) {
			game.grid.value += "" + grid[i][j] + " ";
		}
		game.grid.value += "\r\n";
	}
	return false;
}

function startTheClock() {
	if(start) {
		var clock = document.getElementById("clock");
		clock.value = ++clockTimer;
		//setInterval(startTheClock(), 1000);
		timerID = self.setTimeout("startTheClock()", 1000)
	}
}

function guess(e) {
	if(endGame) {
		alert("The game has ended. Please click the restart button");
		return ;
	}
	if(!start) {
		start = true;
		startTheClock()
	}
	var id = "";
	//Fixes oddness with attachEvent / addWindowListener, browser detection to get src element
	if(e.target) {
		id = e.target.id;
	} else {
		id = window.event.srcElement.id;
		
	}
	var button = document.getElementById(id);
	if(((button.value == BLANK) || (button.value == IE_BLANK)) && flag) {
		document.getElementById(id).value="?";
		document.getElementById(id).firstChild.nodeValue = "?";
		alterTotal(1);
		return ;
	}
	
	if((button.value == "?") && flag) {
		return ;
	}
	
	var coords = id.substring(1).split(",");
	var x = coords[0];
	var y = coords[1];
	
	if(grid[x][y] == "X") {
		endGame = true;
		start = false;
		clearTimeout(timerID);
		//alert("Whoops, you selected a mine, you lose");
	}
	
	if(((button.value == BLANK) || (button.value == IE_BLANK)) || (button.value == "?")) {
		if(button.value == "?") {
			alterTotal(-1);
		}
		var result = grid[x][y];
		button.value = result;
		button.firstChild.nodeValue = result;
		
		if(result == 0) {
			clearZeros(x*1,y*1);
			button.disabled=true;
			button.value = "0";
			button.firstChild.nodeValue = "0";
		} else {
			button.style.color = colors[result];
		}
		if(endGame) {
			return ;
		}
		squaresLeft--;
		if(squaresLeft == 0) {
			start = false;
			clearTimeout(timerID);
			alert("You win");
			endGame = true;
		}
	}
}

function clearZeros(i,j) {
	for(var x=-1; x<2; x++) {
		for(var y=-1; y<2; y++) {
			if((x==0 && y==0) || ((i+x)<0) || ((y+j)<0) || ((i+x)>=GRID_SIZE) || ((j+y)>=GRID_SIZE)) {
				continue;
			}
			var result = grid[(i+x)][(j+y)];
			var ref = "B" + (i+x) + "," + (j+y);
			var button = document.getElementById(ref);
			if(((button.value == BLANK) || (button.value == IE_BLANK)) && !button.disabled) {
				button.value = result;
				button.firstChild.nodeValue = result;
				squaresLeft--;
				if(result == "0") {
					button.disabled=true;
					button.value = "0";
					button.firstChild.nodeValue = "0";
					clearZeros((i+x),(j+y));
				} else {
					button.style.color = colors[result];
				}
			}
		}
	}
}

function setFlag() {
	flag = document.getElementById("flag").checked;
//	flag = !flag;
}

//Reset the UI, then reinitialise the game
function resetGame(game) {
	squaresLeft = (GRID_SIZE*GRID_SIZE) - NUM_MINES;
	clockTimer = 0;
	start = false;
	clearTimeout(timerID);
	endGame = false;
	resetGrid();
}