/*
 * JavaScript required for the search suggest tool
 */ 

var cur_str		= "";		// current string that suggestions are shown for
var cache		= Array();	// cache eash search in this
var item_over	= null;		// the currently highlighted item
var TAB			= 9;
var ENTER		= 13;
var ESC			= 27;
var KEYUP		= 38;
var KEYDN		= 40;


/*
 * Looks for arrow up/down.  Moves selected item, if possible.  Catch event before the onkeyup event is fired
 */ 
function checkKeyDown(oInput, e)
{
	var sug			= document.getElementById("suggestions");
	var	content		= ( sug ) ? sug.firstChild : null;
	var item_next	= null;

	if ( e.keyCode == KEYDN )
	{
		if ( sug && sug.style.visibility != "hidden" && content )
		{
			if ( !item_over ) item_next = content.firstChild;
			else item_next = item_over.nextSibling;

			if ( !item_next ) return false;									// no more items, exit

			var done = false;
			while ( !done )
			{
				if ( item_next.className == "item" ) done = true;			// found another item, stop loop
				else item_next = item_next.nextSibling;
				if ( !item_next ) return false;								// no more items, exit
			}
		}
	}
	else if ( e.keyCode == KEYUP )
	{
		if ( item_over )
		{
			if ( content.firstChild != item_over )	// if not on first item
			{
				var done = false;
				item_next = item_over;
				while ( !done )
				{
					item_next = item_next.previousSibling;
					if ( !item_next ) return false;								// no more items, exit
					else if ( item_next.className == "item" ) done = true;		// found another item, stop loop
				}
			}
		}
	}

	if ( item_over && item_next ) item_over.className = "item";
	if ( item_next )
	{
		item_next.className = "item over";
		item_over = item_next;
	}

	if ( e.keyCode == KEYDN || e.keyCode == KEYUP ) return false;
	else return true;
}


/*
 * If enough letters to start a suggestion, look in cache.  If not in cache, then use ajax to get suggestions.
 */ 
function checkKeyUp(oInput, e)
{
	var str = oInput.value;
	var sug = document.getElementById("suggestions");

	if ( str == cur_str ) return true;		// if string hasn't changed, don't do anything
	else cur_str = str;

	if ( !sug )
	{
		sug = document.createElement("div");
		sug.id = "suggestions";
		sug.style.visibility = "hidden";

		content = document.createElement("div");
		content.id = "suggestions_content";
		sug.appendChild(content);

		document.body.appendChild(sug);
	}

	// change class for homepage suggestions
	if ( oInput.id == "q_quick_home" ) sug.className = "homepage";
	else sug.className = "";
	
	pos = findPosition(oInput);
	if ( oInput.id == "q_quick" || oInput.id == "q_quick_home" )
	{
		// align to left of quick seach input
		if ( oInput.id == "q_quick_home" ) sug.style.left = pos.x+"px";
		else sug.style.left = (pos.x-1)+"px";	// non-home moves left 1 pixel
		sug.style.top = (pos.y+getHeight(oInput))+"px";
	}
	else
	{
		// align to right of site search input
		sug.style.left = (pos.x+getWidth(oInput)+1)-getWidth(sug)+"px";
		sug.style.top = (pos.y+getHeight(oInput))+"px";
	}


	if ( str.length > 2 )
	{
		if ( cache[str] )
		{
			findSuggestionDone(cache[str]);	// use archived result from previous search
		}
		else findSuggestions(str);							// new search
	}
	else hideSuggestions();

	return true;
}


/*
 * Looks for 'enter', 'esc' and 'tab' keypresses.  If enter and item is selected, submit that item.  If escape/tab, remove the suggestions
 */ 
function checkKeyPress(oInput, e)
{
	if ( e.keyCode == ENTER )
	{
		if ( item_over ) item_over.onenter();		// If an item is selected, "submit" it.
		else
		{
			if ( oInput.id == "input_site_search" ) verifySiteSearch();
			else verifySearch();
		}
		return false;
	}
	else if ( e.keyCode == ESC )
	{
		if ( item_over ) item_over.className = "item";
		item_over = null;
		hideSuggestions();
	}
	else if ( e.keyCode == TAB )
	{
		if ( item_over ) item_over.className = "item";
		item_over = null;
		hideSuggestions();
	}
}


/*
 * Use ajax to search for the passed string in property names, cities, states and countries
 */ 
