/**
 * UI functions for Othello game
 * @author Tommi Laukkanen
 * http://www.substanceofcode.com
 */

function setButton(pos, color) {
	//alert('position ' + pos);
	var cell = $('#button' + pos);
	if (color.length > 0) {
		cell.html('<img src="img/' + color + '_button.png"/>');
	} else {
		cell.html('');
	}
}

function setWhite(x,y) {
	setButton(String(x) + String(y), 'white');
}

function setBlack(x,y) {
	setButton(String(x) + String(y), 'black');
}

function setBlank(x,y) {
	setButton(String(x) + String(y), '');
}

function drawBoard() {
	for(var y=0; y<8; y++) {
		for(var x=0; x<8; x++) {
			var cellValue = game.getBoard(x, y);
			switch(cellValue) {
				case 0:
					setWhite( x, y);
					break;
				case 1:
					setBlack( x, y);
					break;
				default: 
					setBlank( x, y);
			}
		}
	}
	var blackScore = game.getScore(1);
	var whiteScore = game.getScore(0);
	$('#score').text("Black " + blackScore + ' - White ' + whiteScore);
}

function checkGameOver() {
	if(game.gameIsNotOver==false) {
		$('#status').text('Game Over!');
	}
}

function computerTurn() {
	// Computer turn
	$('#status').text('Computer is thinking hard...');
	game.turn(-1,-1);
	$('#status').text('Your turn');
	checkGameOver();
	drawBoard();
}

/** Cell is clicked with mouse */
function cellClick() {
	var x = this.id.substring(6,7);
	var y = this.id.substring(7,8);
	// User turn
	game.turn(x,y);
	drawBoard();
	$('#status').text('Computer is thinking...');
	var f = setTimeout('computerTurn();',200);
}

function initializeGame() {
	game = new OthelloGame();	
	game.initGame();
	game.setGame( true );	
}

function resetGame() {
	initializeGame();
	drawBoard();
	$('#status').text('Your turn');
}

function buildBoard() {
	
	// Initialize game logic
	initializeGame();
	
	// Create board
	var board = document.getElementById('board');
	for(var i=0;i<8;i++) {
		var boardRow = document.createElement('tr');
		boardRow.className = 'boardRow';
		for(var j=0;j<8; j++) {
			
			var cell = document.createElement('td');
			cell.className = 'boardCell';
			cell.id = 'cell' + j + i;
			
			var cellButton = document.createElement('div');
			cellButton.className = 'cellButton';
			cellButton.id = 'button' + j + i;
			cellButton.addEventListener('click', cellClick, false);
			
			cell.appendChild( cellButton );
			
			boardRow.appendChild( cell );
		}
		board.appendChild( boardRow );
	}
	
	// Reset link
	var resetMenu = document.getElementById('resetAction');
	resetMenu.addEventListener('click', resetGame, false)
	
	// Draw board
	drawBoard();
}







