var previousTerm = '';

$(function() {
	var search_box = $("#search");
	
	if(search_box.size() == 1) {
		// Amended so input value doesn't trigger ajax call
		if($("#search2").val() != '' && $("#search2").val() !== "Search by Date, Event, Venue or Town") {
			ajaxGetMatchingEvents($("#search2").val(), 0);
		}
		
		$("#search2", search_box).mousedown(function() {
			$(this).addClass('focus');
			document.search.keyword2.focus();
		}).focus(function() {
			$(this).addClass('focus');
			search_results_box().fadeIn("fast");
		}).blur(function() {
			unsetSearchSelected();
			search_results_box().fadeOut("fast");
			if(this.value == "") {
				$(this).removeClass('focus');
			}
		}).keydown(function(event) {
			return newKeyHasBeenPressed(event);
		}).keyup(function() {
			if($.trim(previousTerm) != $.trim(this.value)) { 
				ajaxGetMatchingEvents(this.value, 0);
			}
		});
		
		$("#des_genre", search_box).change(function() {
			window.open(this.options[this.selectedIndex].value,'_top');
		});
	}
});

var lastGetMatchingEventsRequest = 0;

function search_results_box() {
	if($("#search_results_box").size() == 0) {
		$("form#search").parent().prepend('<div id="search_results_box"><div><p>Search by Date, Event, Venue or Town</p></div></div>');
	}
	
	return $("#search_results_box");
}

function delayedRequest(term, attempt)
{
	//check if it's either a new request or the last request made.
	//if a new request has been made, disregard it
	if(attempt == 0 || attempt == lastGetMatchingEventsRequest)
	{
		//update last request time
		//var d = new Date();
		//lastGetMatchingEventsRequest = d.getTime();

		//update previousTerm
		previousTerm = term;

		if ( http.readyState == 0 || http.readyState == 4 ){
			http.open("GET", "/additional_files/search_query.php?query=" + term + "&attempt=" + attempt, true);
			http.onreadystatechange = handleResponseAjaxGetMatchingEvents;
			http.send(null);
		} else {
			setTimeout('delayedRequest("' + term + '", "' + attempt + '");', 500);
		}
	}
}

function ajaxGetMatchingEvents(term, attempt)
{
	if(term.length > 0)
	{
		//update last request time
		var d = new Date();
		lastGetMatchingEventsRequest = d.getTime();
		setTimeout('delayedRequest("' + term + '", "' + lastGetMatchingEventsRequest + '");', 500);
	}
	else
	{
		search_results_box().html("Search by event, artist, or venue");
	}
}

function handleResponseAjaxGetMatchingEvents()
{
	if (http.readyState == 4)
	{
		var response = http.responseXML;
		xmlRoot =  response.documentElement;
		var eventIdNodes = response.getElementsByTagName("event_id");
		var eventNameNodes = response.getElementsByTagName("event_name");
		var venueNameNodes = response.getElementsByTagName("venue_name");
		var venueTownNodes = response.getElementsByTagName("venue_town");
		var startDateNodes = response.getElementsByTagName("start_date");
		var searchTermNodes = response.getElementsByTagName("search_term");
		
		if (eventIdNodes.length < 25) { // if 25 then create a 26th line to say more results ....
			sEventIds = new Array(eventIdNodes.length);
		} else {
			sEventIds = new Array(26);
		}
		
		//result will be the HTML returned
		var result = "";

		if(eventIdNodes.length == 0)
		{
			result = "No matching events!";
		}
		else
		{
			for(var i=0; i < eventIdNodes.length; i++)
			{
				var eventName = eventNameNodes.item(i).firstChild.nodeValue;
				eventName = eventName.replace(/andquot;/g, "'");
				var venueName = venueNameNodes.item(i).firstChild.nodeValue;
				var eventId = eventIdNodes.item(i).firstChild.nodeValue;
				var eventDate = startDateNodes.item(i).firstChild.nodeValue;
				// event_town can be empty and therefore .firstChild will be null
				var eventTown = venueTownNodes.item(i).firstChild ? venueTownNodes.item(i).firstChild.nodeValue : '';

				sEventIds[i] = eventId;
				
				if(eventTown != "") {
					eventTown = ", "+eventTown;
				}

				result += "<div><p id='search_item_" + eventId + "' onmousedown=\"location.href='/buy_tickets/events/?id=" + eventId + "';\" onmouseout=\"unsetSearchSelected();\" onmouseover=\"unsetSearchSelected(); setSearchSelected(" + i + ");\" href='#' class='menu_item_1'>" + eventDate +" - <strong>" + eventName + "</strong> at " + venueName + eventTown + "</p></div>";
			}
			
			if (eventIdNodes.length == 25) { // Create more.. line
				var searchTerm = searchTermNodes.item(0).firstChild.nodeValue;
				sEventIds[eventIdNodes.length] = "99999999";
				result += "<div><p id='search_item_99999999' onmousedown=\"location.href='/buy_tickets/?keyword2=" + encodeURIComponent(searchTerm) + "&genre_2=';\" onmouseout=\"unsetSearchSelected();\" onmouseover=\"unsetSearchSelected(); setSearchSelected(25);\" href='#' class='menu_item_1'><br />More results for \"<strong>" + searchTerm + "\"</strong> >>> </p></div>";
			}
		}

		search_results_box().html(result);
	}
}

function newKeyHasBeenPressed(e)
{
	var keynum;
	if(window.event) // IE
	{
		keynum = e.keyCode;
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}
	if(keynum == '13' && searchSelected != null) //enter
	{
		location.href = "/buy_tickets/events/?id=" + sEventIds[searchSelected];
		return false;
	}
	if(keynum == '40' || keynum == '38') //down //up
	{
		var i = 0;
		if(searchSelected != null)
		{
			i = searchSelected + 1;
		}
		if(keynum == '38')
		{
			i--;
			i--;
		}
		while(sEventIds[i])
		{
			unsetSearchSelected();
			setSearchSelected(i);
			break;
		}
		return false;
	}
	else
	{
		return true;
	}
}

