var pitsPerSide = 6;
var startingSeedsPerPit = 4;
var delay = 500;
var opponent = 0;
var player = 1;
var numLevelsToExamine = 2;

var adPercentage = 0.50		//Percentage of time to show ads before game.

var automaticPlay = false;
var autoRestart = false;			//Used for endless loop testing.

var pitObjs;
var pitCounts;

var statusBarObj;
var opponentStoreObj;
var opponentSeedsInPlayObj;
var opponentScoreObj;
var playerStoreObj;
var playerSeedsInPlayObj;
var playerScoreObj;

var gameOver = false;
var moveInProgress;
var extraTurn = false;
var initialized = false;
var currentMover = player;

var curPane;

function switchPane(newPaneId)
{
  curPane.style.display = "none";
//  eval(curPane.id + '_exit()');
  curPane = document.getElementById(newPaneId);
//  eval(curPane.id + '_enter()');
  curPane.style.display = "block";
}

function showAds()
{
	var showAd = (Math.random() <= adPercentage);
	if (showAd)
	{
  	// Using time as a query param to defeat browser caching.
  	var currentTime = new Date(); 
    googleAdFrame.location = "rps_googleAds.html?x=" + currentTime.getTime(); 
		switchPane("ads");
	}
	else
	{
		switchPane("gameBoard");
	}
}


function init()
{
	var restartButton = document.getElementById("newGame");
	restartButton.style.display="none";

	curPane = document.getElementById("gameBoard");
	showAds();
	
	pitObjs = new Array();
	pitCounts = new Array();

  pitObjs[0] = new Array();
  pitObjs[1] = new Array();
	pitCounts[0] = new Array();
	pitCounts[1] = new Array();

    for (var i = 0; i <= pitsPerSide; i++)
	{
      pitObjs[0][i] = document.getElementById("topPitCount_" + i);
      pitObjs[1][i] = document.getElementById("bottomPitCount_" + i);
	}

	statusBarObj = document.getElementById("statusBar");
	opponentStoreObj = document.getElementById("opponentStore");
	opponentSeedsInPlayObj = document.getElementById("opponentSeedsInPlay");
	opponentScoreObj = document.getElementById("opponentScore");
	playerStoreObj = document.getElementById("playerStore");
	playerSeedsInPlayObj = document.getElementById("playerSeedsInPlay");
	playerScoreObj = document.getElementById("playerScore");

	for(var i=1 ; i<=pitsPerSide ; i++)
	{
		//Set the staritng counts in the pits.
		pitCounts[0][i] = startingSeedsPerPit;
		pitCounts[1][i] = startingSeedsPerPit;

		updatePit(0,i);
		updatePit(1,i);
	}
	//Reset the stores to 0.
	pitCounts[0][0] = 0;
	pitCounts[1][0] = 0;
	updatePit(0,0);
	updatePit(1,0);
	
	updateScores();

	setInnerText(statusBarObj, "Your turn.");

  gameOver = false;
  moveInProgress = false;
  initialized = true;
  
  if (automaticPlay) makeMove();

  return;
}

function setInnerText( obj, newText )
{
	if (obj.innerText != undefined) {
		// Works for IE and Safari.
		obj.innerText = "" + newText;
	} else if ( obj.textContent != undefined ) {
		// Works for Firefox.
		obj.textContent = "" + newText;
	}
}

function updatePit(row, pit, value)
{
	var myVal = (value == null) ? pitCounts[row][pit] : value;
	setInnerText(pitObjs[row][pit], myVal);
}

function updatePitColor(row, pit, color)
{
	pitObjs[row][pit].style.color = color;
}

function handleClick(pitIndex)
{
	if (initialized && !moveInProgress)
	{
		if (!gameOver)
		{
			if (currentMover == opponent)
			{
				setInnerText(statusBarObj, "Invalid move. It's your opponent's turn.");
			}
			else
			{
				handleMove(pitIndex);
			}
		}
		else
		{
			setInnerText(statusBarObj, "Game over. ");
			alert("Game is already over.");
		}
	}
}


