/*
 * Province and District Functions (AJAX)
 */
function changeProvince(removeAll) {
	var code = getValue("province_code");
	var sea_code = getValue("sea_code");
	var district = getElement("district_code");
	var district_name = district.options[district.selectedIndex].text;
	var district_code = district.value;
	district.length = removeAll ? 0 : 1;
	if (!code) return;
	district.disabled = true;
	var xmlhttp = new XMLHttp;
	xmlhttp.onReceive = function(xmlhttp) {
		var xmlroot = xmlhttp.parse();
		if (xmlroot) {
			if (xmlroot.error) {
				showAlert(xmlroot.error.text);
			} else if (xmlroot.district) {
				var list = xmlroot.district.length ? xmlroot.district : [xmlroot.district];
				var district = getElement("district_code");
				district.disabled = false;
				for (var i = 0; i < list.length; i++) {
					var e = district.appendChild(createOption(list[i].code,list[i].name));
					if (list[i].code == district_code && list[i].name == district_name) {
						e.selected = true;
						changeDistrict();
					}
				}
			}
		} else showAlert("Invalid XML data.");
	};
	xmlhttp.receive("get_districts.php?province_code="+code+(sea_code ? "&sea_code="+sea_code : ""));
	updateMap();
}

function changeDistrict() {
	updateMap();
}

function updateMap() {
	if (typeof(map) == "undefined" || !map) return false;
	var province_code = getValue("province_code");
	var district_code = getValue("district_code");
  var xmlhttp = new XMLHttp;
	xmlhttp.onReceive = function(xmlhttp) {
		var xmlroot = xmlhttp.parse();
		if (xmlroot) {
			if (xmlroot.error) {
				showAlert(xmlroot.error.text);
			} else {
				var box = xmlroot.box;
				if (box && box.latmin && box.lonmin && box.latmax && box.lonmax) {
		      if (typeof(map) != "undefined") {
		        var bounds = new GLatLngBounds(new GLatLng(box.latmin,box.lonmin),new GLatLng(box.latmax,box.lonmax));
		        map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
		      }
				}
			}
		} else showAlert("Invalid XML data.");
	}
	xmlhttp.receive("get_bounding_box.php?province_code="+province_code+(district_code ? "&district_code="+district_code : ""));
}

/* Initialize variables */
addEvent(window,"load",function() {
	if (!getValue("latitude") && !getValue("longitude") && getValue("province_code")) updateMap();
});
