/**

	Javascript for controlling the country/city search boxes

**/

countryArray = new Array();

// if window already has an onload function defined
if(typeof window.onload == 'function')
{
	//store it
	var existing = onload;
	
	//add new onload handler
	window.onload = function()
	{
		//call existing onload function
		existing();
		
		//call bespoke onload function		
		showHide();
	};
}
else
{
	//setup onload function
	window.onload = function()
	{
		showHide();
	}
}


/* Hides the non-javascript country/city dropdown and shows/initialises 
   the separate js-controlled ones instead. */

function showHide()
{
	document.getElementById('countryCityItem').style.display="none"
	
	if(document.getElementById('countryItem').nodeName=="DIV")
	{
		document.getElementById('countryItem').style.display="block"
	}
	else document.getElementById('countryItem').style.display="list-item"
	
	if(document.getElementById('cityItem').nodeName=="DIV")
	{
		document.getElementById('cityItem').style.display="block"
	}
	else document.getElementById('cityItem').style.display="list-item"
		
	initialiseCountryDropdown()
}


/* Populates the country dropdown with the list of countries */

function initialiseCountryDropdown()
{
	countryDropdown = document.getElementById('countryDropdown')
	
	// hook the onchange event to the populateCity function
	countryDropdown.onchange = function(){populateCity();}
	
	for (country in countryArray)
	{
		addOption(countryDropdown, countryArray[country][0], countryArray[country][1], currentCountry)
	}
	
	populateCity();
}


/* Populates the city dropdown with the list of cities for
   the currently-selected city */

function populateCity()
{
	country = document.getElementById('countryDropdown').value
	cityDropdown = document.getElementById('cityDropdown')
	
	clearOptions(cityDropdown)
	
	if(country=='')
	{
		addOption(cityDropdown,'', 'Choose a city / town', currentCity)
	}
	else if (countryArray[country][2].length > 0)
	{		
		addOption(cityDropdown,'', '', currentCity)
		
		for (city in countryArray[country][2])
		{
			addOption(cityDropdown,countryArray[country][2][city][0], countryArray[country][2][city][1], currentCity)
		}
		
	//	auto-select city if only one is in the list
		if (countryArray[country][2].length == 1)
		{
			cityDropdown.selectedIndex = 1;
		}
	}
	else addOption(cityDropdown, '', 'All', currentCity)
}


/* Adds an option to a select box */

function addOption(dropdown, value, text, selected)
{
	var opt = document.createElement('option');
	opt.value = value
	opt.text = text
	
	if (value==selected)
	{
		opt.defaultSelected = true;
		opt.selected = true;
	}
	
// TODO test	opt.setAttribute("selected", "selected");
	
	try
	{
		dropdown.add(opt, null); // standards compliant; doesn't work in IE
	}
	catch(ex)
	{
		dropdown.add(opt); // IE only
	}
}


/* Clears all options from a select box */

function clearOptions(dropdown)
{
	dropdown.options.length = 0
}
