COOKIE_NAME = "chesscookie";
currentStyle="style1";
var fennames = new Array();

fennames["w_rook"]		= "R";
fennames["w_knight"]	= "N";
fennames["w_bishop"]	= "B";
fennames["w_queen"]		= "Q";
fennames["w_king"]		= "K";
fennames["w_pawn"]		= "P";
fennames["b_rook"]		= "r";
fennames["b_knight"]	= "n";
fennames["b_bishop"]	= "b";
fennames["b_queen"]		= "q";
fennames["b_king"]		= "k";
fennames["b_pawn"]		= "p";

fennames["R"]	= "w_rook";
fennames["N"]	= "w_knight";
fennames["B"]	= "w_bishop";
fennames["Q"]	= "w_queen";
fennames["K"]	= "w_king";
fennames["P"]	= "w_pawn";
fennames["r"]	= "b_rook";
fennames["n"]	= "b_knight";
fennames["b"]	= "b_bishop";
fennames["q"]	= "b_queen";
fennames["k"]	= "b_king";
fennames["p"]	= "b_pawn";

var imagenames = new Array();

imagenames[0] = "w_rook";
imagenames[1] = "w_knight";
imagenames[2] = "w_bishop";
imagenames[3] = "w_queen";
imagenames[4] = "w_king";
imagenames[5] = "w_pawn";
imagenames[6] = "b_rook";
imagenames[7] = "b_knight";
imagenames[8] = "b_bishop";
imagenames[9] = "b_queen";
imagenames[10] = "b_king";
imagenames[11] = "b_pawn";

//////////////////////////////////////////////
/// Get the value of a radio button group ////
//////////////////////////////////////////////
function getCheckedValue(radioName) {
	radioObj = document.getElementsByName(radioName);

	if(!radioObj)
		return "";

	var radioLength = radioObj.length;
	
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";

	for(var i = 0; i < radioLength; i++) 
	{
		if(radioObj[i].checked) 
		{
			return radioObj[i].value;
		}
	}
	return "";
}

/////////////////////////////////////////////////////
/// Get the FEN representing the current position ///
/////////////////////////////////////////////////////
function getFEN()
{
	s = "";
	count = 0;

	for(i = 0; i < 8; i++)
	{
		for(j = 0; j < 8; j++)
		{
			piece = board[i][j];
			if(piece == null)
				count++;
			else
			{
				piece = piece.name;
				piece = getFENSymbol(piece);
				if(count != 0)
				{
					s = s + count;
					count = 0;
				}
				s = s + piece;
			}	

		}
		if(count != 0)
		{
			s = s + count;
			count = 0;
		}

		if(i < 7)
			s = s  + "/";
	}

	//alert(s);
	return s;
}

function getFENSymbol(pieceName)
{
	pName = "";

	for(loop = 0; loop < pieceName.length; loop++)
	{
		
		c = pieceName.charAt(loop);
		if(isNaN(parseInt(c)))
		{
			pName = pName + c;
		}
		else
			break;
	}
	return fennames[pName];
}

function enterFEN()
{
	fen = prompt("Please enter FEN (example:  rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR) ", "");
	
	if(fen == "" || fen == null)
		return;

	setupFEN(fen);
}


function setupFEN(fen)
{

	fen = fen.split(" ")[0];
	fenArray = fen.split("/");
	if(fenArray.length != 8)
	{
		s = "";
		for(i = 0; i < fenArray.length; i++)
		{
			s += (i + 1) + ") " + fenArray[i] + "\n";
		}
		alert("I'm sorry, I don't understand this command.\nI expected 8 rows, but you entered " + fenArray.length + ":\n\n" + s);
		return;
	}
	
	if(!validFEN(fenArray))
	{
		return;
	}

	clearBoard();

	for(loop0 = 0; loop0 < fenArray.length; loop0++)
	{

		col = 0;
		row = loop0;

		fenLine = fenArray[loop0];

		for(loop1 = 0; loop1 < fenLine.length; loop1++)
		{
			fenChar = fenLine.charAt(loop1);
			if(isNaN(parseInt(fenChar)))
			{
				placePieceRC(fennames[fenChar], row, col);
				col++;
			}
			else
			{
				col += parseInt(fenChar);
			}

		}

	}

}

function validFENChar(fenChar)
{
	validFenChars = "RNBQKPrnbqkp12345678xo";
	if(validFenChars.indexOf(fenChar) < 0)
		return false;

	return true;
}