function findSuggestions(str)
{
	if (!xmlh_lock)
	{
		xmlh_lock = true;
		xmlh_queryPost("/ajax/searchSuggest.php", "str="+encodeURI(str), findSuggestionDone);
	}
}


/*
 * The callback for funSuggestions() and may be called when match is found in cache.  Parses the
 * json results and builds the suggestions box. 
 */ 
function findSuggestionDone(response)
{
	item_over = null;
	var data = eval('(' + response + ')');

	if ( data["success"] )
	{
		var str = data['str']										// get the string searched for
		if ( !cache[str] ) cache[str] = response;					// cache the response
		var sug = document.getElementById("suggestions_content");	// get the suggestions div
		sug.innerHTML = '';

		/*
		 * City results
		 */		 
		if ( data['cities'].length )
		{
			addTitle("Cities");

			for ( i=0; i<data['cities'].length; i++ )
			{
				city	= data['cities'][i]['city'];
				state	= data['cities'][i]['state'];
				country	= data['cities'][i]['country'];

				var oDiv = document.createElement("div");
				oDiv.className = "item";
				oDiv.city = city;
				oDiv.onmouseover = function() { itemOver(this); };
				oDiv.onmouseout = function() { itemOut(this); };
				oDiv.onmouseup = function() { gotoCity(this); };
				oDiv.onenter = function() { gotoCity(this); };

				var oName = document.createElement("div");
				oName.className = "name";
				name_bolded = city.replace(new RegExp( "("+str+")", "gi" ), highlight);
				oName.innerHTML = name_bolded;

				var oAddr = document.createElement("span");
				oAddr.className = "address";
				oAddr.innerHTML = state+", "+country;

				oName.appendChild(oAddr);
				oDiv.appendChild(oName);
				sug.appendChild(oDiv);
			}
		}


		/*
		 * State results
		 */		 
		if ( data['states'].length )
		{
			addTitle("States");

			for ( i=0; i<data['states'].length; i++ )
			{
				state	= data['states'][i]['state'];
				country	= data['states'][i]['country'];

				var oDiv = document.createElement("div");
				oDiv.className = "item";
				oDiv.state = state;
				oDiv.onmouseover = function() { itemOver(this); };
				oDiv.onmouseout = function() { itemOut(this); };
				oDiv.onmouseup = function() { gotoState(this); };
				oDiv.onenter = function() { gotoState(this); };

				var oName = document.createElement("div");
				oName.className = "name";
				name_bolded = state.replace(new RegExp( "("+str+")", "gi" ), highlight);
				oName.innerHTML = name_bolded;

				var oAddr = document.createElement("span");
				oAddr.className = "address";
				oAddr.innerHTML = country;

				oName.appendChild(oAddr);
				oDiv.appendChild(oName);
				sug.appendChild(oDiv);
			}
		}


		/*
		 * Country results
		 */		 
		if ( data['countries'].length )
		{
			addTitle("Countries");

			for ( i=0; i<data['countries'].length; i++ )
			{
				country = data['countries'][i]['country'];

				var oDiv = document.createElement("div");
				oDiv.className = "item";
				oDiv.country = country;
				oDiv.onmouseover = function() { itemOver(this); };
				oDiv.onmouseout = function() { itemOut(this); };
				oDiv.onmouseup = function() { gotoCountry(this); };
				oDiv.onenter = function() { gotoCountry(this); };

				var oName = document.createElement("div");
				oName.className = "name";
				name_bolded = country.replace(new RegExp( "("+str+")", "gi" ), highlight);
				oName.innerHTML = name_bolded;

				oDiv.appendChild(oName);
				sug.appendChild(oDiv);
			}
		}


		/*
		 * Hotels & Resorts results
		 */		 
		if ( data['properties'].length ) addTitle("Hotels/Resorts");

		for ( i=0; i<data['properties'].length; i++ )
		{
			property_id = data['properties'][i]['id'];
			if ( property_id )
			{
				slug	= data['properties'][i]['url'];
				name	= data['properties'][i]['name'];
				city	= data['properties'][i]['city'];
				state	= data['properties'][i]['state'];
				country= data['properties'][i]['country'];
				address = city;
				if ( state != "" ) address += ", "+state;
				if ( country != "" && country != "United States" ) address += ", "+country;

				var oDiv = document.createElement("div");
				oDiv.className = "item";
				oDiv.property_id = property_id;
				oDiv.slug = slug;
				oDiv.onmouseover = function() { itemOver(this); };
				oDiv.onmouseout = function() { itemOut(this); };
				oDiv.onmouseup = function() { gotoProperty(this); };
				oDiv.onenter = function() { gotoProperty(this); };

				var oName = document.createElement("div");
				oName.className = "name";
				name_bolded = name.replace(new RegExp( "("+str+")", "gi" ), highlight);
				oName.innerHTML = name_bolded;

				var oAddr = document.createElement("div");
				oAddr.className = "address";
				oAddr.innerHTML = address

				oDiv.appendChild(oName);
				oDiv.appendChild(oAddr);
				sug.appendChild(oDiv);
			}
			// no property_id is the summary item
			else
			{
				num_found	= data['properties'][i]['num_found'];
				num_left	= data['properties'][i]['num_left'];

				var oDiv = document.createElement("div");
				oDiv.className = "item";
				oDiv.str = str;
				oDiv.onmouseover = function() { itemOver(this); };
				oDiv.onmouseout = function() { itemOut(this); };
				oDiv.onmouseup = function() { gotoMore(this); };
				oDiv.onenter = function() { gotoMore(this); };

				var oName = document.createElement("div");
				oName.className = "name";
				oName.innerHTML = "<b>View all "+num_found+" results</b>";

				oDiv.appendChild(oName);
				sug.appendChild(oDiv);
			}
		}


		// If there are any items, show the suggestion box.  Otherwise hide it.
		if ( data['properties'].length || data['cities'].length || data['states'].length || data['countries'].length )
		{
			addTitle("");

			// add final item to perform normal search
			var oDiv = document.createElement("div");
			oDiv.className = "item";
			oDiv.str = str;
			oDiv.onmouseover = function() { itemOver(this); };
			oDiv.onmouseout = function() { itemOut(this); };
			oDiv.onmouseup = function() { gotoSearch(this); };
			oDiv.onenter = function() { gotoSearch(this); };

			var oName = document.createElement("div");
			oName.className = "name";
			oName.innerHTML = 'Perform normal search for "'+str+'"';

			oDiv.appendChild(oName);
			sug.appendChild(oDiv);

			document.getElementById("suggestions").style.visibility = "visible";
		}
		else
		{
			hideSuggestions();
		}
	}


	/*
	 * Creates a title div to separate groups of items with
	 */		 
	function addTitle(title)
	{
		var sug = document.getElementById("suggestions_content");
		var oDiv = document.createElement("div");
		oDiv.className = "title";
		oDiv.innerHTML = title;
		sug.appendChild(oDiv);
	}


	xmlh_lock = false;
}


