(function($) {
$.fn.ajaxSearch = function(options) {
	options = $.extend({}, $.ajaxSearcher.defaults, options);
	
	this.each(function(){
		new $.ajaxSearcher(this,options);
	});
	return this;
}

$.ajaxSearcher = function(input, options) {
	var $guideObject,$input = $guideObject = $(input), boxMouseDown = false, curObj, mostRecentHideTimer=0, lastValue = '';
	
	function init() {
		curObj = $('#'+options.targetDiv);
		curObj.css('display','none').addClass('_ajaxSearch');
		$input.focus(function() {
			clearTimeout(mostRecentHideTimer);
			curObj.stop(true, true).fadeOut('fast');
			$('body').mousedown(global_mousedown_listener);
			show();
		}).blur(function(){
			prepare_hide();
		});

		$input.keyup(function() {
			if ($input.val() != lastValue) {

				var q = $input.val();
				clearTimeout(mostRecentHideTimer);

				jQuery.get(options.url + q, function (data) {
					if (data.length) {
						curObj.html(data);
					}
				});
				lastValue = $input.val();
			}
		});




	}
	
	// This is evaluated each time to prevent probs with elements with display none
	function align() {
		var offsets = $guideObject.position(),
			left = offsets.left + $guideObject.width() + options.incrementLeft,
			top = offsets.top + options.incrementTop;

		curObj.css({position:"absolute",top:top,left:left});
	}
	
	function show() {
		align();
		curObj.stop(true, true).fadeIn(options.speedIn);
	}
	
	function prepare_hide() {
		// We want to allow user to select and copy/paste content from the box
		// So delay a bit to see where user click
		$('body').click(global_click_listener);
		if (boxMouseDown) return;
		mostRecentHideTimer = setTimeout(function(){hide()},options.typeDelay);
	}
	
	var global_click_listener = function(e) {
		var $e = $(e.target),c='._ajaxSearch';
		clearTimeout(mostRecentHideTimer);
		if ($e.parents(c).length == 0 && $e.is(c) == false) hide();
	};
	
	// Prevent hiding when selecting..
	// When user Select a text to select, a Mousedown is fired BEFORE blur of input
	// This why we need to know when a Mousedown is done to our object
	var global_mousedown_listener = function(e) {
		var $e = $(e.target),c='._ajaxSearch';
		boxMouseDown = ($e.parents(c).length != 0 || $e.is(c) != false);
	}
	
	function hide() {
		$('body').unbind('click',global_click_listener);
		$('body').unbind('mousedown',global_mousedown_listener);
		align();
		curObj.stop(true, true).fadeOut(options.speedOut);
	}
	
	init();
	return {}
};


$.ajaxSearcher.defaults = {
	speedIn:200, 
	speedOut:100, 
	targetDiv:'', 
	typeDelay:100,
	url:'obligatoriu',
	incrementLeft:12,
	incrementTop:4,
	menuwidth:200
}

})(jQuery);
