// This JavaScript provides a means of obtaining a list of 
// Country Subdivisions (ex. states, provinces, etc)
// based on a selected country using AJAX. (Yay, an excuse to use AJAX!)

/**
 * Creates an XMLHttpRequest object for sending AJAX requests to the server.
 */
function getXmlHttpObject() {
  var xmlHttp;
  try {
    xmlHttp = new XMLHttpRequest();
  } catch (e) {
    // Internet Explorer
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        return null;
      }
    }
  }
  return xmlHttp;  
}

/**
 * A JavaScript function that takes the value of a selected country code from a
 * list of countries expected in a <select> element with an id of
 * 'countrySelect', and then sends that country code to the
 * UpdateCountrySubdivisionsAction on the server side, and expects to receive
 * back a JSON array of provinces (or states or whatever subdivision for a
 * particular country).
 * 
 * It will then generate a new <select> list of provinces which it then places
 * inside an expected element in the page with the id 'provinceSelect', which
 * should contain the input element for specifying a province. However, if the
 * JSON array retrieved from the server is empty, then it assumes that the
 * database does not contain a list of provinces for the selected country, and
 * instead puts in a <input> with the type set to 'text', so that the user can
 * input the province/state/region name manually.
 * 
 * @param subdivisionPropertyName
 *            The name of the property associated with the province in the
 *            page's form
 * @return
 */
function updateCountrySubdivisionList(subdivisionPropertyName, subdivisionValue) {
  	countrySelect = document.getElementById('countrySelect');
  	if (countrySelect == null) return false;
  	
  	selectedCountry = countrySelect.options[countrySelect.selectedIndex].value;
    url = "update_country_subdivisions?countryCode=" + selectedCountry;
    
    var xmlHttp = getXmlHttpObject();
    if (xmlHttp == null) {
   		document.getElementById('updateSubdivisionError').innerHTML = "Error encountered Your browser does not appear to support AJAX";
    	return false;
    }
    
    xmlHttp.open("GET", url, true); 
	function updateProvinceSelect() {
	    if (xmlHttp.readyState == 4) { 
			try {
				if (xmlHttp.status == 200) { 
		        	var fields = eval('('+xmlHttp.responseText+')');
		        	var newHTML='';
		        	if (fields.length == 1 && fields[0].code == '') {
		        		if (fields[0].name == 'N/A') {
							newHTML = '<input id="provinceSelect" type="text" name="' + subdivisionPropertyName + '" maxlength="60" style="width:250px; height:22px;" value="' + subdivisionValue + '"/>';
						} else {
							newHTML = '<select name="' + subdivisionPropertyName + '" size="1"><option value="">Please Choose Country First</option></select>';
						} 	
		        	} else {
		        		newHTML = '<select id="provinceSelect" name="' + subdivisionPropertyName + '" size="1">';
					    for (i=0; i< fields.length; i++) {
					    	if (fields[i].code == subdivisionValue) {
					    		newHTML += '<option value="' + fields[i].code + '" selected="true">' + fields[i].name + '</option>';
					    	} else {
					    		newHTML += '<option value="' + fields[i].code + '">' + fields[i].name + '</option>';
					    	}
					    }
					    newHTML += '</select>';
					}
					document.getElementById('provinceInput').innerHTML = newHTML;
		        } else {
		    		document.getElementById('updateSubdivisionError').innerHTML = "Error encountered. xmlHttp.status =" + xmlHttp.status + "\n" + xmlHttp.responseText;
		  		}
	        } catch (err) {
	        	document.getElementById('updateSubdivisionError').innerHTML = "Error encountered." + err.description;
	        }
		}  
	}
    xmlHttp.onreadystatechange = updateProvinceSelect;
    xmlHttp.send("");
}
