/*******************************************************************************
**	Author: Peter McCutcheon
**	Date Created:  7/22/2016
**	Last Modified: 7/22/2016
**
**------------------------------------------------------------------------------
**Description of Code:
**
**	This script implements displaying the code examples. The program adds and
**	event listener to a text box.  On any change to the textbox an Ajax request
**	is sent to the server to retrieve a code/description file that maps three
**	character airport codes into a descriptive name.  The file is scanned for
**	the code that the user entered and then the airport descriptive name
**	is displayed.
**
********************************************************************************/

var tBox = document.getElementById("displaycode");
tBox.addEventListener("change", function()
{
	var request = new XMLHttpRequest();
	//alert("Ok we triggered the change event.");
	if (!request)
	{
		alert("Error - Ajax object not created, browser may not support Ajax.")
	}
	request.onreadystatechange = function() 
	{
		if (request.readyState == 4)
		{
			if (request.status == 200)
			{
				if (this.responseText != null)
				{
					//alert(request.responseText);
					var AirPort = "";
					var tmpStr = "";
					var apcodeUpper = "";
					var apInput = document.getElementById("apcode");
					tmpStr = apInput.value;
					apcodeUpper = tmpStr.toUpperCase();
					var apDesc = document.getElementById("apdesc");
					var results = request.responseText.split("\n");
					//alert("Results: " + results);
					for (i = 0; i <= request.responseText.length; i++)
					{
						AirPort = results[i].split(",");
						//alert("AirPort: " + results[i]);
						if (AirPort[0] == apcodeUpper)
						{
							//alert("We found it.");
							tmpStr = AirPort[1].replace('"','');
							apDesc.value = tmpStr.concat(AirPort[2].replace('"',''));
							break;
						}
					}
				}
				else alert("Ajax error: No data received")
			}
			else alert("Ajax error: " + this.statusText)
		}
	}
	request.open("GET", "../data/apinfofile.txt", true);
	request.send();

	
}, false);