// +----------------
// | Search Suggest 
// | Author: Kai Johnson
// | Author URI: www.goldentreestudio.com
// | Contributor: Frank Perez
// | Contributor URI: www.frankperez.net
// +----------------

(function($){
	
	$.fn.searchSuggest = function(pathToSearch){
		$form = $(this);
		$input = $form.find('input[type="text"]');
		var pos = $form.position(),
			ht = $input.outerHeight(true),
			active = -1,
			back = 0,
			timer = 0,
			popuptimer = 0,
			hovertimer = 0;
		
		$popup = $('<div id="searchSuggest"></div>').css({'top':pos.top+ht + 12,'left':pos.left + 6}).insertAfter($input).hide();
		
		$input.keyup(function(e){
			active = -1;
			var search = $input.val();
			switch(e.which) {
				case 40: //down - scroll through suggestion list
					e.preventDefault();
					clearTimeout(popuptimer);
					moveSelect(1);
				break;
				case 38: //up - do nothing 
				break; 
				case 27: //esc - clear the suggestion list
					$popup.fadeOut(250);
				break;
				default:
					if(search == '') $popup.delay(250).fadeOut(250);
					else {
						clearTimeout(timer);
						timer = setTimeout(function(){
							$.post(pathToSearch, {s: search}, function(r){
								$popup.html(r).stop(true, true).fadeIn(250);
								$list = $popup.children('ul').children('li');
								count = $list.length;
							});
						}, 100);
					}
				break;
			}
		});

		// $popup.live('mouseover', function(){
			// if ( $('.searchresults').length > 0 ) {
		$popup.hover(function(){
			clearTimeout(hovertimer);
			$list.removeClass('active');
		}, function(){
			hovertimer =
				setTimeout(function(){
					$popup.fadeOut(250);
				}, 1000);
		});
		
		$popup.keydown(function(e){
			if(e.which == 38 || e.which == 40){
				e.preventDefault();
				dir = e.which == 38 ? -1 : 1;
				moveSelect(dir);
			}
		});
			// }
		// });
		
		var moveSelect = function(step) {
			if(typeof(count) == 'undefined' || count == 0) return;
			active += step;
			if (active == '-1'){
				$input.focus();
				$list.removeClass('active');
				popuptimer =	
					setTimeout(function(){
						$popup.fadeOut(250);
					}, 500);
				return;
			} 
			if (active < 0 || active >= count) {
				active = 0;
			}  
			$list.eq(active).addClass('active').siblings().removeClass('active');
			$list.eq(active).children('a').focus();	
		};
	};
})(jQuery);
