/* jQuery & json parsing is required!  */
var actorNames = new Array();
var tags = new Array();
var highlightedEntry = -1;
var lastHighlightedEntry = -1;
var prefix = '';

/* It's business time!
 * svalue: the search string
 * searchTerms: Array: [ID] => "Text Label"
 * Return: Array: [ID] => "Text Label" (Matched, of course)
 */
function findMatches(svalue, searchTerms) {
	
	if(isSearchTime(svalue)) {
		var results = new Array();
		var niceName = '';
		var count = 0;
		var limit = 10;

		for ( var i in searchTerms )
		{
			// Be case INsensitive
			niceName = searchTerms[i].toLowerCase();
			if(niceName.match(svalue.toLowerCase()) && count < limit) {
				results[i] = searchTerms[i];
				count++;
			}
		} 
	}
	
	return results;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function count(myArray) {
	var count = 0;
	for(var i in myArray) {
		count++;
	}
	return count;
}

function saveSearch(searchText, label) {
		//$.get("/inc/saveSearch.php", {search_term: searchText, method: label}); 
		//alert(searchText + " - " + label);
}
	
function getLinks(group, label) {
	var myLinks = '';
	var a_info = new Array();
	switch(label) {
		case 'pornstar':
			for ( var i in group ) {
				var model_code = i;
				//alert(model_code);
				var model_name = group[i];
				//alert(model_name);
				myLinks += "<li><a class='results_link' href='/pornstars/" + model_code + "/'><div class='label'>" + model_name.toUpperCase() + "</div><div class='type' style='float: right;'>" + label.small() + "</div></a><p style='clear: both'/></li>";	
			}
			break;
		case 'tag':
			for ( var i in group ) {
				var tag_code = i;
				//alert(tag_code);
				var tag_name = group[i];
				//alert(tag_name);
				myLinks += "<li><a class='results_link' href='/tags/" + tag_code + "/'><div class='label'>" + tag_name.toUpperCase() + "</div><div class='type' style='float: right;'>" + label.small() + "</div></a><p style='clear: both'/></li>";
			}
			break;
		default:
			break;
	}
	return myLinks;
}

// What time is it?
function isSearchTime(value) {
	
	if(value.length > 1) { return true; }
	else { return false; }
}



$(document).ready(function() { 

	var arrowScrolling = false;
	var focused_box = 'headerSearch';

	// Start hidden so we can make a dramatic entrance!
	$(".results").hide();
	//$(".highlight").click(function() { alert("Gotcha!");});
	//$(".highlight").click(function () { alert("No body does it better."); });
	/* Fix this later, being weird with the @name= call
	$("input[@name='searchbutton']").click(function() { 
		var term = trim($("input[@name='term']").val());
		if( term != '') {
			saveSearch(term, 'search button - clicked'); 
		}
	});
	*/

	// Load all of the data
	if(top.location.host == 'localhost') {
		$.get("ajax/load_autocomplete.php", {list: 'tags'}, function(data) { tags = jsonParse(data); 	});
		$.get("ajax/load_autocomplete.php", {list: 'pornstars'}, function(data) { actorNames = jsonParse(data); });
	}
	else {
		
		$.get("/ajax/load_autocomplete.php", {list: 'tags'}, function(data) { tags = jsonParse(data); });
		$.get("/ajax/load_autocomplete.php", {list: 'pornstars'}, function(data) { actorNames = jsonParse(data); });	
	}
	
	// If they leave the window, hide the results
	$("#headerSearchBox").blur(function() {
		//alert("#headerSearchBox.blur()");
		$(".small_search .results").slideUp('medium');	
		arrowScrolling = false;
		highlightedEntry = -1; 
	});	
	
	$("#headerSearchBox").focus(function() {
		//alert("#headerSearchBox.focus()");
		focused_box = "headerSearchBox";
		prefix = '.small_search ';
	});	

	
	$("#large_search").blur(function() { 
		$(".large_search .results").slideUp('medium');	
		arrowScrolling = false;
		highlightedEntry = -1; 
	});	
	
	$("#large_search").focus(function() { 
		focused_box = "large_search";
		prefix = '.large_search ';
	});	

	
	
	// Capture every keystroke so that we can match as they type
	$(window.document).keydown(function(event) {
				
		var svalue = $("#" + focused_box).val();
		var pressedKey = '';
		var pressedKeyCode = '';
		var links = '';
		var actresses, who, what, where = '';
		
		//alert(svalue);
		if (event.which == null) {   // IE
			pressedKeyCode = event.keyCode;
		}
		else { // All others
			pressedKeyCode = event.which;			
		}
		
		
		
		// Special character handling: Arrow buttons navigate & backspace deletes
		switch(pressedKeyCode) {
				// "UP"
				case 30: // up arrow
				case 38: // up arrow
					if(arrowScrolling) {
						lastHighlightedEntry = highlightedEntry--;
					}
					break;
				// DOWN
				case 31: // down arrow
				case 40: // down arrow
					if(arrowScrolling) {
						lastHighlightedEntry = highlightedEntry++;
					}
					break;
				case 8: // BACKSPACE
					
					svalue = svalue.substring(0,svalue.length-1);
					pressedKey = String.fromCharCode(pressedKeyCode);
					//alert("Backspace: " + svalue);
					break;
				case 13: // ENTER
					var link = 'http://' + top.location.host + $(prefix + ".results ul li:eq(" + highlightedEntry + ") a").attr("href");		
					var shortLink = $(prefix + ".results ul li:eq(" + highlightedEntry + ") a").attr("href");	
					var searchText = $(prefix + ".results ul li:eq(" + highlightedEntry + ") a .label").text();	

					if(highlightedEntry >= 0) {
						event.preventDefault();
						saveSearch(searchText, 'members - autocompleted');
						top.location = shortLink;
					}
					else if(svalue != undefined && trim(svalue) != ''){
						saveSearch(trim(svalue), 'members - typein');
					}
					break;
				default:
				if (pressedKeyCode > 40 && pressedKeyCode < 110) {
					pressedKey = String.fromCharCode(pressedKeyCode);
					svalue += pressedKey;
					//alert(svalue);
				}
		}
		
		if(highlightedEntry < 0) {

			highlightedEntry = -1;
		}
		
		
		if(svalue != '' && pressedKey != '') {
			
			var close = 'close';
			
			// Search actresses, who, what & where
			actresses 	= findMatches(svalue, actorNames);
			what		= findMatches(svalue, tags);
			
			// Print the results
			
			links += getLinks(actresses, 'pornstar');
			links += getLinks(what, 'tag');
			
			if(links != '') {
				//alert(focused_box + ': svalue = ' + svalue);
				// Wrap the output
				links = '<ul style="padding: 0px; margin:0px; list-style-type: none">' + links;
				//links += "<li><a id='closeResults' href='#'><div class='label'></div><div class='type' style='float: right;'>" + close.small() + "</div></a><p style='clear: both'/></li>";	
				links += '</ul>';
				
				// Show the results and allow the user to hover over the selection
				var searchString = svalue.toUpperCase();
				var newText = '';
				
				$(prefix + ".results").html(links);
				$(prefix + ".results").slideDown('medium');
				arrowScrolling = true;
				
				// If result text contains the user's search string, then highlight it!
				$(".label:contains('"+ searchString +"')").each(function (i) {
					newText = $(this).text().split(searchString).join("<span class='highlightLetters'>" +searchString+ "</span>");
					$(this).html(newText);				
				});
				$(prefix + ".results ul li").hover(function() { $(this).addClass("highlight"); }, function() { $(this).removeClass("highlight"); });
			}
			else {
				
				// There are no results, so hide the dropdown
				$(prefix + ".results").slideUp('medium');
				arrowScrolling = false;
			}
		}
		else {
			
			// Highlight the proper entry
			$(prefix + ".results ul li").eq(highlightedEntry).addClass("highlight");		  
			if(lastHighlightedEntry != highlightedEntry)
				$(prefix + ".results ul li").eq(lastHighlightedEntry).removeClass("highlight");
		}	
		
		
		
	});
	
}); 

