﻿////////////////////////////////////////////////////////////////////
/// UI.js
/// © 2007 Carl Johansen
/// 
/// User Interface for Reversi game.
////////////////////////////////////////////////////////////////////

var IMG_CTRL_PREFIX = "ctl00_ContentPlaceHolder1_"

function InitGame()
{
    theBoard = GetInitializedBoard();
    evalWeight = GetInitializedEvaluator();
    UpdateScreenBoard();
    document.getElementById("lblScore").innerHTML = "<span>White: 2, Black: 2</span>";
    
    currPlayer = WhitePlayer;
    
    GetStartButton().onclick = StartGame;
    GetStartButton().disabled = false;    
    GetResetButton().onclick = InitGame;
    GetResetButton().disabled = true;    
}

function GetStartButton()
{
    return document.getElementById("cmdStart");
}

function GetResetButton()
{
    return document.getElementById("cmdReset");
}

//---------------------------------------------------------------------------------------

function StartGame()
{
    var validMoves;
    var selWhite = document.getElementById("selWhite");
    var selBlack = document.getElementById("selBlack");
    
    document.getElementById("cmdStart").value = "Stop";
    document.getElementById("cmdReset").disabled = true;
    document.getElementById("cmdStart").onclick = StopGame;
    
    ShowPlayerUp();
    
    playerType[WhitePlayer] = selWhite.options[selWhite.selectedIndex].value;
    playerType[BlackPlayer] = selBlack.options[selBlack.selectedIndex].value;
    
    selWhite.disabled = true;
    selBlack.disabled = true;
    
    if(playerType[currPlayer] == ComputerPlayerType)
        ScheduleComputerMove();
    else
    {
        validMoves = GetValidMoveList(theBoard, currPlayer);
        SetRolloversForValidMoves(validMoves);
    }
}

//---------------------------------------------------------------------------------------

function StopGame()
{
    window.clearInterval(intCompMoveIntervalID);
    ClearRollovers();
    ClearPlayerUpDisplay();
    GetStartButton().value = "Start";
    GetStartButton().onclick = StartGame;
    GetResetButton().disabled = false;
    var selWhite = document.getElementById("selWhite");
    var selBlack = document.getElementById("selBlack");
    selWhite.disabled = false;
    selBlack.disabled = false;
}

//---------------------------------------------------------------------------------------

function StopGameWithNoResume()
{
    StopGame();
    GetStartButton().disabled = true;
}

//---------------------------------------------------------------------------------------

function OnComputerMove()
{
    window.clearInterval(intCompMoveIntervalID);
    var computerMove = ChooseMove(theBoard, currPlayer);
    if(computerMove.Row == -1)
        alert("Computer cannot move (this message should not normally appear!)");
    else
        ApplyMoveAndSwitchPlayerUp(computerMove.Row, computerMove.Col);
}

//---------------------------------------------------------------------------------------

function OnPlayerMove(e)
{
    var sourceElement = (e ? e.target : window.event.srcElement);
    var cellID = sourceElement.id;
    var theRow = parseInt(cellID.substr(cellID.length - 2, 1));
    var theCol = parseInt(cellID.substr(cellID.length - 1, 1));
    if(IsValidMove(theBoard, theRow, theCol, currPlayer))
        ApplyMoveAndSwitchPlayerUp(theRow, theCol);
}

//---------------------------------------------------------------------------------------

