/*

This work is licensed under the Creative Commons Attribution-ShareAlike License. 
To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/2.0/ 
or send a letter to 

	Creative Commons, 
	559 Nathan Abbott Way, 
	Stanford, California 
		94305, USA.
*/

var strToken = "";
var strTokenXML = "";
var strUsername = "Not logged in";
var aryActions = Array("images/nothing.png", "images/build.png", "images/attack.png", "images/defend.png", "images/destroy.png", "images/connect.png", "images/claim.png", "images/collect.png", "images/give.png");
var aryTransformations = Array();
var aryTransformationNames = Array("gamelist.xsl", "stats.xsl", "players.xsl", "economics.xsl", "playernodes.xsl", "nodes.xsl");

var blnMustFilter = true;
var intCurrentGameID = 0;
var objDebugArea = null;

function CallURL(strURL, strPostData, fnStateChange)
{
	try
	{
		var objRequest = new XMLHttpRequest();
		if(objRequest)
		{
			objRequest.onreadystatechange = function()
			{
				if(objRequest.readyState == 4)
				{
					if(objRequest.status == 200)
					{
						objDebugArea.value += Sarissa.serialize(objRequest.responseXML);
						fnStateChange(objRequest.responseXML);
					}
					else
					{
						alert("There was a problem retrieving some data.  Received a status of " + objRequest.status + " from the URL " + strURL + ".");
					}
				}
			}
			
			objRequest.open(strMethod, strURL);
			objRequest.send(strPostData);
		}
		else
		{
			alert("No XMLHttpRequest Support!  Your browser is unable to use the Connection interface.");
		}
		
	}	
	catch(e)
	{
		alert("[connection.js]/CallURL: " . e.message);
	}	
}

function JoinStateChange(objXML)
{
	try
	{
		if(objXML.documentElement.tagName == "Error")
		{
			objMessage = objXML.documentElement.childNodes;
			strError = "Undefined error!";

			for(i = 0; i < objMessage.length; i++)
			{
				if(objMessage[i].nodeType == 1)
				{
					strError = Sarissa.getText(objMessage[i]);
					i = objMessage.length;
				}
			}

			alert(strError);
		}
		else
		{
			FetchGame(intCurrentGameID);
		}
	}
	catch(e)
	{
		alert("[connection.js]/JoinStateChange: " . e.message);
	}
}

function RenderFromURL(strURL, aryDestination, aryTransform, strPostData)
{
	try
	{
		if(aryDestination.length != aryTransform.length)
		{
			alert("The destination array must be the same size as the transform array.");
			return;
		}
		
		strMethod = "GET";
		if(typeof(strPostData) == "undefined")
		{
			strPostData = "";
		}
		
		if(strPostData == null)
		{
			strPostData = "";
		}
		
		if(strPostData != "")
		{
			strMethod = "POST";
		}
		else
		{
			strPostData = "<Request>" + strPostData + "</Request>";
		}
		
		for(i = 0; i < aryDestination.length; i++)
		{
			var objDestination = document.getElementById(aryDestination[i]);
			if(objDestination == null)
			{
				alert("Null destination '" + aryDestination[i] + "'.");
				return;
			}
			ClearDiv(objDestination, "Loading data... please wait.");
		}
		var objRequest = new XMLHttpRequest();
		if(objRequest)
		{
			objRequest.onreadystatechange = function()
			{
				if(objRequest.readyState == 4)
				{
					if(objRequest.status == 200)
					{
						objDebugArea.value += Sarissa.serialize(objRequest.responseXML);
						aryObjDestination = Array();
						for(i = 0; i < aryDestination.length; i++)
						{
							aryObjDestination.push(document.getElementById(aryDestination[i]));
						}

						PostRender(aryObjDestination, objRequest.responseXML, aryTransform);
					}
					else
					{
						for(i = 0; i < aryObjDestination.length; i++)
						{
							ClearDiv(document.getElementById(aryDestination[i]), "Error retrieving data.");
						}
						alert("There was a problem retrieving some data.  Received a status of " + objRequest.status + " from the URL " + strURL + ".");
					}
				}
			}
			objRequest.open(strMethod, strURL);
			objRequest.send(strPostData);
		}
		else
		{
			alert("No XMLHttpRequest Support!  Your browser is unable to use the Connection interface.");
		}
		
	}	
	catch(e)
	{
		alert(e.message);
	}	
}

function PostRender(aryObjDestination, objXMLResult, aryTransform)
{
	try
	{
		for(i = 0; i < aryObjDestination.length; i++)
		{
			var objDiv = aryObjDestination[i];
			objXSLTProc = new XSLTProcessor();
			objXSLTProc.importStylesheet(aryTransformations[aryTransform[i]]);
			Sarissa.updateContentFromNode(objXMLResult, objDiv, objXSLTProc);
			FilterImages(objDiv);
			//RunScripts(objDiv);
		}
	}
	catch(e)
	{
		alert("[RenderPlayerNodes] : " + e.message);
	}	
}