function validFEN(fenArray)
{
	
	for(i = 0; i < fenArray.length; i++)
	{
		fenRow = fenArray[i];
		// Check that all characters are valid
		for(j = 0; j < fenRow.length; j++)
		{
			if(!validFENChar(fenRow.charAt(j)))
			//if(!validFENChar(fenRow[j]))
			{
				errorMsg = "Invalid FEN character '" + fenRow.charAt(j) + "' on row " + (i + 1) + "\n" + 
							fenRow;
							
				alert(errorMsg);
				return false;
			}
		}

		// Check that length is 8
		columns = 0;
		for(j = 0; j < fenRow.length; j++)
		{
			if(isNaN(parseInt(fenRow.charAt(j))))
			{
				columns++;
			}
			else
			{
				num = parseInt(fenRow.charAt(j));
				columns += num;
			}
		}

		if(columns != 8)
		{
			errorMsg = "Row " + (i + 1) + " only describes " + columns + " columns.  I expected it to describe 8\nRow " + (i+1)+ ": " + fenRow;
			alert(errorMsg);
			return false;
		}

	}

	return true; //TODO: Fill this in
}

function fenTests()
{
	var fentests= new Array();

	fentests[0]= "rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R";
	fentests[1]= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR";
	fentests[2]= "6k1/p5r1/4bpN1/1p1Q4/6n1/1P6/P1P1r1P1/1K5R";
	fentests[3]= "5qk1/p1p3r1/2N1nBNp/4P1b1/2BQ2p1/8/PP4P1/1K6";
	fentests[4]= "r5k1/pp4p1/n2N2n1/2PPp1NQ/1P6/P5q1/8/1K1R4";
	fentests[5]= "8/1p3r1p/5Npk/1P2Qp2/2R5/p5P1/3q1PKP/8";
	fentests[6]= "6k1/2p2pr1/p1n2R1Q/1pb1p3/4P3/1BPq4/PP1N2PP/2K5";
	fentests[7]= "4rrk1/p6p/1p1p1pPQ/2pN4/2P4q/3P1n2/PP5P/4RR1K";
	fentests[8]= "1r3rk1/p4pp1/1p6/2q5/2p1Bpb1/P3P2R/5QPP/3R2K1";
	fentests[9]= "4Q3/7k/5K2/8/8/6r1/8/8";
	fentests[10]="2q5/p7/2bQ1p2/1k2p3/8/5P2/P4PKP/2R5";
	fentests[11]="5r2/1b2k1p1/pp1nP1Bp/3q4/PP6/8/5QPP/4R1K1";
	fentests[12]="1r2k3/4r2p/p3p1pB/1p2NpP1/5P2/8/PKP3BP/3R4";
	fentests[13]="3q4/1p3r1k/5bRp/1N3Q2/P2pp3/7P/6P1/7K";
	fentests[14]="6kr/qn3pr1/1p1p1Q2/3Pp2p/P1R5/2P3PB/7P/5R1K";
	fentests[15]="r7/1p2pBk1/2p5/p5P1/3P4/2P2QK1/P2q4/7R";
	fentests[16]="5n1k/7p/4pNpP/4P3/p2Q4/q3P3/5P1K/8";
	fentests[17]="r4r2/1bq1bpk1/p2pp1p1/8/1n1NnP2/2N1B2Q/1PP5/2KR1B1R";
	fentests[18]="2r3k1/1p3pp1/pB1Qb2p/8/P5n1/5NP1/1q2P1BP/6K1";
	fentests[19]="3r4/p1kq4/2pb4/2p5/8/1N2p1P1/PPQ1P3/R3K3";
	fentests[20]="8/8/8/8/7R/1kr2b2/8/1K6";
	fentests[21]="r2q3k/p1p3pp/7r/1Qbb1p2/5Pn1/2P4P/PPB2NP1/R1B2R1K";
	fentests[22]="6rk/4b2p/3p2rq/p1pPp3/P1N1Pp2/1P4n1/1R3QPP/4RBK1";
	fentests[23]="r1b3k1/ppp3pp/8/2bP4/5r2/2N2pNq/PP1P1P1P/R1B2QRK";
	fentests[24]="5r1k/1p2R3/p7/1b1p4/NP1PB1p1/P5qp/5rP1/3Q2RK";
	fentests[25]="6k1/8/8/1p4p1/1P1q1pp1/6P1/3B2K1/5N2";
	fentests[26]="R7/5pkp/6p1/1B1p4/2nb4/5PB1/6rP/4K3";

	failures = 0;
	for(testnum = 0; testnum < fentests.length; testnum++)
	{
		fen = fentests[testnum];
		setupFEN(fen);
		newFen = getFEN();

		if(fen != newFen)
		{
			alert("ERROR: FEN Test Failed\n" + 
					"INPUT  : " + fen + "\n" +
					"OUTPUT : " + newFen)
			failures++;
		}
	
	}

	alert(fentests.length + " tests\n" + failures + " failures");

}


function toggleDetails()
{
	if(getCheckedValue("boardDetails") == "on")
	{
		document.getElementById("detailsTable").style.display = "";
	}
	else
	{
		document.getElementById("detailsTable").style.display = "none";
	}
}