function ApplyMoveAndSwitchPlayerUp(moveRow, moveCol)
{
	//Applies the player's move (assumes it is valid), carries out post-move actions and switches the current player
    
    ClearRollovers();
    ApplyMove(theBoard, moveRow, moveCol, currPlayer);
    UpdateScreenBoard();
    
    //Update the scoreboard
    var squareCount = GetSquareCount(theBoard);
	document.getElementById("lblScore").innerHTML = "<span>" + "White: " + squareCount.NumWhite + ", Black: " + squareCount.NumBlack + "</span>";
    //Check for game over
    if(squareCount.NumEmpty == 0)
    {
        alert("Game Over");
        StopGameWithNoResume();
        return;
    }
    
    //Switch current player.
    currPlayer = GetOpponent(currPlayer);
    ShowPlayerUp();
    
    validMoves = GetValidMoveList(theBoard, currPlayer);    
    //Check for new player forfeit.
    if(validMoves.NumValidMoves == 0)
    {
        var strMsg = (playerType[currPlayer] == ComputerPlayerType ? "Computer" : "Player");
        strMsg += " (" + ColourName(currPlayer) + ") cannot move.";
        alert(strMsg);
        //Back to the other player.
        currPlayer = GetOpponent(currPlayer);
        ShowPlayerUp();
        validMoves = GetValidMoveList(theBoard, currPlayer);
        if(validMoves.NumValidMoves == 0)
         {
            //Original player can't move either - it's all over.
            alert("Game Over (no moves left).");
            StopGameWithNoResume();
            return;
         }
    }
    
    if(playerType[currPlayer] == ComputerPlayerType)
        ScheduleComputerMove();
    else
        SetRolloversForValidMoves(validMoves);       
}

//---------------------------------------------------------------------------------------

function UpdateScreenBoard()
{
    var currRow, currCol;
    
    for(currRow = 1; currRow <= BOARD_SIZE; currRow++)
        for(currCol = 1; currCol <= BOARD_SIZE; currCol++)
        {
            var currSquare = document.getElementById(IMG_CTRL_PREFIX + "img" + currRow + currCol);
            if(theBoard[currRow][currCol] == WhitePlayer)
            {
                if(currSquare.src != "whitesquare.gif")
                    currSquare.src = "whitesquare.gif";
            }
            else if(theBoard[currRow][currCol] == BlackPlayer)
            {
                if(currSquare.src != "blacksquare.gif")
                    currSquare.src = "blacksquare.gif";
            }
            else
            {
                if(currSquare.src != "emptysquare.gif")
                    currSquare.src = "emptysquare.gif";
            }                    
        }
}

//---------------------------------------------------------------------------------------

function HighlightSquareForPlayerMove(e)
{
    var sourceElement = (e ? e.target : window.event.srcElement);
    var strHighlightGif = (currPlayer == WhitePlayer ? "whitesquare.gif" : "blacksquare.gif");
    sourceElement.src = strHighlightGif;
}

//---------------------------------------------------------------------------------------

function UnhighlightSquare(e)
{
    var sourceElement = (e ? e.target : window.event.srcElement);
    sourceElement.src = "emptysquare.gif";
}

//---------------------------------------------------------------------------------------

function ClearRollovers()
{
    var intRow, intCol;
    
    for(intRow = 1; intRow <= BOARD_SIZE; intRow++)
        for(intCol = 1; intCol <= BOARD_SIZE; intCol++)
        {
            var squareElement = document.getElementById(IMG_CTRL_PREFIX + "img" + intRow + intCol);
            squareElement.onmouseover = null;
            squareElement.onmouseout = null;
            squareElement.onclick = null;
        }
}

//---------------------------------------------------------------------------------------

function SetRolloversForValidMoves(validMoves)
{
    ClearRollovers();
    var i;
    for(i = 0; i < validMoves.NumValidMoves; i++)
    {
        intRow = validMoves.ValidMoves[0][i];
        intCol = validMoves.ValidMoves[1][i];
        var squareElement = document.getElementById(IMG_CTRL_PREFIX + "img" + intRow + intCol);
        squareElement.onmouseover = HighlightSquareForPlayerMove;
        squareElement.onmouseout = UnhighlightSquare;
        squareElement.onclick = OnPlayerMove;
    }
}

//---------------------------------------------------------------------------------------

function ColourName(playerColour)
{
    return (playerColour == WhitePlayer ? "White" : "Black");
}

//---------------------------------------------------------------------------------------

function ShowPlayerUp()
{
    document.getElementById("lblPlayerUp").innerHTML = "<span>" + ColourName(currPlayer) + " to move" + "</span>";
}

//---------------------------------------------------------------------------------------

function ClearPlayerUpDisplay()
{
    document.getElementById("lblPlayerUp").innerHTML = "";
}

//---------------------------------------------------------------------------------------

function ScheduleComputerMove()
{
    //The computer moves so quickly that we need a delay to make it look like it's thinking...
    intCompMoveIntervalID = window.setInterval("OnComputerMove()", 350);
}