function handleMove(pitIndex)
{
	var pitObj = pitObjs[currentMover][pitIndex];
	var seeds = parseInt( (pitObj.innerText != undefined) ? pitObj.innerText : pitObj.textContent );
	var currentPit;
	var currentRow;
	var flipDelay = 0;
	
	if (seeds > 0)
	{
		var origColor;

		moveInProgess = true;
		setInnerText(statusBarObj, "moving...");

		currentRow = currentMover;
		pitCounts[currentRow][pitIndex] = 0;
		updatePit(currentRow, pitIndex);
		currentPit = pitIndex;
		
		if (currentMover == opponent)
		{
			var origClassName = pitObjs[currentRow][pitIndex].className;
			pitObjs[currentRow][pitIndex].className += ' picked';
			setTimeout("pitObjs[" + currentRow + "][" + pitIndex + "].className = '" + origClassName + "'", (delay*2));
		}
		
		while (seeds > 0)
		{
			if( (currentPit == 0) || (currentPit == 1 && currentRow != currentMover))
			{
				currentPit = pitsPerSide;
				currentRow = (currentRow == opponent) ? player : opponent;
			}
			else
			{
				currentPit--;
			}

			origColor = pitObjs[currentRow][currentPit].style.color;
			pitCounts[currentRow][currentPit]++;
			setTimeout("updatePit(" + currentRow + ", " + currentPit + ", " + pitCounts[currentRow][currentPit] + ")", flipDelay);
			setTimeout("updatePitColor(" + currentRow + ", " + currentPit + ", 'white')", flipDelay);
			flipDelay += delay;
			setTimeout("updatePitColor(" + currentRow + ", " + currentPit + ", '" + origColor + "')", flipDelay);
			seeds--;
		}

		flipDelay += delay;
		setTimeout("updatePitColor(" + currentRow + ", " + currentPit + ", '" + origColor + "')", flipDelay);
		
		if (currentPit != 0)
		{
			var opposingPit = pitsPerSide - currentPit + 1;
			var opposingRow = (currentMover == player) ? opponent : player;
			
			if (currentRow == currentMover && (pitCounts[currentRow][currentPit] == 1 && pitCounts[opposingRow][opposingPit] > 0) )
			{
				//var capturedSeeds = pitCounts[opposingRow][currentPit] + pitCounts[currentRow][opposingPit];
				var capturedSeeds = pitCounts[currentRow][currentPit] + pitCounts[opposingRow][opposingPit];

				origColor = pitObjs[opposingRow][opposingPit].style.color;

				flipDelay += delay;
				setTimeout("setInnerText(statusBarObj, 'captured stones!')", flipDelay);
				setTimeout("updatePitColor(" + opposingRow + ", " + opposingPit + ", 'white')", flipDelay);
				setTimeout("updatePitColor(" + currentRow + ", " + currentPit + ", 'white')", flipDelay);
				pitCounts[opposingRow][opposingPit] = pitCounts[currentRow][currentPit]= 0;
				setTimeout("updatePit(" + opposingRow + "," + opposingPit + ")", flipDelay);
				setTimeout("updatePit(" + currentRow + "," + currentPit + ")", flipDelay);

				flipDelay += delay;
				setTimeout("updatePitColor(" + opposingRow + ", " + opposingPit + ", '" + origColor + "')", flipDelay);
				setTimeout("updatePitColor(" + currentRow + ", " + currentPit + ", '" + origColor + "')", flipDelay);
				setTimeout("updatePitColor(" + currentRow + ", 0, 'white')", flipDelay);
				pitCounts[currentRow][0] += capturedSeeds;
				setTimeout("updatePit(" + currentRow + ",0)", flipDelay);

				flipDelay += delay;
				setTimeout("updatePitColor(" + currentRow + ", 0, '" + origColor + "')", flipDelay);
			}
			currentMover = (currentMover == player) ? opponent : player;
			if (currentMover == opponent) 
			{
				setTimeout("setInnerText(statusBarObj, 'waiting on opponent...')", flipDelay);
			}
		}
		else
		{
			setTimeout("setInnerText(statusBarObj, 'extra turn!')", flipDelay);
		}
		flipDelay += delay;
		setTimeout("endTurn()", flipDelay);
    }
}

function endTurn()
{
	moveInProgress = false;
	updateScores();

	if (!gameOver)
	{
		var playerPitSum = sumPits(pitCounts[player]);
		var opponentPitSum = sumPits(pitCounts[opponent]);
		if ( playerPitSum == 0 || opponentPitSum == 0 )
		{
			// Game is over.
			gameOver = true;
			var playerScore = pitCounts[player][0] + playerPitSum;
			var opponentScore = pitCounts[opponent][0] + opponentPitSum;
			
			var winner = null;
			if (playerScore != opponentScore)
			{
				winner = (playerScore > opponentScore) ? player : opponent;
			}
			
			var statusText = "game over!";
			statusText += (winner == null) ? " tie game!" : "";
			statusText += (winner == player) ? " you\'re a winner!" : " you\'re a loser!";
			setInnerText(statusBarObj, statusText);

			if (autoRestart)
				init();
			else
			{
				var restartButton = document.getElementById("newGame");
				restartButton.style.display="block";
			}
		}
		else
		{
			if (currentMover == opponent)
			{
				setInnerText(statusBarObj, "waiting on opponent...");
				makeMove();
			}
			else
			{
				setInnerText(statusBarObj, 'your move.');
				if (automaticPlay) makeMove();
			}
		}
	}
}

