var countryField = false;
var regionField = false;

function updateRegions()
{
    if (!countryField || ! regionField) {
	return;
    }
    while(regionField.options.length > 1) {
	regionField.remove(regionField.options.length - 1);
    }
    if(countryField.value.length) {
	for(j = 0; j < regions[countryField.value].length; j++) {
	    newel = document.createElement('option');
	    newel.text = regions[countryField.value][j].name;
	    newel.value = regions[countryField.value][j].id;
	    try {
		regionField.add(newel, null); // standards compliant; doesn't work in IE
	    }
	    catch(ex) {
		regionField.add(newel); // IE only
	    }
	}
    }
}

function initSelects()
{
    if (typeof mode == 'undefined') return;
    countryField = document.getElementById(mode + ":country_id");
    regionField = document.getElementById(mode + ":region");
    if (!countryField || ! regionField) {
	return;
    }
    
    for (var item in countries) {
	newel = document.createElement('option');
	newel.text = countries[item];
	newel.value = item;
	try {
	    countryField.add(newel, null); // standards compliant; doesn't work in IE
	}
	catch(ex) {
	    countryField.add(newel); // IE only
	}
    }
    updateRegions();
}



window.onDomReady = initReady;
 
// Initialize event depending on browser
function initReady(fn)
{
    //W3C-compliant browser
    if(document.addEventListener) {
	document.addEventListener("DOMContentLoaded", fn, false);
    }
    //IE
    else {
	document.onreadystatechange = function(){readyState(fn)}
    }
}

//IE execute function
function readyState(func)
{
    // DOM is ready
    if(document.readyState == "interactive" || document.readyState == "complete")
    {
	func();
    }
}



window.onDomReady(initSelects);
