//window.onload = initAll;
var xhr = false;
var citiesArray = new Array();
//var statedata;

function initAll(stateS) {
	
	document.getElementById("town").onkeyup = searchSuggest;

	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
	}
	else {
		if (window.ActiveXObject) {
			try {

				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) { }
		}
	}

	if (xhr) {

		// work around - since the numbers aint matching up
		//if(stateS < 10){
		//	stateS = stateS -1;
		//}	
		
		if(stateS !=0){
		 	document.getElementById("selectmsg").innerHTML = "<i><font size=1>**if you see your city please select from the dynamic city list</font></i>";
		}
		
		var states= "get_town_xml.php?q=a&statedata="+stateS;
		
		//alert(states);
	
		xhr.onreadystatechange = setStatesArray;
		xhr.open("GET", states, true);
		xhr.send(null);
	}
	else {
		alert("Sorry, but I couldn't create an XMLHttpRequest");
	}
}

function setStatesArray() {
	if (xhr.readyState == 4) {
		if (xhr.status == 200) {
			if (xhr.responseXML) {
				var allCities = xhr.responseXML.getElementsByTagName("cityname");
				
				//alert(allCities.length);
				for (var i=0; i<allCities.length; i++) {
					citiesArray[i] = allCities[i].firstChild.nodeValue;
				}
			}
		}
		else {
			alert("There was a problem with the request " + xhr.status);
		}
	}
}

function searchSuggest() {
	var str = document.getElementById("town").value;
	document.getElementById("town").className = "";
	if (str != "") {
		document.getElementById("popups").innerHTML = "";
	
	
		for (var i=0; i<citiesArray.length; i++) {
			var thisCity = citiesArray[i];
	
			if (thisCity.toLowerCase().indexOf(str.toLowerCase()) == 0) {
				var tempDiv = document.createElement("div");
				tempDiv.innerHTML = thisCity;
				tempDiv.onclick = makeChoice;
				tempDiv.className = "suggestions";
				document.getElementById("popups").appendChild(tempDiv);
			}
		}
		var foundCt = document.getElementById("popups").childNodes.length;
		if (foundCt == 0) {
			document.getElementById("town").className = "error";
		}
		if (foundCt == 1) {
			document.getElementById("town").value = document.getElementById("popups").firstChild.innerHTML;
			document.getElementById("popups").innerHTML = "";
		}
	}
}

function makeChoice(evt) {
	var thisDiv = (evt) ? evt.target : window.event.srcElement;
	document.getElementById("town").value = thisDiv.innerHTML;
	document.getElementById("popups").innerHTML = "";
}

