var arrow = {left: 37, up: 38, right: 39, down: 40 };
var liveselection = -1;

$(document).ready(function() {

$("div.livesearch input").keyup(function(e) {
		
	var keycode = e.keyCode || e.which;
			
	if (keycode == arrow.left | keycode == arrow.up | keycode == arrow.right | keycode == arrow.down) {
		live_navigate(keycode);
		return;
	}
	
	if (keycode == 13) {
		var href;
		
		if (!$('div.livesearch[live_id="active_livesearch"] div.results').attr('hover'))
			href = $('div.livesearch[live_id="active_livesearch"] li.liveselection a').attr('href');
		else
			href = $('div.livesearch[live_id="active_livesearch"] li:hover a').attr('href');
			
		if (href!=undefined)
			window.location.href = href;
		else
			window.location.href = $('div.livesearch[live_id="active_livesearch"] li:first-child a').attr('href');
	}
		
	var $results_div = $(this).parent().find("div.results");
		
	if (this.value.length<3) {
		$results_div.hide();
		return;
	}
		
	var query = this.value;
		
	$.get("/ajax/livesearch.php?q="+query, function(result) {
		if (result != '0') {
			$results_div.show();
			$results_div.html(result);
			liveselection = -1;
		} else {
			$results_div.hide();
		}
	});		
		
});

$("div.livesearch input").blur(function() {
	$(this).parent().removeAttr('live_id', 'active_livesearch');

	var $results_div = $(this).parent().find("div.results");
	$results_div.delay(30).fadeOut("fast");	
});
		
$("div.livesearch input").focus(function() {
	$(this).parent().attr('live_id', 'active_livesearch');
	
	if (this.value.length<3) return;
			
	var $results_div = $(this).parent().find("div.results");
	$results_div.show();
});

$("div.results").mouseover(function() {
	var $active_livesearch = $('div.livesearch[live_id="active_livesearch"]');
	$active_livesearch.find('li.liveselection').removeClass('liveselection');
	$(this).attr('hover','hover');
	
	liveselection = $(this).find('li:hover').index();
});

});

function live_navigate(e) {

	var $active_livesearch = $('div.livesearch[live_id="active_livesearch"]');
	$active_livesearch.find('div.results').removeAttr('hover');
	
	if (e == arrow.down) {
		liveselection = (liveselection<$active_livesearch.find('li').length-1) ? liveselection+1 : -1;
	} else if (e == arrow.up) {
		liveselection = (liveselection>-1) ? liveselection-1 : $active_livesearch.find('li').length-1;
	} else if (e == arrow.right && liveselection==-1) {
		liveselection = 0;
	}

	$active_livesearch.find('li:hover').removeAttr('class');
	$active_livesearch.find('li.liveselection').removeClass('liveselection');
	if (liveselection>=0) $active_livesearch.find('li').eq(liveselection).addClass('liveselection');
}

