var theTimeout;
var liveSearchLast = '';
var isIE = false;
var searchInProgress = false;

function liveSearchInit()
{
	if ($('livesearch'))
	{
		if (navigator.userAgent.indexOf("Safari") != -1)
		{
			$('livesearch').addEventListener("keydown",liveSearchKeyPress,false);
		} else if (navigator.product == "Gecko") {
			$('livesearch').addEventListener("keypress",liveSearchKeyPress,false);
		} else {
			$('livesearch').attachEvent('onkeydown',liveSearchKeyPress);
			isIE = true;
		}
		$('livesearch').setAttribute("autocomplete","off");
	}
}

function liveSearchKeyPress(event)
{
	var theKey = event.keyCode;
	var hl = $('LSHighlight');
	var res = $('LSRes');
	switch (theKey)
	{
		case 27: //ESC
			if (hl)
				hl.removeAttribute('id');
			closeResults();
			document.forms.searchform.s.value = '';
			liveSearchLast = '';
			return;
			break;

		case 40: //KEY DOWN
			if (!hl){
				hl = res.firstChild;
			} else {
				hl.removeAttribute('id');
				hl = hl.nextSibling;
			}
			break;

		case 38: //KEY UP
			if (!hl) {
				hl = res.lastChild;
			} else {
				hl.removeAttribute('id');
				hl = hl.previousSibling;
			}
			break;

		case 9: // TAB
			if (theTimeout)
				window.clearTimeout(theTimeout);

		default: // all other keys
			return;
			break;
	}
	if (hl)
			hl.setAttribute('id','LSHighlight');
	if (!isIE)
		event.preventDefault();
}

function liveSearchStart()
{
	if (theTimeout)
		window.clearTimeout(theTimeout);
	theTimeout = window.setTimeout("liveSearchDoSearch()",400); // 400ms should be enough
}

function liveSearchDoSearch()
{
	if (searchInProgress) return false;
	var theTerm = document.forms.searchform.s.value;
	if (liveSearchLast != theTerm)
	{
		if (theTerm == '')
		{
			$("LSResult").style.display = "none";
			highlight = $("LSHighlight");
			if (highlight) {
				highlight.removeAttribute("id");
			}
			return false;
		}
		searchInProgress = true;
		var pars = '';
		var myAjax = new Ajax.Request(
			liveSearchURI + theTerm,
			{
				method    : 'get',
				parameters: pars,
				onComplete: function(request) {liveSearchProcessReqChange(request);}
			}
		);
		liveSearchLast = theTerm;
	}
}

function liveSearchProcessReqChange(req)
{
	var res = $("LSResult");
	res.style.display = "block";
	res.firstChild.innerHTML = req.responseText;
	searchInProgress = false;
	Behaviour.apply();
}

function liveSearchSubmit()
{
	var highlight = $("LSHighlight");
	if (highlight && highlight.firstChild) {
		window.location = highlight.firstChild.getAttribute("href");
		return false;
	}
	else {
		return true;
	}
}

function closeResults()
{
	new Effect.Fade($("LSResult"));
}
