//Vars
var isProcessing = false;
var previousInput = '';
$(document).ready(function()
{
	//Clear Input
	$('#input').val('');
	$('#input').focus();	
	//Different Selectors
	$('#selector li').click(function()
	{
		$('#selector li').each(function()
		{
			$(this).removeClass('active');
		});
		$(this).addClass('active');
		testTimeout(true);
	});
	//Search timer
	function testTimeout(force)
	{
		if(force == true || (getInputValue() != previousInput && isProcessing == false))
		{
			processSearch(true);
		}
	}
	setInterval(testTimeout, 750);
	//Capture keypresses
	$("#input").keypress(function(e)
	{
		if(e.keyCode == 13)
		{
			testTimeout();
		}
	});
	//Get search box value
	function getInputValue()
	{
		return $.trim($("#input").get(0).value);
	}
	//Search
	function processSearch()
	{
		var inputValue = getInputValue();
		$('#results').empty();
		if(inputValue.length > 0)
		{
			if(isProcessing == false)
			{
				$('#results').html('<p class="center"><img src="imgs/loader.gif" width="16" height="16" alt="" /></p>');
				isProcessing = true;
				previousInput = inputValue;
				$.getJSON('json.php?q=' + escape(inputValue) + '&t=' + $('#selector li.active').eq(0).text(), function(data, status)
				{
					$('#results').empty();
					if(status == "success")
					{
						if(data.length > 0)
						{
							var newText = '';
							$.each(data, function(i, item)
							{
								var firstText = i == 0 ? ' first' : '';
								var typesOfNode = ['Package', 'Class', 'Function', 'Interface', 'Variable', 'Other'];
								var regexSearchString = inputValue.replace(/([\#\_\^\$\/\.\*\+\?\|\(\)\[\]\{\}\\])/, '\\$1');
								var regexSearch = new RegExp('(' + regexSearchString + ')', 'i');
								newText += '<div class="result' + firstText + '"><span class="name"><a href="' + item.link + '" target="_blank" title="' + item.link + '">' + item.name.replace(regexSearch, '<span>$1</span>') + '</a></span><span class="icons"><img src="imgs/' + typesOfNode[item.type - 1] + '.png" width="10" height="10" title="' + typesOfNode[item.type - 1] + '" alt="" /></span><div class="clear"></div></div>';
							});
							$('#results').append(newText);
						}
						else
						{
							$('#results').html('<p class="center error">No results found</p>');
						}
					}
					else
					{
						$('#results').html('<p class="center error">Unable to contact the server</p>');
					}
					isProcessing = false;
				});
			}
		}
	}
});