/*
		Generic Javascript functions for PLEADE.
		
		Depends on the availability of Prototype library, version
		1.5 (or above, but not tested).
		
		See http://www.prototypejs.org/
*/

/*
	This function will update a list with values obtained from the
	search engine. Parameters are:
	
		divName:		the id (or name) of the source list's enclosing div
		sourceName:		the id (or name) of the source list (the one giving the value)
		targetName:		the id (or name) of the target list (the one that will be updated)
		firstOption:	the value of the first option of the target list (ay be empty or null)
	
	When this function is called, it will query (using Ajax) the search engine in order to
	get terms for the field "targetName". These values will be "filtered", only terms for
	which there are documents with sourceName = sourceName.selectedValue.
	
	For instance, suppose we have these values:
		sourceName=region
		targetName=city
		firstOption=-- Please select a city --
	
	The method will take the selected value of the "region" list in the form. Suppose
	it is "Aquitaine". Then it will search for terms in the "city" field, filtered with
	region="Aquitaine".
	
	These terms will be put into the "city" list, and this list's first option will be
	"-- Please select a city--".
	
	This function depends heavily on the Prototype Javascript library.
*/
function updateSelect(divName, sourceName, firstOption, targetName) {
	// The URL withtout parameters
	var url = '_functions/terms.options.txt';
	
	// The parameter part of the URL
	var params = 'f=' + sourceName;
	if (targetName) params += '&v=' + $F($(sourceName)) + '&f=' + targetName;
	
	// An Ajax request using Prototype
	new Ajax.Request(url, {
		method: 'get',				//FIXME Does this work in Opera ?
		parameters: params,			//Only way to pass multiple values for the same parameter name
		onSuccess: function(transport) {
			
			// If we have a target or not, the list to update is different
			var selectName = targetName ? targetName : sourceName;

			// We build the onchange attribute by using the previous onchange attribute
			var onchange = $(selectName).readAttribute("onchange") != null ? ' onchange="' + $(selectName).readAttribute("onchange") + '"' : '';

			// We build the firstOption if provided
			var fo = firstOption != '' ? '<option value="">' + firstOption + '</option>' : '';
			
			// Then we update the enclosing div's content (updating the select doesn't work in IE)
			$(divName).innerHTML = '<select name="' + selectName + '" id="' + selectName + '"' + onchange + '>' + fo + transport.responseText + "</select>";

			// We select the first item in the list
			$(selectName).selectedIndex = 0;
		}
	});
}

