function america_search_states_init()
{
	var states_select = $("america_search_states");
	
	if (states_select) {
		states_select.observe("change", onchange_handler_america_search_states);
	}
}

function ajax_response_america_search_cities(transport)
{
	var doc = transport.responseXML.documentElement;
	var cities_select = $("america_search_cities");

	// Get the current state initials	
	var states_select = $("america_search_states");
	var selected_state_initials = false;
	if (states_select) {
		selected_state_initials = states_select.options[states_select.selectedIndex].value;
	}
	
	// Add the new cities
	var doc_children = doc.getElementsByTagName('city');
	for (var i = 0; i < doc_children.length; i++) {
		var city_name = doc_children[i].firstChild.nodeValue;
		
		// Create the option element
		option = document.createElement("option");
		option.setAttribute("value", city_name);
		if (typeof g_state != "undefined" && typeof g_city != "undefined") {
			if (selected_state_initials == g_state && city_name == g_city) {
				option.setAttribute("selected", "selected");
			}
		}
		
		// Add its text
		option.appendChild(document.createTextNode(city_name));
		
		// Append this option to the select
		cities_select.appendChild(option);
	}
}

function onchange_handler_america_search_states()
{
	var selected_state_initials = this.options[this.selectedIndex].value;
	//alert("selected state = " + selected_state_initials);

	// Remove the current cities
	var cities_select = $("america_search_cities");
	var cities_select_children = cities_select.childElements();
	for (var i = 1; i < cities_select_children.length; i++) {
		cities_select.removeChild(cities_select_children[i]);
	}

	// Add the "All cities" option
	/*
	var option = document.createElement("option");
	option.setAttribute("value", "");
	option.appendChild(document.createTextNode("(Any city)"));
	cities_select.appendChild(option);
	*/
	
	// Send off the AJAX request for cities in the state
	new Ajax.Request("xml/cities", {
		method:"get",
		parameters:{
			state:selected_state_initials
		},
		onSuccess:ajax_response_america_search_cities,
		onFailure:function() {
			alert("failed!");
		}
	});
}

// Require that Prototype is available
if (typeof Prototype == "undefined") {
} else {
	document.observe("dom:loaded", america_search_states_init);
}