/*
	AppendText(DOM element, string)
	
	Creates a new text node containing the given string and appends it
	to the given element.
*/
function AppendText(objElement, strText)
{
	try
	{
		objElement.appendChild(document.createTextNode(strText));
	}
	catch(e)
	{
		alert("[AppendText] : " + e.message);
	}
}

function RunScripts(objEl)
{
	objScripts = objEl.getElementsByTagName("script");
	for(i = 0; i < objScripts.length; i++)
	{
	alert(i);
	}
}

function FilterImages(objEl)
{
	try
	{
		if(blnMustFilter == false)
		{
			return;
		}

		if(objEl != null)
		{
			objEl = objEl.firstChild;
		}

		while(objEl != null)
		{
			if(objEl.nodeType == 1)
			{
				if(objEl.tagName == "IMG")
				{
					PNGFilter(objEl);			
				}
				else
				{
					FilterImages(objEl);
				}
			}
			objEl = objEl.nextSibling;
		}
	}
	catch(e)
	{
		alert("[connection.js]/FilterImages] - " + e.message);
	}
}

function PNGFilter(objEl)
{
	try
	{
		if(objEl.runtimeStyle)
		{
			var strSrc = objEl.src;
			var width = objEl.width;
			var height = objEl.height;
			if(width == 0)width = 32;
			if(height == 0)height = 32;
			objEl.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + strSrc + "',sizingMethod='scale')";
			objEl.src = "http://connection.ronsbrain.com/blank.gif";
			objEl.width = width;
			objEl.height = height;
		}
		else
		{
			blnMustFilter = false;
		}
	}
	catch(e)
	{
		alert("[connection.js/PNGFilter] - " + e.message);
	}
}

function LoadTransformations()
{
	if(typeof(aryTransformations["gamelist.xsl"]) != "undefined")
	{
		return;
	}
	
	try
	{
		for(i = 0; i < aryTransformationNames.length; i++)
		{
			objTransform = Sarissa.getDomDocument();
			objTransform.async = false;
			objTransform.load("http://connection.ronsbrain.com/xslt/" + aryTransformationNames[i]);

			aryTransformations[aryTransformationNames[i]] = objTransform;
		}
	}
	catch(e)
	{
		alert(e.message);
	}
}

function ReadCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function SetUsername()
{
	try
	{
		document.getElementById("Login").style.display = "none";
		document.getElementById("Username").innerHTML = "You are playing as " + strUsername;
		document.getElementById("Username").style.display = "block";
		strTokenXML = "<Token>" + strToken + "</Token>";
		
		if(intCurrentGameID != 0)
		{
			RenderFromURL("http://connection.ronsbrain.com/games/" + intCurrentGameID + "/nodes/", new Array("CommandScreen", "Map"), new Array("playernodes.xsl", "nodes.xsl"), strTokenXML);
		}
	}
	catch(e)
	{
		alert(e.message);
	}
}

function Login()
{
	try
	{
		objName = document.getElementById("username");
		strName = objName.value;

		objPass = document.getElementById("password");
		strPass = objPass.value;

		strLogin = "<Request><Username>" + strName + "</Username><Password>" + strPass + "</Password></Request>";
	
		var objRequest = new XMLHttpRequest();
		objRequest.open('POST', 'http://connection.ronsbrain.com/tokens/', false);
		objRequest.send(strLogin);
		objResult = objRequest.responseXML;
		if(objResult.documentElement.tagName == "Error")
		{
			objMessage = objResult.documentElement.childNodes;
			strError = "Undefined error!";
			
			for(i = 0; i < objMessage.length; i++)
			{
				if(objMessage[i].nodeType == 1)
				{
					strError = Sarissa.getText(objMessage[i]);
					i = objMessage.length;
				}
			}
			
			alert(strError);
			objPass.value = "";
		}
		else
		{
			strToken = Sarissa.getText(objResult.documentElement.childNodes[1]);
			strUsername = Sarissa.getText(objResult.documentElement.childNodes[0]);
			SetUsername();
		}
		
	}	
	catch(e)
	{
		alert(e.message);
	}
}

function JoinGame()
{
	CallURL("http://connection.ronsbrain.com/games/" + intCurrentGameID + "/players/", "<Request>" + strTokenXML + "</Request>", JoinStateChange);
}

/*
	ClearDiv(objDiv, strText)
	
	Clear a div tag.
	
	objDiv - DOM object referring to a div.
	strText - Text to display in the div after it is cleared.  Can be null.
	
	Basically, remove the last child from the given div until there are no
	more children.  If the given text is not null, append a text node that
	has the given text.  This is useful for a "Loading data..." message.
*/
function ClearDiv(objDiv, strText)
{
	try
	{
		if(objDiv == null)
		{
			alert("Given object is null.");
			return;
		}

		while(objDiv.childNodes.length > 0)
		{
			objDiv.removeChild(objDiv.firstChild);
		}
		
 		if(strText != null)
 		{
 			objDiv.innerHTML = "<span>" + strText + "</span>";
 		}
 		return objDiv;
 	}
	catch(e)
	{
		alert("[ClearDiv] : " + e.message);
	}
}

