/**
 * Start index in the list for US states
 */
var usStart = 1;
/**
 * End index in the list for US states
 */
var usEnd = 66;

/**
 * Start index in the list for Canadian provinces
 */
var caStart = 70;
/**
 * End index in the list for Canadian provinces
 */
var caEnd = 83;

/**
 * Contains all states loaded by #storeStates()
 */
var states = new Array();

function State() {
	this.value;
	this.label;
	this.name;
}
	
/**
* Remembers all states.
* @param selectElementId The select element ID with the states.
*/
function storeStates(selectElementId) {
    try
    {
        var el = getElementById(selectElementId);
        if (el != null)
        {
        	var state;
			for (var i = 0; i<el.length; i++) 
			{
				state = new State();
				state.value = el[i].value;
				state.text = el[i].text;
				state.label = el[i].label;
				states[i] = state;
			}
	    }
    }
    catch(e)
    {
        // ignore exception
    }
}

/**
* Gets an element by its ID.
* @param elementId The element ID.
* @return The element object. 
*/
function getElementById(elementId) {
	var el = null;
	if (document.all)
	{
	    el = document.all[elementId];
	}
	else
	{
	    el = document.getElementById(elementId);
	}
	return el;
}

/**
 * Appends a new option element with a state.
 * @param selectElement The select element.
 * @param stateIndex The index in the states array.
 */
function appendOptionLast(selectElement, stateIndex)
{
  var elOptNew = document.createElement('option');
  elOptNew.text = states[stateIndex].text;
  elOptNew.value = states[stateIndex].value;
  elOptNew.label = states[stateIndex].label;
 
  try {
    selectElement.add(elOptNew, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    selectElement.add(elOptNew); // IE only
  }
}

/**
 * Shows the state for a countryCode.
 * @param selectElementId The select element ID with the states.
 * @param countryCode The coutry code.
 */
function showStatesForCountry(selectElementId, countryCode) {
    try
    {
        el = getElementById(selectElementId);
        if (el != null)
        {
        	var selectedValue = el.value;
        	var start = 0;
        	var end = 0;
			if (countryCode == "US") 
			{
				start = usStart;
				end = usEnd;
			}
			else if (countryCode == "CA") 
			{
				start = caStart;
				end = caEnd;
			}
			// remove all
			while(el.hasChildNodes())
			{
				el.removeChild(el.lastChild);
			}
			// always display select field
			appendOptionLast(el,0);
			for (var i = start; i<end; i++) 
			{
				appendOptionLast(el,i);
			}
			// set to first if by default
			el.selectedIndex = 0;
			for (var i=1; i<el.length;i++) {
				if (el[i].value == selectedValue && el[i].value != null && el[i].value != "") {
					el.selectedIndex = i;
				}
			}
	    }
    }
    catch(e)
    {
        // ignore exception
    }
}
	
