AutoComplete = function(input, suggestions, timeout)
{
	var timer;

	input.attachEvent("onkeyup", handleKeyUp);
	input.attachEvent("onkeydown", handleArrowKeys);

	function handleKeyUp(event)
	{
		if (event.keyCode != 40 && event.keyCode != 38 && event.keyCode != 13 && event.keyCode != 27)
		{
			if (input.value.length == 0)
				suggestions.innerHTML = "";

			if (timer)
				clearTimeout(timer);

			if (input.value.length > 0)
				timer = setTimeout(reload, timeout);
		}
		else if (event.keyCode == 13)
		{
			var cursor = getCursor();
			var parent = suggestions.firstChild;

			if (cursor != -1 && cursor < parent.childNodes.length)
			{
				if (IS_IE)
					input.value = parent.childNodes[cursor].innerText;
				else
					input.value = parent.childNodes[cursor].textContent;

				var path = parent.childNodes[cursor].getAttribute("path");
				window.location = path;
				suggestions.innerHTML = "";
			}
		}
		else if (event.keyCode == 27)
		{
			suggestions.innerHTML = "";
		}
	}


	function reload()
	{
		//suggestions.reload({ prefix : input.value });
		if( input.value.length == 0 )
			suggestions.innerHTML = "";
		else
			getHint( input.value );
	}


	function handleArrowKeys(event)
	{
		try
		{
			var cursor = getCursor();
			var parent = suggestions.firstChild;

			if (cursor != -1 && (event.keyCode == 40 || event.keyCode == 38))
			{
				if (event.keyCode == 40)
				{
					if (cursor == parent.childNodes.length)
						parent.childNodes[0].style.backgroundColor = "#a3ceff";
					else if (cursor < parent.childNodes.length - 1)
					{
						parent.childNodes[cursor].style.backgroundColor = "";
						parent.childNodes[cursor + 1].style.backgroundColor = "#a3ceff";
					}
				}
				else
				{
					if (cursor > 0)
					{
						parent.childNodes[cursor].style.backgroundColor = "";
						parent.childNodes[cursor - 1].style.backgroundColor = "#a3ceff";
					}
				}
			}
		}
		catch (e) { }
	}


	function getCursor()
	{
		if (suggestions.innerHTML.length == 0)
			return -1;

		var parent = suggestions.firstChild;

		for (var i = 0; i < parent.childNodes.length; i++)
			if (
					parent.childNodes[i].style.backgroundColor == "#a3ceff" ||
					parent.childNodes[i].style.backgroundColor == "rgb(163, 206, 255)"
			   )
				return i;

		return parent.childNodes.length;
	}
}
