var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject()
{
	var xmlHttp;
		
	if(window.ActiveXObject)
	{
		try
		{
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e)
		{
			xmlHttp = false;
		}
	}
	else
	{
		try
		{
			xmlHttp = new XMLHttpRequest();
		}
		catch(e)
		{
			xmlHttp = false;
		}
	}
		
	if(!xmlHttp)
	{
		return false;
	}
	else
	{
		return xmlHttp;
	}
}

function updateModels(modelElement, makeID, modelID, showCount)
{
	if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
	{	
		xmlHttp.onreadystatechange = handleServerResponse;
		xmlHttp.open("GET", "/tools/model_query.php?key=c6FuB9K1&me=" + modelElement + "&make_id=" + makeID + "&model_id=" + modelID + "&show_count=" + showCount, true);
		xmlHttp.send(null);
	}
	else
	{
		//How to pass function elements?  Might not work?
		//setTimeout("updateModels(modelElement, makeID)", 1000);
	}
}

function handleServerResponse()
{
	if(xmlHttp.readyState == 4)
	{
		if(xmlHttp.status == 200)
		{
			xmlResponse = xmlHttp.responseXML;
			xmlDocumentElement = xmlResponse.documentElement;
			
			//get the options info
			//get the product pricing info
			optionsArray = xmlDocumentElement.getElementsByTagName("options");
			selectElement = optionsArray[0].getElementsByTagName("me")[0].firstChild.nodeValue;
			selectedID = optionsArray[0].getElementsByTagName("selected")[0].firstChild.nodeValue;
			showCount = optionsArray[0].getElementsByTagName("show_count")[0].firstChild.nodeValue;

			//get the model info
			modelArray = xmlDocumentElement.getElementsByTagName("model");
			
			//clear the model drop down
			var model_select = document.getElementById(selectElement);
			
			model_select.options.length = 0;		
			
			var optionName = new Option("Select Model", "", 0, 0);
			var length = model_select.length;
			model_select.options[length] = optionName;
			
			//populate the model drop down
			for(var i = 0; i < modelArray.length; i++)
			{
				modelID      = modelArray[i].getElementsByTagName("model_id")[0].firstChild.nodeValue;
				vehicleCount = modelArray[i].getElementsByTagName("total_vehicles")[0].firstChild.nodeValue;
				
				if(showCount != 0)
				{
					modelName = modelArray[i].getElementsByTagName("name")[0].firstChild.nodeValue + "  (" + vehicleCount + ")";
				} else {
					modelName = modelArray[i].getElementsByTagName("name")[0].firstChild.nodeValue;
				}
				
				var optionName = new Option(modelName, modelID, 0, 0);
				var length = model_select.length;
				model_select.options[length] = optionName;

				if(selectedID == model_select.options[length].value)
				{
					model_select.selectedIndex = length;
				}
			}
		}
		else
		{
			return false;
		}
	}
}