
var selectedMove = null;
var pgnString = null;
var pgnFileName = null;
var currentMove = 0;
var totalMoves = 0;
/**
 * Called when the script is loaded for the first time.
 **/
function GameInfo_Load()
{
	var container = this.GetElementByID("GameInfoContainer");
	container.innerHTML = "No game selected.";
}

/**
 * Clears the game info.
 **/
function GameInfo_MakeEmpty()
{
	var container = this.GetElementByID("GameInfoContainer");
	container.innerHTML = "No game selected.";
}

/**
 * Called when the info panel is about to receive a game update.
 * Shows the loading message.
 **/
function GameInfo_BeginUpdate()
{
	var container = this.GetElementByID("GameInfoContainer");
	container.innerHTML = "<img height=\"11\" class=\"gameInfoLoadingIcon\" src=\"Images/Controls/GameInfo/Loading.gif\" width=\"11\" />Loading...";
}

/**
 * Called when there is a game available to show in the control.
 **/
function GameInfo_DataAvailable(infoString)
{
	var infoFields = infoString.split('|');
	var container = this.GetElementByID("GameInfoContainer");
	
	if (infoFields[GAME_INFO_MOVES] == "") 
	{
		GameInfo_MakeEmpty();
		return;
	}
	
	var output = "";
	output += this.GameInfo_DrawStandardInfo(infoFields);
	output += this.GameInfo_DrawMoves(infoFields[GAME_INFO_MOVES]);

	this.GameInfo_GeneratePgnFile(infoFields);
	
	container.innerHTML = output;
	
	this.Panel_Show("GameInfoPanel");
}

/**
 * Outputs pgn string to PgnViewer.aspx
 **/
function GameInfo_DownloadPgnGameFile()
{
	var url = "PgnViewer.aspx?FileName=" + this.pgnFileName + "&Pgn=" + this.pgnString;

	location.href = url;
}
/**
 * Select the move at the specified index.
 **/
function GameInfo_SelectMove(moveIndex)
{
	if (this.selectedMove != null)
	{
		this.selectedMove.className = "";
	}

	if (moveIndex == 0) return;
	
	this.selectedMove = this.GetElementByID("Move" + (moveIndex-1));
	this.selectedMove.className = "moveSelected";
}

/**
 * Draws the standard info for a game.
 **/
