/* Ajax Autocompleter for use with SiteBuilder */
/* Allows use of a SiteBuilder page as a proxy for another server */

/**
  * Ajax.Autocompleter.Custom extends the Scriptaculous autocompleter control so 
  * that the server response can be of any kind. You 
  * need to pass a callback function among the options (responseProcessor)
  * responsible to parse the server response and return the HTML <ul>
  * expected by the usual Ajax.Autocompleter. If no function is passed then the
  * server must respond with a <ul> like Ajax.Autocompleter expects.
  *
  * @author Alessandro Lacava (http://www.alessandrolacava.com)
  */

Ajax.Autocompleter.Custom = Class.create(Ajax.Autocompleter, {
	initialize: function(element, update, url, options) {
		this.baseInitialize(element, update, options);
		this.options.asynchronous  = true;
		this.options.onComplete    = this.onComplete.bind(this);
		this.options.defaultParams = this.options.parameters || null;
		this.url                   = url;
		this.options.responseProcessor = this.options.responseProcessor || Prototype.K;
	},

	onComplete: function(request) {
		var htmlUL = this.options.responseProcessor(request.responseText, this.element);
		if(htmlUL) {
			this.updateChoices(htmlUL);
		}
	}
});

function htmlResponseProcessor(respText, elem) {
	var staff = respText;
	var ret = staff.match(/<ul>[.\s\S]*<\/ul>?/igm);
	return ret;
}

function getSelectedId(text, li) {
	$('wmgid').value=li.id;
}
		
function buildAutocompleter() {
	new Ajax.Autocompleter.Custom(
		'staff_name',
		'staff_list',
		'/fac/sci/wmg/ssproxy?xdoplain=true',
		{
			responseProcessor : htmlResponseProcessor, 
			afterUpdateElement : getSelectedId
		}
	);
}

Event.observe(window, "load", buildAutocompleter);