/*
	ShowTab(the tab ID)
	
	Sets the display style of the last chosen tab to "none" (hiding it)
	and then sets the last chosen tab to the tab that was chosen and
	sets its style to "block" (showing it)
*/
function ShowTab(strTab)
{
	var objLastTabButton;
	
	if(objLastTab != null)
	{
		var strLast = objLastTab.id;
		objLastTabButton = document.getElementById(strLast + "Button");
		objLastTab.style.display = "none";
		objLastTabButton.className = "tab";
	}
	
	objLastTab = document.getElementById(strTab);
	objLastTab.style.display = "block";
	objLastTabButton = document.getElementById(strTab + "Button");
	objLastTabButton.className = "tabActive";
}

/*
	FormatDate(string of the date)
	
	Formats the given date into something nice, rather than an ugly
	UTC encoding.  If the date is invalid, then we say "Never".
*/
function FormatDate(strDate)
{
	var strFormatted;
	
	strFormatted = new Date(strDate);
	if(strFormatted = "Invalid Date")
	{
		strFormatted = "Never";
	}
	
	return strFormatted;
}

/*
	FetchGame(game id)
	
	Fetch game info from the system.  Also resets the game divs so that
	they say "Loading something or other..."
*/
function FetchGame(intGameID)
{
	try
	{
		intCurrentGameID = intGameID;

		RenderFromURL("http://connection.ronsbrain.com/games/" + intGameID + "/players/", new Array("Players"), new Array("players.xsl"), "");
		RenderFromURL("http://connection.ronsbrain.com/games/" + intGameID + "/", new Array("GameStats", "Economics"), new Array("stats.xsl", "economics.xsl"), strTokenXML);
		RenderFromURL("http://connection.ronsbrain.com/games/" + intGameID + "/nodes/", new Array("CommandScreen", "Map"), new Array("playernodes.xsl", "nodes.xsl"), strTokenXML);
		
		objGameList = document.getElementById("Gamelist");
		objMain = document.getElementById("Main");
		objGameList.style.display = "none";
		objMain.style.display = "block";

	}
	catch(e)
	{
		alert("[FetchGame] : " + e.message);
	}
}

function FetchNode(intNodeID)
{
	objAux = document.getElementById("Auxpanel");
	objAux.style.display = "block";
	objAux.prev = document.getElementById("Main");
	objAux.prev.style.display = "none";
	
	objNode = document.getElementById("node_" + intNodeID);
	aryNode = new Array();
	aryNode["id"] = objNode.getAttribute("id");
	aryNode["owned"] = objNode.getAttribute("owned");
	aryNode["owner"] = objNode.getAttribute("owner");
	
	alert(aryNode["id"] + " : " + aryNode["owned"] + " : " + aryNode["owner"]);
}

function CloseAux()
{
	objAux = document.getElementById("Auxpanel");
	objAux.style.display = "none";
	if(typeof(objAux.prev) != "undefined")
	{
		if(objAux.prev != null)
		{
			objAux.prev.style.display = "block";
			objAux.prev = null;
		}
	}
}

function GetToken()
{
	try
	{
		strToken = ReadCookie("session");
		if(strToken != null && strToken != "")
		{
			strRequest = "<Request><Token>" + strToken + "</Token></Request>";
			var objRequest = new XMLHttpRequest();
			objRequest.open('POST', 'http://connection.ronsbrain.com/tokens/', false);
			objRequest.send(strRequest);
			objResult = objRequest.responseXML;
			if(objResult.documentElement.tagName != "Error")
			{
				strToken = Sarissa.getText(objResult.documentElement.childNodes[1]);
				strUsername = Sarissa.getText(objResult.documentElement.childNodes[0]);
				SetUsername();
			}		
			else
			{
				strToken = "";
			}
		}
	}
	catch(e)
	{
		alert(e.message);
	}
}

/*
	LoadStart()
	
	Runs after the whole page is loaded.  This ensures that all divs are
	in the DOM and everything gets initialized properly.  Probably should
	have called this "init" or some shit like that.  Or should I have called
	it Polyphemus?  Who cares?
	
	We need to get the games list.  Our XMLHttpRequest object comes to the
	rescue.  We request the games list through our custom Connection XML
	web services back-end e-game virtual content blah blah blah.
	
	Once the request is complete, and we get an "OK" (200) then we call our
	RenderGamesList() function to show the games, because, you know, that
	might be useful.  If we got something other than a 200, we should probably
	do something else, but that's for a beta release.
*/
function LoadStart()
{
	objDebugArea = document.getElementById("DebugArea");
	FilterImages(document.body);
	strToken = GetToken();
	LoadTransformations();

	try
	{
		var objDiv = document.getElementById("Gamelist");
		objDiv.style.display = "block";
		objMain = document.getElementById("Main");
		objMain.style.display = "none";
		RenderFromURL("http://connection.ronsbrain.com/games/", new Array("Gamelist"), new Array("gamelist.xsl"));
		ShowTab("Players");
	}
	catch(e)
	{
		alert(e.message);
	}
}

/* Our last chosen tab, which is really null */
var objLastTab = null;