function GameInfo_DrawStandardInfo(infoFields)
{
	var output = "";
	
	output += "<div id=\"GameInfoStandard\">";

	// If no header only print the PGN download button
	if (!GameInfo_GameHasHeader(infoFields))
	{
		output += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">";
		output += "<tr>";
		output += "<td>";
		output += "<b>" + infoFields[GAME_INFO_NICKEY_CODE] + "</b>&nbsp;&nbsp;";
		output += "</td>";
		output += "<td></td>";
		output += "<td align=\"right\">";
		output += "<a href=\"javascript:GameInfo_DownloadPgnGameFile()\">";
		output += "<img border=\"0\" class=\"imageButton\" onclick=\"GameInfo_DownloadPgnGameFile()\" src=\"../Common/Images/DownloadIcon.gif\" width=\"16\" height=\"16\" style=\"margin-right: 5px;\" alt=\"Download as PGN\" />";
		output += "</a>";
		output += "</td>";
		output += "</tr>";
		output += "</table>";
	
		output += "</div>";
		return output;
	}
	
	// NICKey and ECOKey
	output += "<b>" + infoFields[GAME_INFO_NICKEY_CODE] + "</b> (" + infoFields[GAME_INFO_ECOKEY_CODE] + ")";
	output += "<br />";
	
	output += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">";
	
	// White player row
	output += "<tr>";
	output += "<td>";
	output += "<img alt=\"White player\" height=\"11\" src=\"Images/Controls/GameInfo/White.gif\" width=\"11\" />&nbsp;&nbsp;";
	output += "<a href=\"javascript:Player_Click(" + infoFields[GAME_INFO_ID_WHITE] + ")\">";
	output += infoFields[GAME_INFO_FIRST_NAME_WHITE];
	output += " " + infoFields[GAME_INFO_LAST_NAME_WHITE];
	output += "</a>";
	output += "</td><td>";
	//
	if (infoFields[GAME_INFO_COUNTRY_CODE_WHITE] != "   ")
	{
		output += " <img height=\"10\" class=\"countryFlag\" src=\"Images/Controls/GameInfo/Flags/" + infoFields[GAME_INFO_COUNTRY_CODE_WHITE] + ".gif\" width=\"17\" alt=\""+ infoFields[GAME_INFO_COUNTRY_CODE_WHITE] + "\" />";
	}
	//
	output += "</td>";
	output += "<td align=\"right\">";
	output += infoFields[GAME_INFO_TITLE_WHITE] == "" ? "" : infoFields[GAME_INFO_TITLE_WHITE] + " ";
	output += infoFields[GAME_INFO_RANKING_WHITE] == "0" ? "-" : infoFields[GAME_INFO_RANKING_WHITE];
	output += "&nbsp;</td>";
	output += "</tr>";
	
	// Black player row
	output += "<tr>";
	output += "<td>";
	output += "<img alt=\"Black player\" height=\"11\" src=\"Images/Controls/GameInfo/Black.gif\" width=\"11\" />&nbsp;&nbsp;";
	output += "<a href=\"javascript:Player_Click(" + infoFields[GAME_INFO_ID_BLACK] + ")\">";
	output += infoFields[GAME_INFO_FIRST_NAME_BLACK];
	output += " " + infoFields[GAME_INFO_LAST_NAME_BLACK];
	output += "</a>";
	output += "</td><td>";
	//
	if (infoFields[GAME_INFO_COUNTRY_CODE_BLACK] != "   ")
	{
		output += " <img height=\"10\" class=\"countryFlag\" src=\"Images/Controls/GameInfo/Flags/" + infoFields[GAME_INFO_COUNTRY_CODE_BLACK] + ".gif\" width=\"17\" alt=\""+ infoFields[GAME_INFO_COUNTRY_CODE_BLACK] + "\" />";
	}
	//
	output += "</td>";
	output += "<td align=\"right\">";
	output += infoFields[GAME_INFO_TITLE_BLACK] == "" ? "" : infoFields[GAME_INFO_TITLE_BLACK] + " ";
	output += infoFields[GAME_INFO_RANKING_BLACK] == "0" ? "-" : infoFields[GAME_INFO_RANKING_BLACK];
	output += "&nbsp;</td>";
	output += "</tr>";

	output += "<tr>";
	output += "<td>";
	output += infoFields[GAME_INFO_PLACE] + " ";
	output += infoFields[GAME_INFO_DATE];
	output += " (" + infoFields[GAME_INFO_ROUND] + ")";
	output += "</td>";
	output += "<td>&nbsp;</td>";
	output += "<td align=\"right\">" + infoFields[GAME_INFO_RESULT] + "&nbsp;</td>";
	output += "</tr>";
	output += "</table>";

	// Source and PGN download row
	output += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">";
	output += "<tr>";
	output += "<td valign=\"top\" width=\"50\">Source:</td>";
	output += "<td>";
	output += this.GameInfo_FormatSource(infoFields);
	output += "</td>";
	output += "<td></td>";
	output += "<td align=\"right\">";
	output += "<a href=\"javascript:GameInfo_DownloadPgnGameFile()\">";
	output += "<img border=\"0\" class=\"imageButton\" onclick=\"GameInfo_DownloadPgnGameFile()\" src=\"../Common/Images/DownloadIcon.gif\" width=\"16\" height=\"16\" style=\"margin-right: 5px;\" alt=\"Download as PGN\" />";
	output += "</a>";
	output += "</td>";
	output += "</tr>";
	output += "</table>";

	output += "</div>";
	
	return output;
}

/**
 * Formats Magazine, Yearbook and General source with links to Archives and Shop
 **/
function GameInfo_FormatSource(infoFields)
{
	var sourceArray = new Array(3);
	
	var magazine = this.GameInfo_FormatMagazineSource(infoFields);
	var yearbook = this.GameInfo_FormatYearbookSource(infoFields);
	var generalSource = this.GameInfo_FormatGeneralSource(infoFields[GAME_INFO_SOURCE]);

	sourceArray[0] = magazine;
	sourceArray[1] = yearbook;
	sourceArray[2] = -1 //generalSource;
	
	var result = "";
	for (i = 0; i < sourceArray.length; i++)
	{
		if (sourceArray[i] != -1)
		{
			result += sourceArray[i] + "<br />";
		}
	}
	return result == "" ? "-" : result;
}

/**
 * Formats Magazine source with links to Archives and Shop
 **/
function GameInfo_FormatMagazineSource(infoFields)
{
	// Check if empty
	if (infoFields[GAME_INFO_MAGAZINE_ID] == "") return -1;
	
	var result = "";
	
	result += "<a href=\"../Archives/ArticlesList.aspx?MagazineID=" + infoFields[GAME_INFO_MAGAZINE_ID] + "\">";
	result += infoFields[GAME_INFO_MAGAZINE_NAME];
	result += "</a>";
	if (infoFields[GAME_INFO_MAGAZINE_PRODUCT_ID] != 0)
	{
		result += "&nbsp";
		result += "<a href=\"../Shop/ProductDetails.aspx?ProductID=" + infoFields[GAME_INFO_MAGAZINE_PRODUCT_ID] + "\">";
		result += "<img src=\"../Common/Images/BuyButton.gif\" alt=\"buy\" border=\"0\" />";
		result += "</a>";	
	}
	return result;
}

