/*
	Wrapper for jQuery's Autocomplete plugin. 
	- Lets us choose whether to use local flat file data
	  or on the fly data from a script.
*/

function autocompleter(text_field_id)
{
	this.field = $('#'+text_field_id);
	this.area = '';
	this.path = 'http://'+window.location.host+'/';
	this.script = 'autocompleter.pl';
	
	this.options =
	{
		minChars: 2,
		max: 10,
		matchContains: true,
		delay: 200,
		selectFirst: false
	};
	
	// ------------------
	
	this.initialise = function(area)
	{
		this.area = area;
		this.options.extraParams = this.params;
		
		if (this.area) {
			this.use_local_data();	// Faster local data
		} else {
			this.use_remote_data();	// Slower remote data
		}
		
		this.field.result($.proxy(this.choose, this));
	};
	
	this.use_local_data = function()
	{
		var self = this;
		$.getJSON(this.path+'js/area_json/'+this.area.toLowerCase()+'.js', function(json)
		{
			self.field.autocomplete(json, self.options);
		});
	};
	
	this.use_remote_data = function()
	{
		this.options.formatItem = function(row)
		{
			return '<span class="'+row[1]+'">'+row[0]+'</span>';
		};
	
		this.field.autocomplete(this.path+this.script, this.options);
	};
	
	this.choose = function(event, data, formatted)
	{
		this.field.parents('form').submit();
	};
}