//function to create ajax object
function pullAjax() {
	
	var a;
	try {
		a = new XMLHttpRequest()
	} catch (b) {
		try {
			a = new ActiveXObject("Msxml2.XMLHTTP")
		} catch (b) {
			try {
				a = new ActiveXObject("Microsoft.XMLHTTP")
			} catch (b) {
				alert("Your browser broke!");
				return false
			}
		}
	}
	return a;
}
// this function does the ajax call, and appends cities into the second dropdown
function populate_cities(x) {
	
	obj = pullAjax();
	var cities_list = document.getElementById('city');
	obj.onreadystatechange = function() {		
		if (obj.readyState == 4) {
			// returns comma separated list of cities after successful ajax
			// request
			var tmp = obj.responseText;
			
			// split function returns array of city
			cities = tmp.split(',');
		
			// if second dropdown already has some data, CLEAR it
			if (cities_list.length >= 1)
				clean_cities(cities_list);
			// for loop to append the cities
			var i = 1;
			while(i < cities.length)
			{
				append_city(cities[i-1],cities[i]);
				i+=2;
			}	
				
		}
	};
	
	obj.open("GET", "cities_data.php?state=" + x.value, true);
	
	obj.send(null);
	
}
// this gets call in the for loop and creates the options for the dropdown
function append_city(city_value,city_caption) {
	var cities_list = document.getElementById('city');
	cities_list.options[cities_list.options.length] = new Option(city_caption,city_value
			, false, false);
}
// CLEARs the dropdown
function clean_cities() {
	var cities_list = document.getElementById('city');
	cities_list.options.length = 0;
}
// autoloads the city list, when the page first loads
function autoload() {
	populate_cities(document.getElementById('state'));
}