/**
 * Formats Yearbook source with links to Archives and Shop
 **/
function GameInfo_FormatYearbookSource(infoFields)
{
	// Check if empty
	if (infoFields[GAME_INFO_YEARBOOK_ID] == "") return -1;
	
	var result = "";
	
	result += "<a href=\"../Archives/SurveysList.aspx?YearbookID=" + infoFields[GAME_INFO_YEARBOOK_ID] + "\">";
	result += infoFields[GAME_INFO_YEARBOOK_NAME];
	result += "</a>";
	if (infoFields[GAME_INFO_YEARBOOK_PRODUCT_ID] != 0)
	{
		result += "&nbsp";
		result += "<a href=\"../Shop/ProductDetails.aspx?ProductID=" + infoFields[GAME_INFO_YEARBOOK_PRODUCT_ID] + "\">";
		result += "<img src=\"../Common/Images/BuyButton.gif\" alt=\"buy\" border=\"0\" />";
		result += "</a>";	
	}
	return result;
}

/**
 * Formats source (ex. Schaakbulletin, old Yearbooks, Informator, etc)
 **/
function GameInfo_FormatGeneralSource(sourceField)
{
	if (sourceField == "") return -1;

	var i;
	var sourceArray = sourceField.split(' ');
	
	for (i = 0; i < sourceArray.length; i++)
	{
		if (sourceArray[i].indexOf("SB") == 0)
		{
			sourceArray[i] = sourceArray[i].replace("SB", "Schaakbulletin");
		}
		else if (sourceArray[i].indexOf("IF") == 0)
		{
			sourceArray[i] = sourceArray[i].replace("IF", "Informator");
		}
		else
		{
			var b = sourceArray[i].split('-');
	
			if (b.length == 3)
			{
				sourceArray[i] = "Magazine " + b[0] + "/" + b[1] + " p." + b[2];
			}
			else if (b.length == 2)
			{
				sourceArray[i] = "Yearbook " + b[0] + " p." + b[1];
			}
		}
	}
	
	var result = "";
	for (i = 0; i < sourceArray.length; i++)
	{
		result += sourceArray[i] + "<br />";
	}
	
	return result;
}

function GameInfo_GameHasHeader(infoFields)
{
	// If no lastnames then header is probably empty
	return ((infoFields[GAME_INFO_LAST_NAME_WHITE] == "") &&
			(infoFields[GAME_INFO_LAST_NAME_BLACK] == "")) == false;
}

/**
 * Draws the moves info for a game.
 **/
function GameInfo_DrawMoves(moveString)
{
	var moves = moveString.split(' ');
	var output = "";
	var moveNumber = 0;
	

	for (var i = 0; i < moves.length - 1; i += 3)
	{
//		var move = moves[i];
		
//		if ((i % 2) == 0)
//		{
//			var split = move.split('.');
//			move = "<b>" + split[0] + "</b>." + split[1];	
//		}

//		output += "<nobr><a id=\"Move" + i + "\" href=\"javascript:Move_Click(" + (i + 1) + ")\">";
//		output += Figures_Replace(move, false);
//		output += "</a></nobr> ";


		moveNumber += 1;
		output += "<nobr><a id=\"Move" + (moveNumber-1) + "\" href=\"javascript:Move_Click(" + moveNumber + ")\">";
		output += "<b>" + moves[i] + "</b>";	
		output += Figures_Replace(moves[i+1], false);
		output += "</a></nobr> ";

		moveNumber += 1;
		output += "<nobr><a id=\"Move" + (moveNumber-1) + "\" href=\"javascript:Move_Click(" + moveNumber + ")\">";
		output += Figures_Replace(moves[i+2], false);
		output += "</a></nobr> ";
	}
	this.totalMoves = moveNumber-1;
	return output;
}


/**
 * Calculates the PlyCount (white + black moves)
 **/
function GameInfo_CalculatePlyCount(moveString)
{
	var moves = moveString.split(' ');
	var result = 0;
	
	for (var i = 0; i < moves.length - 1; i++)
	{	
		if (i % 3 != 0) result += 1;
	}
	
	return result;
}

/**
 * Set the PGN output string and FileName
 **/
