$(document).ready(function() {
	
	// Keeps track of what livesearch iteration we're on, 
	// so we don't display outdated information
	var sid = 0;
	
	// The current highlighted index number
	var currentIndex = 0;
	
	// Keeps track of the last thing we searched for
	var q = "";	
	
	// Holder for the livesearch html request
	var request;
	
	// Is the mouse over the livesearch window?
	var mouseOver = false;
	
	// Are we currently showing livesearch results?
	var showResults = false;
	
	// Catch special character keypresses and cancel their results
	$("#livesearch #txt1").keydown(function(event) {
		// Up arrow
		if(event.which == 38) {	moveUp(); return false; }
		
		// Down arrow
		else if(event.which == 40) { moveDown(); return false; }
		
		// Return key
		else if(event.which == 13)
			followLink();
	});
	
	// After the user changes search text	
	$("#livesearch #txt1").keyup(function(event) {
		if($("#livesearch #txt1").val() == "")
			hideResults();
		else if(q != $("#livesearch #txt1").val())
		{
			showResults = true;
			getPage();
		}
		
		q = $("#livesearch #txt1").val();
	});
	
	// After user focuses into livesearch
	$("#livesearch #txt1").focus(function(event) {
		if($("#livesearch #txt1").val().length > 0)
		{
			showResults = true;
			
			if(q == "")
			{
				getPage();
				q = $("#livesearch #txt1").val();
			}
			else
			{
				$("#search-results").show();
				$("#reset-search").show();
			}
		}
		
		//If IE 7-
		if($.browser.msie && $.browser.version < 8)
			if(!$("#livesearch #txt1").hasClass("on"))
				$("#livesearch #txt1").addClass("on");
	});
		
	// Clear results
	$("#reset-search").click(function() { hideResults(); });	
	
	// Set mouseover for clear search button
	$("#reset-search").hover(
		function() {
			mouseOver = true;
			$(this).css('cursor','pointer');
		}, function() {
			mouseOver = false;
	});
	
	// After user unfocuses from livesearch
	$("#livesearch #txt1").blur(function(event) {
		// hide the input text decorators
		$("#reset-search").hide();
		$("#searching").hide();
		
		if(!mouseOver)
		{
			showResults = false;
			
			$("#search-results").hide();
		}
		
		//If IE 7-
		if($.browser.msie && $.browser.version < 8)
			if($("#livesearch #txt1").hasClass("on"))
				$("#livesearch #txt1").removeClass("on");
	});
			
	// Retrieve livesearch page
	function getPage()
	{
		var str = $("#livesearch #txt1").val();
		
		$("#reset-search").hide();
		$("#searching").show();
			
		var url = 'http://' + document.domain + '/livesearch/?q=' + str + "&sid=" + ++sid;
		
		// Kill last request and get a new livesearch document
		if(request != null)
			request.abort();
		request = $.get(url, {language: "php", version: 5}, function(responseText) { stateChanged(responseText); }, "html");  
	}
	
	// When a livesearch page is received
	function stateChanged(responseText) 
	{ 	
		// Try to get the page id
		try { var pageSid = /sid: (\d+)/i.exec(responseText)[1]; } catch(e) { return; }
		
		// If this is the latest search results
		if(sid == pageSid)
		{ 	
			$("#searching").hide();
			mouseOver = false;
			
			// If we're going to show the livesearch
			if(showResults)
			{	
				$("#reset-search").show();
								
				// if there are no search results being displayed
				if($("#search-results").is(":hidden"))
				{
					currentIndex = 0;
					
					document.getElementById("search-results").innerHTML = responseText;
					
					$("#search-results").css("height", "");
					$("#search-results").slideDown("normal");
									
					// Set a minimum size for the search results
					var newHeight = $("#results-box").height();
					if(newHeight < 25)
						$("#search-results").animate({ height: 25 }, { queue: false, duration: "normal" });
											
					setListeners();
				}
				
				//If the search window is resizing
				else
				{	
					// Set the old height of the window
					var oldHeight = $("#search-results").height();
					$("#search-results").css("height", oldHeight);
									
					// Get the new height of the livesearch results
					document.getElementById("shrinking-holder").innerHTML = responseText;
					var newHeight = $("#shrinking-holder").height();
					if(newHeight < 25)
						newHeight = 25;
					
					// If the window is growing, replace results immediately
					if(newHeight >= $("#search-results").height())
					{
						document.getElementById("search-results").innerHTML = responseText;
						$("#search-results").animate({ height: newHeight }, "normal");
						setListeners();
						
						maintainCurrentIndex();
					}
					
					// If the window is shrinking, replace results after size change
					else
						$("#search-results").animate({ height: newHeight }, "normal", "linear",	function() { document.getElementById("search-results").innerHTML = responseText; setListeners(); maintainCurrentIndex(); });
				}
			}
			
			// If the input has been blurred in the interim
			else
			{
				$("#reset-search").hide();
				$("#search-results").css("height", "");
				document.getElementById("search-results").innerHTML = responseText;
			}
		}
	}
	
	// Slide the results up
	function hideResults()
	{
		showResults = false;
		
		$("#livesearch #txt1").val("");
		q = "";
		
		$("#search-results").slideUp("normal");
		
		$("#searching").hide();
		$("#reset-search").hide();
	}
	
	// Set the mouseover listener for search items
	function setListeners()
	{		
		// If a user mouses over a link, set it to the return action and highlight it
		$(".search-link")
		 	.mouseover(function() { 
	 			mouseOver = true;
	 			
	 			// Remove previous highlighted item
 				highlight();
	 			
	 			// Get item id
				var splitString = $(this).attr("id").split('-');
				
				// Highlight item
				if(splitString[0] == "result" && parseInt(splitString[1]) > 0)
				{
					currentIndex = parseInt(splitString[1]);
					highlight();
				}
		 	})
		 	
		    .mouseout(function() {
	    		mouseOver = false;
	    		
	    		// Remove highlighting
	    		highlight();
	    		currentIndex = 0;
		    });
	}
		
	// When the user presses the up arrow key
	function moveUp()
	{	       		
		if(!$("#search-results").is(":hidden"))
		{
			if(currentIndex > 0)
			{	
				// Remove highlighting
				highlight();
				
				currentIndex--;
				
				// Add highlighting
				highlight();
			}
		}
	}
	
	// When the user presses the down arrow key
	function moveDown()
	{
		if(!$("#search-results").is(":hidden"))
		{	
			if($("#result-" + (currentIndex + 1)).length)
			{
				// Remove highlighting
				highlight();
				
				currentIndex++;
				
				// Add highlighting
				highlight();
			}				
		}
	}
	
	// Toggle the hover class
	function highlight()
	{
		// Toggle highlighting on either the search item or view all results
		if($("#result-" + currentIndex).length)
			if($("#result-" + currentIndex + " .link-box").length)
				$("#result-" + currentIndex + " .link-box").toggleClass("hover");
			else
				$("#result-" + currentIndex + " .text-right").toggleClass("hover");
	}
	
	// Try to maintain current index on data change
	function maintainCurrentIndex()
	{
		if($("#result-" + currentIndex).length)
			highlight();
		else
			currentIndex = 0;
	}
	
	// When the user presses the enter key
	function followLink()
	{
		if($("#result-" + currentIndex).length)
			window.location = $("#result-" + currentIndex).attr('href');
	}
	
	// Check on page load if input text element has focus and remove it
	// (bug with input state change)
	function IE7CheckFocus()
	{
		if($.browser.msie && $.browser.version < 8)
			$("#livesearch #txt1").blur();
	}
	
	// Call the IE7 function to blur input if necessary
	IE7CheckFocus();
});