var $lsLastValue = false;

$(function() {
	$("#search").attr("autocomplete", "off");
	
	$("#searchbox").keyup(function() {
		$q = $("#searchbox").val();

		if($q != $lsLastValue) {
			if($q.length > 3) {
				$.ajax({
					type: "POST",
					data: "q=" + $q,
					url: "/livesuche.php",
					success: function($data) {
						if($data != 0) {
							$("#livesuche").html("");
							$("#livesuche").html($data).slideDown("fast");

							$(document.body).click(function(event) {
								var clicked = jQuery(event.target);
								var test = (clicked.is("#livesuche") || (clicked.parents("#livesuche").length > 0) || clicked.is('input'));

								if (test == false) {
									$("#livesuche").slideUp("fast");
								}
							});

						} else {
							$("#livesuche").hide();
						}
					}
				});
			} else {
				$("#livesuche").hide();
			}
		}

		$lsLastValue = $q;
	});
	
	$("#searchbox").keydown(function(e) {
		$key = e.keyCode;
		if($key != 13 && $key != 27 && $key != 38 && $key != 40) {
			return true;
		}
		
		$set = $("#livesuche ul li a");
		$links = $("#livesuche a");
		$active = $("#livesuche li a.active");
		$first = $("#livesuche a:first");
		$last = $("#livesuche a:last");
		$index = $set.index($active);
		$length = $set.length;
		
		switch($key) {
			case 13:
				e.preventDefault();
				if($active.length == 1) {
					document.location.href = $active.attr("href");
					return false;
				} else {
					$("#search").submit();
					return false;
				}
			break;
			
			case 27: 
				$("#livesuche").slideUp("fast");
				return false;
			break;
			
			case 38:
				e.preventDefault();
				if($active.length == 0) {
					$last.addClass("active");
					return false;
				} else {
					$active.removeClass("active");
					if($index == 0) { 
						$index = $length;
					}
					$set.eq(parseInt($index) - 1).addClass("active");
					return false;
				}
			break;
			
			case 40: 
				e.preventDefault();
				if($active.length == 0) {
					$first.addClass("active");
					return false;
				} else {
					$active.removeClass("active");
					if($length - 1 == $index) { 
						$index = -1;
					}
					$set.eq(parseInt($index) + 1).addClass("active");
					return false;
				}
			break;
		}
	});
	
});


