var AutoSearch = new Class({
	Implements: [Options, Events],
	options: {
		container:'auto-search-results',     //the container to hold search results
		searchResultsClass:'.auto-search',   //the css class for items returned by search
		searchInputFields:[],                //the input field(s) to supply search term
		onChange: $empty
	},
 	initialize: function(input, url, options) {
		this.setOptions(options);
		this.options.container = $(this.options.container);
		this.input = $(input);  //input field to trigger the auto search
		this.url = url;           //the url of the method that executes the search and returns the html results
		this.input.addEvent('keyup',function(event) {
			var event = new Event(event).stop();
			this.style_container();
			this.do_search();
		}.bind(this));
		window.document.addEvent('click', function(){
		   this.options.container.setStyle('display','none');  //hides the auto search results with a click in document window
		 }.bind(this));            
        },
	style_container: function() {
		 // positions the container of search results just underneath the input box
		var coordinates = this.input.getCoordinates();
		var top = (coordinates.top + coordinates.height);
		var left = coordinates.left;
		var width = coordinates.width - 2;
		this.options.container.setStyles({
			'display':'block',
			'top':top,
			'left':left,
			'width':width
		
		});     
	},
	do_search: function() {
		//conducts the search and puts result in input box when clicked
		var that = this;
		var length = this.options.searchInputFields.length;
		if(length > 0) {
				var post = new Object;
				 this.options.searchInputFields.each(function(item, index) {
						 post[item]=$(item).getProperty('value');
				 });
		   
		} else {
				var post = {'auto_search':this.input.getProperty('value')}; 
		}
	  var auto_search = new Request.HTML({
				url:this.url,
				update:this.options.container,
				onComplete:function(){
					   $$(that.options.searchResultsClass).each(function(element) {
							   element.addEvent('click', function() {
										var text = element.get('text');
										that.input.setProperty('value',text);
								});    
						});  
				}
		}).post(post);
	}   
});

