var LiveSearch = Class.create();
LiveSearch.prototype = {
	initialize: function(searchElement, resultElement, url, options) {
		this.searchElement = $(searchElement);
		this.resultElement = $(resultElement);
		this.url = url;
		this.options = options;
		
		if (!this.options.minChars) {
			this.options.minChars = 3;
		}
		
		if (!this.options.frequency) {
			this.options.frequency = 0.4;
		}
		
		Event.observe(this.searchElement, 'keypress', this.onKeyPress.bindAsEventListener(this));
	},
	
	onKeyPress: function(event)
	{
		if (this.observer) {
			clearTimeout(this.observer);
		}
		this.observer = setTimeout(this.fetchResults.bind(this), this.options.frequency*1000);
	},
	
	fetchResults: function(event)
	{
		if (this.searchElement.value.length >= this.options.minChars) {
			if (this.options.loadingIndicator) {
				$(this.options.loadingIndicator).show();
			}
		
			new Ajax.Request(this.url, {
				method: 'post',
				parameters: 'searchText=' + this.searchElement.value,
				onSuccess: this.updateResults.bind(this)
			});
		}
	},
	
	updateResults: function(transport)
	{
		if (this.options.loadingIndicator) {
			$(this.options.loadingIndicator).hide();
		}
		
		this.resultElement.update(transport.responseText);
	}
};