function gotoServer()
{
	//baseUrl = "http://localhost/apps/phpTest/pictureparser.php?";
	deleteCookie(COOKIE_NAME);

	// Create expiration date for new cookie = 1 day from now
	var expDate = new Date();
	expDate.setTime(expDate.getTime() + 1000 * 60 * 60 * 24 * 1)


	baseUrl = "result.php?";
	params = "";


	////////////////////////
	/////// PIECES /////////
	////////////////////////
	params+= "fen=" + getFEN();

	////////////////////////
	///// Coordinates //////
	////////////////////////
	var coord = getCheckedValue("coordRadio");
	if(coord == "on")
	{
		params += "&coord=on";
	}



	///////////////////////////
	/////// GAME INFO /////////
	///////////////////////////
	// URL param name : Description
	//boardDetails : on or off.  If off, don't include other params
	var boardDetails = getCheckedValue("boardDetails");
	if(boardDetails == "off")
	{
		//params += "&boardDetails=off";
	}
	else 
	{
		params += "&boardDetails=on";

		// move : side to move
		var sideToMove = getCheckedValue("sideToMove");
		if(sideToMove == "white")
		{
			params += "&move=W";
		}
		else if(sideToMove == "black")
		{
			params += "&move=B";
		}


		// title : game title
		var gameTitle = document.getElementById("gameTitle").value;
		if(gameTitle != null && gameTitle != "")
		{
			params += "&title=" + gameTitle;
		}

		// wname : white name
		var whiteName = document.getElementById("whiteName").value;
		if(whiteName != null && whiteName != "")
		{
			params += "&wname=" + whiteName;
		}
		
		// bname : black name
		var blackName = document.getElementById("blackName").value;
		if(blackName != null && blackName != "")
		{
			params += "&bname=" + blackName;
		}

		// loc : location
		var loc = document.getElementById("location").value;
		if(loc != null && loc != "")
		{
			params += "&loc=" + loc;
		}

		// date : date game was played
		var gameDate = document.getElementById("gameDate").value;
		if(gameDate != null && gameDate != "")
		{
			params += "&date=" + gameDate;
		}

		// note : note
		var note = document.getElementById("note").value;
		if(note != null && note != "")
		{
			params += "&note=" + note;
		}

		//TODO: Add "Grid" Options

	}

	///////////////////
	///// COLORS //////
	///////////////////
	if(CURRENT_DARK_COLOR != DEFAULT_DARK_COLOR)
		params += "&dcolor=" + CURRENT_DARK_COLOR;

	if(CURRENT_LIGHT_COLOR != DEFAULT_LIGHT_COLOR)
		params += "&lcolor=" + CURRENT_LIGHT_COLOR;

	if(CURRENT_FONT_COLOR != DEFAULT_FONT_COLOR)
		params += "&fcolor=" + CURRENT_FONT_COLOR;

	if(CURRENT_BG_COLOR != DEFAULT_BG_COLOR)
		params += "&bcolor=" + CURRENT_BG_COLOR;

	//////////////////////
	//// Piece Styles ////
	//////////////////////
	if(currentStyle == "style1" || currentStyle == null)
	{
		// do nothing
	}
	else
	{
		params += "&style=" + currentStyle;
	}

	//////////////////////////
	///// Cookies ////////////
	//////////////////////////
	writeMultiValueCookie(COOKIE_NAME, "fen", getFEN(), expDate);
	writeMultiValueCookie(COOKIE_NAME, "style", currentStyle, expDate);
	writeMultiValueCookie(COOKIE_NAME, "dcolor", CURRENT_DARK_COLOR, expDate);
	writeMultiValueCookie(COOKIE_NAME, "lcolor", CURRENT_LIGHT_COLOR, expDate);
	writeMultiValueCookie(COOKIE_NAME, "fcolor", CURRENT_FONT_COLOR, expDate);
	writeMultiValueCookie(COOKIE_NAME, "bcolor", CURRENT_BG_COLOR, expDate);


	//////////////////////////////
	///// Goto Server ////////////
	//////////////////////////////
	newURL = baseUrl + params;
	window.location = newURL;


}




function pieceChange()
{

	newStyle = getCheckedValue("styleRadio");
	
	//document.getElementById("w_king_icon").src = "img/pieces/style2/w_rook.png";
	for(i = 0; i < dd.elements.length; i++)
	{
		name = dd.elements[i].name;
		//alert(name);
		
		if(isPieceName(name))
		{
			origSource = dd.elements[name].src;

			newSource = origSource.replace(currentStyle, newStyle);
			dd.elements[name].swapImage(newSource);
		}
	}

	currentStyle = newStyle;
		
}

function isPieceName(n)
{
	for(loop = 0; loop < imagenames.length; loop++)
	{
		pieceName = imagenames[loop];
		if(n.indexOf(pieceName) != -1)
			return true;
	}

	return false;
}

function fillTinyURL()
{
	document.getElementById("tinyurl").value = window.location;
}