// holds an instance of XMLHttpRequest

var xmlHttp = createXmlHttpRequestObject();
var globalAction = ""; 	// keeps track of which operation is currently being done
var globalName = "";
var globalFromId = 0;
var globalToId = 0;

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject()
{
	var xmlHttp;
	
	// Create the XMLHttpRequest Object for all versions of IE up to and including IE6
	try
	{
		// try to create XMLHttpRequest object
		xmlHttp = new XMLHttpRequest();
	}
	catch(e)
	{
		// assume IE6 or older
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP");
		
		// try every ID until on works
		for (var i=0; i < XmlHttpVersions.length && !xmlHttp; i++)
		{
			try
			{
				// try to create the XMLHttpRequest object
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			}
			catch(e){}
		}
	}
		
	// return the created object or display an error message
	if(!xmlHttp)
	{
		alert("Error creating the XMLHttpRequest object.");
	}
	else
	{
		return xmlHttp;
	}
}

// Font Change Handling
function FontChange()
{
	if(xmlHttp)
	{
		globalAction = "FontChange";
		var selFont = document.getElementById("mapFont").value;
		var newMapText = "";
		try
		{
			newMapText = document.getElementById("mapNewText").value;
		}
		catch(e){}
		
		var params = "action=" + globalAction + "&Selected=" + selFont + "&mapNewText=" + newMapText;
		
		xmlHttp.open("POST","_convmap.php",true);
		xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xmlHttp.send(params);																			
		xmlHttp.onreadystatechange = mapHandleStateChange;	
	}
}

// Assign Map to Font
function FontAssignMap()
{
	if(xmlHttp)
	{
		globalAction = "FontAssignMap";
		var selFont = document.getElementById("mapFont").value;	
		var selMap = document.getElementById("mapMaps").value;
		var params = "action=" + globalAction + "&Font=" + selFont + "&Map=" + selMap;
		
		xmlHttp.open("POST","_convmap.php",true);
		xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xmlHttp.send(params);																			
		xmlHttp.onreadystatechange = mapHandleStateChange;	
	}
}

// Display Map to Font
function MapChange()
{
	if(xmlHttp)
	{
		globalAction = "MapChange";
		var selFont = document.getElementById("mapFont").value;	
		var selMap = document.getElementById("mapMaps").value;
		var params = "action=" + globalAction + "&Font=" + selFont + "&Map=" + selMap;
		
		xmlHttp.open("POST","_convmap.php",true);
		xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xmlHttp.send(params);																			
		xmlHttp.onreadystatechange = mapHandleStateChange;	
	}
}

// Display Map to Font
function showFont(id,char)
{
	var divName = document.getElementById("showFont" + id);
	divName.innerHTML = String.fromCharCode(char);
}

function getKeyCode(id)
{
	var char = document.getElementById("charOrg" + id);
	var code = char.value.charCodeAt(0);
	
	var target = document.getElementById("mapCodes[" + id + "]");
	target.value = code;
}

// Handle Map Functions
function mapHandleStateChange()
{
	if(xmlHttp.readyState == 4)
	{
		if(xmlHttp.status == 200)
		{
			try
			{
				if (globalAction == "FontChange")
				{
					var divName = document.getElementById("divMaps");
					divName.innerHTML = xmlHttp.responseText;
				}
				if (globalAction == "FontAssignMap")
				{
					alert("Assign Complete");
				}
				if (globalAction == "MapChange")
				{
					var divName = document.getElementById("divArea");
					divName.innerHTML = xmlHttp.responseText;
				}				
			}
			catch(e)
			{
				alert("Error reading the response: " + e.toString());
			}
		}
		else
		{
			alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
		}
	}
}




