/**
 * Created by Benjamin on 2/23/2016.
 */
var animspeed = 100;

var player1 = true;

var board = [
	[0, 0, 0],
	[0, 0, 0],
	[0, 0, 0]
];

var diagonalBoard = [
	[1, 1], [1, 3],
	[2, 2],
	[3, 1], [3, 3]
];

$(document).ready(function ()
{
	$('.blank').hover(
		function ()
		{
			if ($(this).attr('class') === 'blank')
			{
				$(this).animate({
					opacity: '.5'
				}, animspeed);
			}
		},
		function ()
		{
			if ($(this).attr('class') === 'blank')
			{
				$(this).animate({
					opacity: '0'
				}, animspeed);
			}
		});

	$('.blank').click(
		function ()
		{
			if (player1 && $(this).attr('class') === 'blank')
			{
				$(this).attr('class', 'player');
				$(this).animate({
					opacity: '1'
				}, 1);
				$('.blank').css('background-color', 'blue');
				player1 = false;
				UpdateBoard($(this).attr('id'), 1);
			}
			else if ($(this).attr('class') === 'blank')
			{
				$(this).attr('class', 'opponent');
				$(this).animate({
					opacity: '1'
				}, 1);
				$('.blank').css('background-color', 'green');
				player1 = true;
				UpdateBoard($(this).attr('id'), 2);
			}
		}
	);
});

function UpdateBoard(val, player)
{
	var tile = val.split("");
	board[tile[0]][tile[1]] = player;
	if (CheckBoard(tile, player))
	{
		alert("Player " + player + " won!");
	}
	else
	{
		console.log("No change of win state");
	}
}

/**
 * @param tile
 * @param player
 * @return {boolean}
 * @constructor
 */
function CheckBoard(tile, player)
{
	var win = 0;
	for (var i = 0; i < 3; i++)
	{
		//Check the row of the selected tile
		if (board[tile[0]][i] != player)
		{
			break;
		}
		win++;
	}
	if (win == 3)
	{
		return true;
	}
	win = 0;
	for (i = 0; i < 3; i++)
	{
		//Check the column of the selected tile
		if (board[i][tile[0]] != player)
		{
			break;
		}
		win++;
	}
	if (win == 3)
	{
		return true;
	}
	win = 0;

	if (isInArray(tile, diagonalBoard))
	{
		//Check diagonal row
		var x = tile[0];
		var y = tile[1];
		var ychange = 1;
		if (tile != [2, 2])
		{
			if (tile === [1, 3] || tile === [3, 3]) ychange = -1;
			for (i = 0; i < 2; i++)
			{
				x += 1;
				if (x > 3) x = 1;

				y += ychange;
				if (y > 3) y = 1;
				else if (y < 1) y = 3;

				if (board[x][y] != player)
				{
					break;
				}
				win++;
			}
		}
	}

	if (win === 3)
	{
		return true;
	}
	return false;
}

function isInArray(value, array)
{
	return array.indexOf(value) > -1;
}