/**
 * @author mcamden
 */

var clearTimeoutID = 0;
$j(document).ready(function () {
	if((typeof($j("#resortLocationSearch").attr("id"))) != "undefined") {
		
		$j("#resortLocationSearch").bind("keyup", function (event) {
			// Detect the key pressed, and convert it to a character. This way we aren't doing searches
			// for like, !@#$ or something stupid
			var charFromEvent = String.fromCharCode(event.keyCode);

			// Matches, characters, numbers, delete key, and backspace
			if($j(this).attr("value").length > 3 && (charFromEvent.match(/[a-zA-Z0-9]/) != null || event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 222)) {
				
				if(typeof($j("#searchSuggestions").attr("id")) != "undefined")
					$j("#searchSuggestions").empty();
				
				var	resultsBox = "<span style='font-style: italic;font-weight:bold;margin-top:5px'>Suggestions:</span>";
					resultsBox += "<ul style='list-style:none'>";

				var searchTerm = $j(this).attr("value");
				$j.getJSON("/includes/ResortSearch.php?searchTerm="+searchTerm, function (data) {
					if (data.length > 0) {
						
						$j.each(data, function(i, node){
							resultsBox += "<ol style='font-size: 9px'><a href='#' id='resort_" + i + "'>"+node.ResortName+"</a></ol>\n";
						});
						resultsBox += "</ul>";

						$j("#searchSuggestions").html(resultsBox);
						
						if(clearTimeoutID > 0)
							clearTimeout(clearTimeoutID);
						
						clearTimeoutID = setTimeout("clearSuggestions();", 20000);
						
						// Bind the onClick event to the new link, so we can pass it's value to the search box
						$j.each(data, function(i, node){
							$j("#resort_" + i).bind("click", function () {
								// Fill search
								$j("#resortLocationSearch").attr("value", node.ResortName);
								clearTimeout(clearTimeoutID);
								clearSuggestions();
								
								// Execute search
								$j("#resort_search").submit();
							});
							$j("#resort_" + i).bind("mouseover", function () {
								$j(this).css("background-color", "#FFFFFF");
							}).bind("mouseout", function () {
								$j(this).css("background-color", "#FFFF99");
							});
							
						});
					}
				});
			}
		});
	}
});
// Clear search suggestions
function clearSuggestions() {
	$j("#searchSuggestions").empty();
}
