/*
* Author:       Michael John Grove
* Version:      0.1 (02 March 2008)
* Description:  Javascript Country DropDown selection with full Province/State selection
*               Fast XHTML compliant Country/State selection list from XML file
* License:      Creative Commons Attribution-Share Alike 2.5 South Africa License (http://creativecommons.org/licenses/by-sa/2.5/za/)
* Fix: 2011-03-21 by Volga Alexandr (make compatibility with Google Chrome and Safari)
*/

/**
 * Browser-independent [A]JAX call
 * 
 * @param {String} locationURL an URL to call, without parameters
 * @param {String} [parameters=null] a parameters list, in the form 
 *        'param1=value1&param2=value2&param3=value3'
 * @param {Function(XHMLHTTPRequest, Object)} [onComplete=null] a function that
 *        will be called when the response (responseText or responseXML of 
 *        XHMLHTTPRequest) will be received
 * @param {Boolean} [doSynchronous=false] make a synchronous request (onComplete
 *        will /not/ be called)        
 * @param {Boolean} [doPost=false] make a POST request instead of GET        
 * @param {Object} [dataPackage=null] any object to transfer to the onComplete 
 *        listener
 * @return {XHMLHTTPRequest} request object, if no exceptions occured
 */
function makeRequest(locationURL, parameters, onComplete, doSynchronous, doPost, dataPackage) {
 
    var http_request = false;
    try {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e1) {
        try {
            http_request= new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e2) {
            http_request = new XMLHttpRequest();
        }
    }
 
    //if (http_request.overrideMimeType) { // optional
    //  http_request.overrideMimeType('text/xml');
    //}
 
    if (!http_request) {
      alert('Cannot create XMLHTTP instance');
      return false;
    }
 
    if (onComplete && !doSynchronous) {
        completeListener = function() { 
            if (http_request.readyState == 4) {
                if (http_request.status == 200) {
                    onComplete(http_request, dataPackage)
                }
            }
        };
        http_request.onreadystatechange = completeListener;
    }
 
    //var salt = hex_md5(new Date().toString());
    if (doPost) {
        http_request.open('POST', locationURL, !doSynchronous);
        http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http_request.setRequestHeader("Content-length", parameters.length);
        http_request.setRequestHeader("Connection", "close");
        http_request.send(parameters);
    } else {
        http_request.open('GET', locationURL + (parameters ? ("?" + parameters) : ""), !doSynchronous);
        //http_request.open('GET', './proxy.php?' + parameters +
                    // "&salt=" + salt, true);
        http_request.send(null);
    }
 
    return http_request;
 
}

/**
 * Loads any XML using synchronous XMLHttpRequest call.
 * @param {String} fileName name of the file to be loaded
 * @return {XMLDocument|Object}
 */
function loadXML(fileName) { 
    // no parameters, no handler, but synchronous
    var request = makeRequest(fileName, null, null, true);
        return request.responseXML;
}
// Load XML file before html loads
var xmlDoc = loadXML("advcountry_state.xml");
/*
// For IE based browsers (tested under IE6 and IE7):
if (window.ActiveXObject) 
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
}
// For Mozilla based browsers (Netsacpe/Firefox):
else if (document.implementation && document.implementation.createDocument) 
{
    xmlDoc = document.implementation.createDocument("","doc",null);
}

// Turn off asynchronus download.
// Load the entire file before trying to do anything with it.
xmlDoc.async=false;

//load the country/state XML file
xmlDoc.load("advcountry_state.xml");
*/
// Populate selected dropdown list with data from XML file
// (<option value="County/StateName">County/StateName</option>)
// Function used for both Country Fill and State Fill 
function fillList(selectbox,text,value)
{
    var optionValue = document.createElement("option");
    optionValue.text = text;
    optionValue.value = value;
    selectbox.options.add(optionValue);
}

// Populate Country list on page load
// Requires: <body onload="fillCountryList();"> on HTML page
function fillCountryList ()
{
	// Get country element ID
	var countryList = document.getElementById("cboCountry");

	// Clear any current values in select box
	// If JavaScript isn't working existing text will remain
	for (var x = countryList.options.length-1; x >-1; x--)
	{
		countryList.options[x] = null;
	}
	// Fill Country name Array from XML file
	var countryNames = xmlDoc.getElementsByTagName("country");
	
	// Gets total Number of countries in XML file
	var numberOfCountries = countryNames.length; // childNodes
	
	// Loop through Country name Array and populate country select
	for (var i=0; i<=numberOfCountries-1; i++)
	{
		var currentCountry =  countryNames[i].getAttribute("name");
		fillList(countryList,currentCountry,currentCountry);
	}
}

// Populate State/Province list on Country change
function fillStateList()
{
    
	// Get State/Province element ID
    var stateList = document.getElementById("cboState")
    
    // Clear any current values in select box
    // If JavaScript isn't working existing text will remain
  for (var x = stateList.options.length-1; x >-1; x--)
    {
        stateList.options[x] = null;
    }
    
    // Get currently selected ID from country element ID
    var countryListSelected = document.getElementById("cboCountry").selectedIndex;
    // Get number of states for current selected Country (populates Array)
    var numberStates = xmlDoc.getElementsByTagName("country")[countryListSelected].getElementsByTagName("state").length;
   
   // Loop through States/Province Array and populate State/Province selection for current Country
    for (var i=0; i<=numberStates-1; i++)
    {
        var currentState =  xmlDoc.getElementsByTagName("country")[countryListSelected].getElementsByTagName("state")[i].firstChild.nodeValue;
        fillList(stateList,currentState,currentState);
    }
        
}

