$(document).ready(function(){
    $("input#q").keyup(function(e){
		searchString = $("input#q").val();
		if(searchString.length > 2)
		{
			url = '/search/suggest';
			data = 'q=' + escape(searchString);
			$.ajax({
				url: url,
				type: 'POST',
				data: data,
				success: function(message)
				{
					if(message != '')
					{
						// output the suggestions
						if($("ul#suggestions").length == 0)
						{
							$("body").append('<ul id="suggestions">' + message + '</ul>');
						}
						else
						{
							$("ul#suggestions").html(message);
						}
						pos = findPos(document.getElementById('q'));

						qHeight = parseInt($("input#q").css('height'));
						qWidth = parseInt($("input#q").css('width'));

						$("ul#suggestions").css('top', parseInt(pos[1]) + qHeight);
						$("ul#suggestions").css('left', pos[0]);
						$("ul#suggestions").css('display', 'block');
						$("ul#suggestions").css('width', qWidth);

						$("ul#suggestions li").click(function(){
							//$("input#q").val(this)
							$("input#q").val(strip_tags(this.innerHTML))
							$("ul#suggestions").css('display', 'none');
						});
					}
					else
					{
						$("ul#suggestions").css('display', 'none');
					}
				}
			});
		}
		else
		{
			$("ul#suggestions").css('display', 'none');
		}
	});
});

function findPos(obj)
{
	var curleft = curtop = 0;
	if(obj.offsetParent)
	{
		do
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
		while(obj = obj.offsetParent);
	}
	return [curleft, curtop];
}

function strip_tags(html)
{
	//PROCESS STRING
	if(arguments.length < 3)
	{
		html=html.replace(/<\/?(?!\!)[^>]*>/gi, '');
	}
	else
	{
		var allowed = arguments[1];
		var specified = eval("["+arguments[2]+"]");
		if(allowed)
		{
			var regex='</?(?!(' + specified.join('|') + '))\b[^>]*>';
			html=html.replace(new RegExp(regex, 'gi'), '');
		}
		else
		{
			var regex='</?(' + specified.join('|') + ')\b[^>]*>';
			html=html.replace(new RegExp(regex, 'gi'), '');
		}
	}
	return html;
}

