function setCountryAndRegion(location) {
	for (var i = 0; i < locations.length; i++) {
		// check for match on country
		if (String(locations[i][1]).toLowerCase() == location) {
			setListValue('country', location);

		// check for region, and work backwards to update its country
		} else if (String(locations[i][0]).toLowerCase() == location) {
			setListValue('country', locations[i][1]);
			setListValue('region', location);
		}
	}
}

function setListValue(id, value) {
	var list = document.getElementById(id);

	for (var i = 0; i < list.options.length; i++) {
		if (list.options[i].value.toLowerCase() == String(value).toLowerCase())
		{
			list.options.selectedIndex = i;
			list.onchange();

			break;
		}
	}
}

function countryChanged(selectedOption) {
	var list = document.getElementById('region');

	document.getElementById('location').value = selectedOption.value;
	
	// clear existing options by removing the 0 index until
	// there's no more, if we for loop the options the array
	// is changed as we loop so it fails to remove all items.
	while (list.options.length > 0)
		list.options[0] = null;

	addOption(list, 'No Preference', '');

	if (selectedOption.value == '') {
		list.disabled = true;
		document.getElementById('location').value = '';
	} else {
		if (list.disabled)
			list.disabled = false;

		// loop regions and find ones belonging to selected country,
		// adding them to the list
		for (var i = 0; i < locations.length; i++) {
			if (locations[i][1] == selectedOption.text)
				addOption(list, locations[i][0], locations[i][0].toLowerCase());
		}
	}
}

function regionChanged(selectedOption) {
	// if the region has been set to no preference, set location to the selected country
	if (selectedOption.value == '') {
		country = document.getElementById('country');
		document.getElementById('location').value = country.options[country.selectedIndex].value;
	} else {
		document.getElementById('location').value = selectedOption.value;
	}
}

function addOption(list, text, value) {
	var option = document.createElement('option');
	option.innerHTML = text;
	option.value = value;

	list.appendChild(option);
}