/**
 * 
 * Livesearch with Key Press Nav
 * 
 *
 */

 $(document).ready(function() {
		var currentSelection = -1;

	$("#search-box").blur( function() {
		$('#suggestions').fadeOut();
		currentSelection = -1;
	});
	
	$(document).keydown(function(e) {
		switch(e.keyCode) { 
			// User pressed "up" arrow
			case 38:
				navigate('up');
			break;
			// User pressed "down" arrow
			case 40:
				navigate('down');
			break;
			// User pressed "enter"
			case 13:
				if(currentUrl != '') {
					window.location = currentUrl;
				}
			break;
		}
	});
	
	$("#search-box").keypress(function (e) {
		if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25) || (97 <= e.which && e.which <= 97 + 25)) {
			lookup(this.value);
			currentSelection = -1;
		}
	});

	$("#suggestions").mouseover( function() {
		$("#searchresults a").removeClass('itemhover');
	})

	
	function setSelected(menuitem) {
		$("#searchresults a").removeClass("itemhover");
		$("#searchresults a").eq(menuitem).addClass("itemhover");
	
		
		//currentUrl = $("#searchresults a").eq(menuitem).attr("href");
	}

	function navigate(direction) {
		// Check if any of the menu items is selected

		if(direction == 'up' && currentSelection != -1) {
			if(currentSelection != 0) {
				currentSelection--;
			}
		} else if (direction == 'down') {
			
			console.log("Down "+$("#searchresults a").size());
			if(currentSelection != ($("#searchresults a").size() -1)) {
				currentSelection++;
			}
		}
		setSelected(currentSelection);
	}

	$("#searchFilter li").click( function() {
		$("#searchFilter li").removeClass();
		$(this).addClass('selected');
		$('#search-box').val("");
	});
	
});

 function lookup(inputString) {
	if(inputString.length == 0) {
      $('#suggestions').fadeOut(); // Hide the suggestions box
	} else {
		if(inputString.length > 1)
		{
			$.post("/_inc/liveSearch.php", {queryString: ""+inputString+"",filter:$("#searchFilter li[class=selected]").attr('id') }, function(data) { // Do an AJAX call
			$('#suggestions').fadeIn(); // Show the suggestions box
			$('#suggestions').html(data); // Fill the suggestions box
			});
		}
	}	
}