//Global XMLHTTP Request object
var XmlHttp;

//Creating and setting the instance of appropriate XMLHTTP Request object to a “XmlHttp” variable  
function CreateXmlHttp()
{
	//Creating object of XMLHTTP in IE
	try
	{
		XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			XmlHttp = null;
		}
	}
	//Creating object of XMLHTTP in Mozilla and Safari 
	if(!XmlHttp && typeof XMLHttpRequest != "undefined") 
	{
		XmlHttp = new XMLHttpRequest();
	}
}

//Gets called when MAKE combo box selection changes
function MakeListOnChange(a) 
{
	var makeList = document.getElementById("makeList");

	//Get the selected value from MAKE combo box.
	var selectedMake = makeList.options[makeList.selectedIndex].value;
	
	// URL to get MODEL for a given MAKE
	var requestUrl = "ajaxxml.asp?MAKE=" + encodeURIComponent(selectedMake);

	CreateXmlHttp();
	
	// If browser supports XMLHTTPRequest object
	if(XmlHttp)
	{
		//Setting the event handler for the response
		XmlHttp.onreadystatechange = HandleResponse;
		
		//Initializes the request object with GET (METHOD of posting), 
		//Request URL and sets the request as synchronous/asynchronous.
		XmlHttp.open("GET", requestUrl,  a);
		
		//Sends the request to server
		XmlHttp.send(null);		
	}
}

//Called when response comes back from server
function HandleResponse()
{
	// To make sure receiving response data from server is completed
	if(XmlHttp.readyState == 4)
	{
		// To make sure valid response is received from the server, 200 means response received is OK
		if(XmlHttp.status == 200)
		{
			ClearAndSetModelListItems(XmlHttp.responseXML.documentElement);
		}
		//else
		//{
		//	alert("There was a problem retrieving data from the server." );
		//}
	}
}

//Clears the contents of MODEL combo box and adds the models of currently selected make
function ClearAndSetModelListItems(makeNode)
{
    var modelList = document.getElementById("modelList");
	//Clears the model combo box contents.
	for (var count = modelList.options.length-1; count >-1; count--)
	{
		modelList.options[count] = null;
	}

	var modelNodes = makeNode.getElementsByTagName('model');
	var textValue; 
	var optionItem;

	//Add new states list to the state combo box.
	for (var count = 0; count < modelNodes.length; count++)
	{
   		textValue = GetInnerText(modelNodes[count]);
		optionItem = new Option( textValue, textValue,  false, false);
		modelList.options[modelList.length] = optionItem;
	}
}

//Returns the node text value 
function GetInnerText (node)
{
	 return (node.textContent || node.innerText || node.text) ;
}