function GameInfo_GeneratePgnFile(infoFields)
{
	var datearray = infoFields[GAME_INFO_DATE].split("-");
	var month = "??";
	var day = "??";
	var year = "????";
	if(datearray[0] != null)	year = datearray[0];
	if(datearray[1] != null)	
	{
		month = datearray[0];
		year = datearray[1];
	}
	if(datearray[2] != null)
	{
		day = datearray[0] < 10 ? "0" + datearray[0] : datearray[0];
		month = datearray[1] < 10 ? "0" + datearray[1] : datearray[1];
		year = datearray[2];
	}
	var output = "";
	
	var date = "" + year + "." + month + "." + day + "";
	var whitePlayer = infoFields[GAME_INFO_LAST_NAME_WHITE] + ", " + infoFields[GAME_INFO_FIRST_NAME_WHITE]
	var blackPlayer = infoFields[GAME_INFO_LAST_NAME_BLACK] + ", " + infoFields[GAME_INFO_FIRST_NAME_BLACK]
	var result = infoFields[GAME_INFO_RESULT];
	var round = infoFields[GAME_INFO_ROUND] != "0" ? infoFields[GAME_INFO_ROUND] : "?";
	var whiteTitle = infoFields[GAME_INFO_TITLE_WHITE];
	var blackTitle = infoFields[GAME_INFO_TITLE_BLACK];
	var whiteElo = infoFields[GAME_INFO_RANKING_WHITE] != "0" ? infoFields[GAME_INFO_RANKING_WHITE] : "";
	var blackElo = infoFields[GAME_INFO_RANKING_BLACK] != "0" ? infoFields[GAME_INFO_RANKING_BLACK] : "";
	var plyCount = GameInfo_CalculatePlyCount(infoFields[GAME_INFO_MOVES]);
	
	switch (result)
	{
		case "1-0":
		case "0-1":
			break;
		
		case "&frac12;-&frac12;":
			result = "1/2-1/2";
			break;
		
		default:
			result = "*";
			break;
	}
	
	// Headers
	output += "[Event \"" + infoFields[GAME_INFO_PLACE] + "\"]|";
	output += "[Site \"\"]|";
	output += "[Date \"" + date + "\"]|";
	output += "[Round \"" + round + "\"]|";
	output += "[White \"" + whitePlayer + "\"]|";
	output += "[Black \"" + blackPlayer + "\"]|";
	output += "[Result \"" + result + "\"]|";
	
	if (whiteTitle != "")
		output += "[WhiteTitle \"" + whiteTitle + "\"]|";

	if (blackTitle != "")
		output += "[BlackTitle \"" + blackTitle + "\"]|";

	if (whiteElo != "")
		output += "[WhiteElo \"" + whiteElo + "\"]|";
	
	if (blackElo != "")
		output += "[BlackElo \"" + blackElo + "\"]|";
	
	output += "[NIC \"" + infoFields[GAME_INFO_NICKEY_CODE] + "\"]|";
	output += "[ECO \"" + infoFields[GAME_INFO_ECOKEY_CODE] + "\"]|";
	output += "[PlyCount \"" + plyCount + "\"]||";

	// Game
	output += makeMoveString(infoFields[GAME_INFO_MOVES]);
	output += "" + result + "";

	this.pgnString = output;
	
	// Format fileName
	var fileName = infoFields[GAME_INFO_LAST_NAME_WHITE];
	fileName += "-" + infoFields[GAME_INFO_LAST_NAME_BLACK];
	fileName += "_" + infoFields[GAME_INFO_DATE];
	fileName += ".pgn";
	
	this.pgnFileName = fileName.length > 6 ? fileName : "NewGame.pgn";
}
function makeMoveString(moves)
{
	var counter = 0;
	var returnstring = "";
	for(i=0;i<moves.length;i++)
	{
		if(counter > 80 && moves.substring(i,i+1) == " ")
		{
			returnstring += " |";
			counter = 0;
		}
		else
		{
			returnstring += moves.substring(i,i+1);
		}
		counter++;
	}
	return returnstring;
}
/**
 * Called when the user clicks on a move.
 * Sends the new move number to the board.
 **/
function Move_Click(moveNumber)
{
	this.currentMove = moveNumber;
	if(this.currentMove > this.totalMoves) this.currentMove = this.totalMoves;
	this.Board_SetCommandParameter("MoveNumber", this.currentMove);
	this.Board_ExecuteCommand("GoToMove");
}

/**
 * Called when the user clicks on a player name.
 * Sends the player id to the server.
 **/
function Player_Click(playerID)
{
	this.Panel_Show("PlayerInfoPanel");
	this.PlayerInfo_BeginUpdate();

	this.Board_SetCommandParameter("PlayerID", playerID);
	this.Board_ExecuteCommand("GetPlayer");
}