/*
 * Used in a regex search/replace function to make the matching text highlighted
 */		 
function highlight(matched)
{
	return "<span class='highlight'>"+matched+"</span>";
}


/*
 * Called on a suggestion item's mouseover event.  Changes style and stores item.
 */		 
function itemOver(oDiv)
{
	if ( item_over ) item_over.className = "item";
	oDiv.className = "item over";
	item_over = oDiv;
}


/*
 * Called on a suggestion item's mouseout event.  Changes style and clears stored item.
 */		 
function itemOut(oDiv)
{
	if ( item_over ) item_over.className = "item";
	item_over = null;
}


/*
 * Called whenever the suggestions should be cleared (onblur, esc, tab).  Also clears the over item.
 */		 
function hideSuggestions()
{
	var sug = document.getElementById("suggestions");
	if ( sug ) document.getElementById("suggestions").style.visibility = "hidden";

	if ( item_over ) item_over.className = "item";
	item_over = null;
}


/*
 * Called whenever a mouseclick or "enter" is pressed on an item.  Takes user to that property or search.
 */		 
function gotoProperty(oDiv)	{ document.location.href= "/property/"+oDiv.slug+"/"; }
function gotoCity(oDiv)		{ document.location.href= "/search.php?q_city="+encodeURI(oDiv.city); }
function gotoState(oDiv)	{ document.location.href= "/search.php?q_state="+encodeURI(oDiv.state); }
function gotoCountry(oDiv)	{ document.location.href= "/search.php?q_country="+encodeURI(oDiv.country); }
function gotoMore(oDiv)		{ document.location.href= "/search.php?q_more="+encodeURI(oDiv.str); }
function gotoSearch(oDiv)	{ document.location.href= "/search.php?perform_search=1&q_quick="+encodeURI(oDiv.str); }
