(function($){
	
	//prototype and create instances
	
	function KeySearch(){
		
	}
	KeySearch.prototype.inp = null;
	KeySearch.prototype.page = null;
	KeySearch.prototype.params = null;
	KeySearch.prototype.timer = null;
	KeySearch.prototype.wrapper = null;
	KeySearch.prototype.ul = null;

	KeySearch.prototype.init = function( inp, page, params, callback ){
		var 
			self = this;
		
		self.inp = inp;
		self.page = page;
		self.params = ( params ? params : {} );

		//calls callback as inp

	
/*		self.callback = function(r){
			var cb = (callback ? callback : self.callback );
			//just to make sure input field hasn't been cleared
			if(self.inp.val() != ""){
				cb.call( self.inp, r );
			}
		};
*/

		self.createElements();
		
		self.inp.keyup(function(){
			self.setTimer.call( self ); 
		});

		return self;
	};

	KeySearch.prototype.createElements = function(){
		var 
			self = this,
			divId = "_keySearch" + self.inp.attr("id") + "Wrapper",
			ulId = "_keySearch" + self.inp.attr("id") + "Rslts",
			newDiv = $("<div></div>").attr({"id":divId}),
			newUL = $("<ul></ul>").attr({"id":ulId}),
			wrapperCss = {
				"width": "auto",
				"float":"left"
			},
			ulCss = {
				"float":"left",
				"width":self.inp.width()
			};
				
		self.inp.wrap(newDiv);
		self.wrapper = $("div#"+divId);
		
		self.wrapper.css( wrapperCss ).append( newUL );
		
		self.ul = $( "ul#" + ulId );
		
		//lis and css in the callback
		self.ul.css( ulCss ).hide();
		
		return true;
	};
		
	KeySearch.prototype.setTimer = function(){
		var
			self = this;
		
		if ( self.inp.val() == "" ){
			return false;
		}
		
		//kills timer if going...
		if(self.timer != null){
			clearTimeout(self.timer);
		}
		
		self.timer = setTimeout( function(){
			self.execute.call( self );
		}, 600);
		
		return true;		
	};
	
	KeySearch.prototype.execute = function(){
		var 
			self = this;
		
		//default string for searching. any other params can be added in the jquery code.
		self.params._keyStr = self.inp.val();
		$.post( self.page, self.params, function(r){
			self.callback.call(self.inp, self, r);
		});
		return true;
	};

	KeySearch.prototype.callback = function(kS, r){
		kS.ul.html(r);
		console.log(kS)
		//presuming it sends back uniform or li elems as child elems
		kS.ul.show().children().css({
			"float":"left",
			"width":"98%",
			"padding":"1%"
		}).filter(":even").css({
			"backgroundColor":"rgb(220,220,220)"
		});
	
	};


	
	$.fn.keySearch = function( page, params, callback){
		var 
			inp = $(this),
			kS = new KeySearch();
			
		kS.init( inp, page, params, callback );
		
		return inp;
	};
})(jQuery);