// called to read a file from the server
function process(action,fieldName)
{
	// only continue if xmlHttp isn't void
	
	if(xmlHttp)
	{
		globalAction = action;				// Set the globalAction
		globalName = fieldName;
		// try to connect to the server
		
		try
		{
			
			// Change the div contents from plain text to a Select Box
			if(action == "text2select")
			{				
				var method = "POST";		// Set to the method ("GET" or "POST") used to pass variables to the server-side page
				var url = "updateDB.php";	// Set to the url of the server-side page being connected to
				var async = true;			// Setting this argument to true is the backbone of AJAX. It allows for connecting to 
											// a server-side page for processing asynchronously.
							
				var params = "action=" + action + "&NAME=" + globalName; // The list of parameters to be passed
							
				xmlHttp.open(method,url,async);	// Opens the asynchronous connection to the server-side page
				xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');	// Set the Content-Type Header
				
				xmlHttp.send(params);	// Set to the parameter list (as a string) being
										// passed to the server-side script If using the "GET"
										//method, this should be set to null
										
																			
				xmlHttp.onreadystatechange = handleStateChange;	// Set to the function that will handle the state change
			}
			
			if(action == "Update")
			{
				// Connect asynchonously to the php to update database
				var method = "POST";		// Set to the method ("GET" or "POST") used to pass variables to the server-side page
				var url = "updateDB.php";	// Set to the url of the server-side page being connected to
				var async = true;			// Setting this argument to true is the backbone of AJAX. It allows for connecting to 
											// a server-side page for processing asynchronously.

				var doc = document.Status; // reference the form being used
				var newStatus = document.getElementById("selStatus").value;
				if(globalName == "fontFrom") globalFromId = newStatus;
				if(globalName == "fontTo") globalToId = newStatus;
				var params = "action=" + globalAction + "&NAME=" + globalName + "&newStatus= " + newStatus; // Parameters to be passed.

				xmlHttp.open(method, url, async);
				xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');	// Set the Content-Type Header
				xmlHttp.onreadystatechange = handleStateChange;	// Set to the function that will handle the state change
				xmlHttp.send(params);	// Set to the parameter list (as a string) being passed to the server-side script
										// If using the "GET" method, this should be set to null.

			}
			
			if(action == "Font")
			{
				// Connect asynchonously to the php to update database
				var method = "POST";		// Set to the method ("GET" or "POST") used to pass variables to the server-side page
				var url = "updateDB.php";	// Set to the url of the server-side page being connected to
				var async = true;			// Setting this argument to true is the backbone of AJAX. It allows for connecting to 
											// a server-side page for processing asynchronously.

				var doc = document.Status; // reference the form being used
				var newStatus = document.getElementById(globalName).value;
				if(globalName == "fontFrom") globalFromId = newStatus;
				var params = "action=" + globalAction + "&NAME=" + globalName + "&newStatus= " + newStatus; // Parameters to be passed.

				xmlHttp.open(method, url, async);
				xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');	// Set the Content-Type Header
				xmlHttp.onreadystatechange = handleStateChange;	// Set to the function that will handle the state change
				xmlHttp.send(params);	// Set to the parameter list (as a string) being passed to the server-side script
										// If using the "GET" method, this should be set to null.

			}			

			if(globalAction == "Convert")
			{
				// Connect asynchonously to the php to update database
				var method = "POST";		// Set to the method ("GET" or "POST") used to pass variables to the server-side page
				var url = "updateDB.php";	// Set to the url of the server-side page being connected to
				var async = true;			// Setting this argument to true is the backbone of AJAX. It allows for connecting to 
											// a server-side page for processing asynchronously.
							
				var textToConvert = document.getElementById("fontFromTextarea").value;
				
				var params = "action=" + globalAction + "&Text=" + encodeURIComponent(textToConvert) + "&FontFrom=" + globalFromId + "&FontTo=" + globalToId; // Parameters to be passed.		
					
				xmlHttp.open(method, url, async);
				xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');	// Set the Content-Type Header
				xmlHttp.onreadystatechange = handleStateChange;	// Set to the function that will handle the state change
				xmlHttp.send(params);	// Set to the parameter list (as a string) being passed to the server-side script
										// If using the "GET" method, this should be set to null.
	
			}
			
		}
		
		// display the error in case of failure
		catch(e)
		{
			alert("Can't connect to server:\n" + e.toString());
		}
	}
}

// function that handles the response from the HttpRequestObject
function handleStateChange()
{
	// We wait until the server is ready to respond
	if(xmlHttp.readyState == 4)
	{
		// only continue if status is 200 or OK
		if(xmlHttp.status == 200)
		{
			try
			{
				// Handle the server's response
				
				// Change the div Text to a Select Box
				if(globalAction == "text2select")
				{
					var divName = document.getElementById(globalName);	// Aquire reference to targeted Div tag
					divName.innerHTML = xmlHttp.responseText;			// Set content of the targeted Div to the value sent back from
																		// the server-side page
				}
				
				if(globalAction == "Update")
				{
					var divName = document.getElementById(globalName);
					divName.innerHTML = '<div id="' + globalName + '"><div style="width:250px" onClick="process(\'text2select\',\'' + globalName + '\')"><u>' + xmlHttp.responseText + '</u></div></div>';
					
					if (globalName == "fontFrom")
					{
						var textareaName = document.getElementById(globalName + "Text");			 
						textareaName.innerHTML = '<div id="' + globalName + "Text" + '"><textarea style="font-family:' + xmlHttp.responseText + '" name="' + globalName + "Textarea" + '" cols="40" rows="10"></textarea></div>';
					}
				}
				
				if(globalAction == "Font")
				{
					if (globalName == "fontFrom")
					{
						var textareaName = document.getElementById(globalName + "Text");			 
						textareaName.innerHTML = '<div id="' + globalName + "Text" + '"><textarea style="font-family:' + xmlHttp.responseText + '" name="' + globalName + "Textarea" + '" cols="40" rows="10"></textarea></div>';
					}
				}				
				
				if(globalAction == "Convert")
				{
					var convertOutput = document.getElementById(globalName);
					convertOutput.innerHTML = '<div style="width:500px" id="' + globalName + '">' + xmlHttp.responseText + '</div>';
				}
			}
			catch(e)
			{
				// display error message
				alert("Error reading the response: " + e.toString());
			}
		}
		else
		{
			// display status message
			alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
		}
	}
}