/**
 *	Determine if we need to show the dropdown box with
 *	cities, clear the previous results and load the cities
 *	we've found.
**/
function showCityDropDown () {
	var	searchField = $('citySearchInput');
	var searchText 	=	searchField.value;

	clearDropDown();

	if(searchText.length >= 2)
		findCities(searchText);
}


/**
 *	Find all cities that start with  the given
 *	searchtext. Ie, if we type in 'Gro' we should get
 *	Groningen, Grollo, etc. Note that this is not and should
 *  not be case sensitive.
 *
 *	@param 	searchText 	String		The text we search for.
 *	@return	Void.
**/
function findCities (searchText) {
	var searchResult = Array();
	var amount			 = 0;

	for (var i = 0; i < cities.length; i++)
		if (cities[i].substr(0, searchText.length).toLowerCase() == searchText.toLowerCase() && ++amount < 12)
			searchResult.push(cities[i]);

	if(searchResult)
		showCities(searchResult);
}


/**
 *	Remove all child elements from the dropdown element,
 *	then hide it.
**/
function clearDropDown () {
	clearElement($('searchDropDownResult'));
	$('searchDropDownResult').style.display = 'none';
}


/**
 *	Add a location option to the given element. This
 *	creates a link node (using the DOM) that can be added
 *	to an element.
 *
 *	@param	location	String		Textual location option string.
 *	@param	element		Element 	Document object where the element is
 *															appended to as a child.
 *	@return	Void.
**/
function addLocationOption (location, element) {
	var newOption 	= document.createElement('div');
	var optionText	=	document.createTextNode(location);
	var linkNode		=	document.createElement('a');
	linkNode.setAttribute('href', 'javascript: selectLocation("' + location + '");');

	linkNode.appendChild(optionText);
	newOption.appendChild(linkNode);

	element.appendChild(newOption);
}


/**
 *	Show the cities given in the searchDropDownResult box
 *	made for it by adding each city to it.
 *
 *	@param	cityList	Array	An array of city text strings.
 *	return 	void.
**/
function showCities (cityList) {
	var resultElement = $('searchDropDownResult')
	for(var i = 0; i < cityList.length; i++)
		addLocationOption(cityList[i], resultElement);
	resultElement.style.display = 'block';
}


/**
 *	Upon selection of a location we want that locations' value to be set to
 *	the "location" input textbox and then hide the locations overview
 *	window again. This does just that.
**/
function selectLocation (location) {
	$('citySearchInput').value = location;
	if ($('ownerData'))
		$('searchDropDownResult').style.display = 'none';
	if ($('citySearch'))		
		$('citySearch').submit();
	else
		clearDropDown();
}
