var xmlHttp = createXmlHttpRequestObject();
var serverAddress = 'inc/cities.php';
var showErrors = false;
var cache = new Array();

function createXmlHttpRequestObject() {
	var xmlHttp;
	try {
		xmlHttp = new XMLHttpRequest();
	}
	catch(e) {
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
										"MSXML2.XMLHTTP.5.0",
										"MSXML2.XMLHTTP.4.0",
										"MSXML2.XMLHTTP.3.0",
										"MSXML2.XMLHTTP",
										"Microsoft.XMLHTTP");
		for (var i = 0; i < XmlHttpVersions.length && !xmlHttp; i++) {
			try {
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			}
			catch(e) {}
		}
	}
	
	if (xmlHttp) return xmlHttp;
}

function displayError(message) {
	if (showErrors) {
		showErrors = false;
		alert('An error has attempt: \n' + message);
		setTimeout('select_cities();',10000);
	}
}

function select_cities(inputValue,fieldID) {
	//alert(inputValue);
	//alert(fieldID);
	if (xmlHttp) {
		if (fieldID) {
			inputValue = encodeURIComponent(inputValue);
			cache.push('inputValue=' + inputValue + '&fieldID=' + fieldID);
		}
		try {
			if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0) && cache.length > 0) {
				var cacheEntry = cache.shift();
				xmlHttp.open("POST", serverAddress, true);
				xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				xmlHttp.onreadystatechange = handleRequestStateChange;
				xmlHttp.send(cacheEntry);
			}
		}
		catch(e) {
			displayError(e.toString());
		}
	}
}

function handleRequestStateChange() {
	//alert(xmlHttp.status);
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			try {
				//alert("12345");
				readResponse();
			}
			catch(e) {
				displayError(e.toString());
			}
		} else {
			displayError(xmlHttp.statusText);
		}
	}
}

function readResponse() {
	//alert("dert");
	//var response = xmlHttp.responseText;
	//alert("sss");
	responseXml = xmlHttp.responseXML;
	xmlDoc = responseXml.documentElement;
	result_count = xmlDoc.getElementsByTagName('result_count')[0].firstChild.data;
	var sel;
	sel = '<select name="sel_city" id="sel_city"  class="world_select" style="width:238px;">';
	for (var i=0;i<result_count;i++){
		result_id = xmlDoc.getElementsByTagName('result_id')[i].firstChild.data;
		result_value = xmlDoc.getElementsByTagName('result_value')[i].firstChild.data;
		sel = sel + '<option value="'+result_id+'">'+result_value+'</option>';
		//alert(result_id);
	}
	sel = sel + '</select>';
	document.getElementById('city').innerHTML = sel;
	//exit;
	setTimeout('select_cities();', 500);
}