function updateScores()
{
	var opponentScore;
	var playerScore;
	var opponentStore = pitCounts[opponent][0];
	var playerStore = pitCounts[player][0];
	var opponentSeedsInPlay = 0;
	var playerSeedsInPlay = 0;

	opponentSeedsInPlay = sumPits(pitCounts[opponent]);
	opponentScore = opponentStore + opponentSeedsInPlay;
	playerSeedsInPlay = sumPits(pitCounts[player]);
	playerScore = playerStore + playerSeedsInPlay;

	setInnerText(opponentStoreObj, opponentStore);
	setInnerText(playerStoreObj, playerStore);
	setInnerText(opponentSeedsInPlayObj, opponentSeedsInPlay);
	setInnerText(playerSeedsInPlayObj, playerSeedsInPlay);
	setInnerText(opponentScoreObj, opponentScore);
	setInnerText(playerScoreObj, playerScore);
	if ( (playerScore + opponentScore) != (pitsPerSide * 2 * startingSeedsPerPit) ) alert("Invalid score!");
}

function sumPits(pitArray)
{
	var value = 0;
	for (var i=1 ; i<=pitsPerSide ; i++)
	{
		value += pitArray[i];
	}
	return value;
}

function makeMove()
{
	var move = findMove(currentMover, numLevelsToExamine, pitCounts);
	handleMove(move[0]);
}

function findMove(mover, numLevels, passedPitCounts)
{
	var returnValue;
	var seeds;
	var currentRow;
	var currentPit;
	var tmpBest;
	var tmpScore = Number.NEGATIVE_INFINITY;
	var bestScore = Number.NEGATIVE_INFINITY;
    var bestPit = new Array();
    var bestCounts = new Array();
	var opposingPlayer = (mover == player) ? opponent : player;

	
	for(var i=1 ; i <= pitsPerSide ; i++)
	{
		var opposingRow;
		var opposingPit;
		var tmpPitCounts = new Array();
		tmpPitCounts[opponent] = passedPitCounts[opponent].slice();
		tmpPitCounts[player] = passedPitCounts[player].slice();
		
		if (tmpPitCounts[mover][i] > 0)
		{
			seeds = tmpPitCounts[mover][i];
			tmpPitCounts[mover][i] = 0;
			currentRow = mover;
			currentPit = i;
			
			while (seeds > 0)
			{
				// If we're done counting down a row, switch sides.
				if ( (currentPit == 0) || ( currentPit == 1 && currentRow != mover ) )
				{
					currentPit = pitsPerSide;
					currentRow = (currentRow == player) ? opponent : player;
				}
				else
				{
					currentPit--;
				}
				tmpPitCounts[currentRow][currentPit]++;
				seeds--;
			}

			opposingRow = (currentRow == player) ? opponent : player;
			opposingPit = (pitsPerSide - currentPit) + 1;
			if (currentPit != 0)
			{
				if (currentRow == mover && tmpPitCounts[currentRow][currentPit] == 1 && tmpPitCounts[opposingRow][opposingPit] > 0)
				{					
					tmpPitCounts[currentRow][0] += (tmpPitCounts[currentRow][currentPit] + tmpPitCounts[opposingRow][opposingPit]);
					tmpPitCounts[currentRow][currentPit] = 0;
					tmpPitCounts[opposingRow][opposingPit] = 0;
				}
				
			}
			else
			{
				// Extra move, so calculate next move to take into account when scoring.
				tmpBest = findMove(mover, numLevels, tmpPitCounts);
				if (tmpBest[0] != -1)
					tmpPitCounts = tmpBest[2];
			}
			
			if (numLevels > 0)
			{
				tmpBest = findMove(opposingPlayer, (numLevels - 1), tmpPitCounts);
//				tmpScore = (tmpBest[0] != -1) ? (tmpBest[1] * -1) : (tmpPitCounts[mover][0] - tmpPitCounts[opposingPlayer][0]);
				tmpScore = (tmpBest[0] != -1) ? (tmpBest[1] * -1) : Number.NEGATIVE_INFINITY;
			}
/*
			else
			{
				tmpScore = tmpPitCounts[mover][0] - tmpPitCounts[opposingPlayer][0];
			}
*/
			if (tmpScore == Number.NEGATIVE_INFINITY)
			{
				var totalMoverScore = tmpPitCounts[mover][0] + sumPits(tmpPitCounts[mover]);
				var totalOpponentScore = tmpPitCounts[opposingPlayer][0] + sumPits(tmpPitCounts[opposingPlayer]);
				tmpScore = totalMoverScore - totalOpponentScore;
			}

			if (tmpScore > bestScore)
			{
				bestScore = tmpScore;
				bestPit = new Array();
				bestPit[0] = i;
				bestCounts[0] = tmpPitCounts;
			}
			else if (tmpScore == bestScore)
			{
				bestPit[bestPit.length] = i;
				bestCounts[bestCounts.length] = tmpPitCounts;
			}

		}
	}

	returnValue = new Array();
	returnValue[1] = bestScore;
	if (bestPit.length > 0)
	{
		var randomChoice = Math.floor(Math.random() * bestPit.length);
		returnValue[0] = bestPit[randomChoice];
		returnValue[2] = bestCounts[randomChoice];
	}
	else
	{
		returnValue[0] = -1;
		returnValue[2] = null;
	}
	
	return(returnValue);
}


