/**
 * This file contains the javascript code to autocomplete tags.
 *
 * To add support for tag autocomplete, add the following code:
 * 
 * <div id="suggestContainer">
 *   <br>
 *   <input type="text" id="tagField" maxlength="25" autocomplete="off" onKeyUp="keyCheck(event);" onBlur="setTimeout(hideSuggest, 200);">
 *   <br>
 *   <div id="tagSuggestDiv" style="display: none; cursor: pointer; cursor: hand;"></div>
 *   <br>
 * </div>
**/


var highlightedIndex = -1;
var highlight = ""
var results = ""
var tagQuery = ""

// Get the tags for the current query
function tagSuggest()
{
	tagQuery = escape($("tagField").value);
	if (tagQuery != "")
	{
		var params = "listingID=" + myListingID;
		params += "&substring=" + tagQuery;
		params += "&userID=" + client.userID;
		params += "&cfToken=" + client.cfToken;

		// Fire off AJAX request
		ajax("POST", "/cfc/tags.cfc?method=getTagsBySubstringRPC", handleTagSuggest, null, params);
	}
	else
	{
		setTimeout("hideSuggest()", 150);
		highlightedIndex = -1;
	}
}

// Loop over the query results and create a div for each tag to be shown.
function handleTagSuggest(query)
{
	results = query;
	var suggestDiv = $("tagSuggestDiv");
	suggestDiv.innerHTML = "";
	if (query["tag"].length > 0)
	{
		for(i=0; i < query["tag"].length; i++)
		{
			var item = query["tag"][i];
			var count = query["hits"][i];
			var usesString = (count == 1) ? "use&nbsp;" : "uses";
			
			var suggest = '';
			suggest += '<div class="tagSuggestLink" id="'+ i +'" ';
			suggest += 'onMouseOver="suggestOver('+ i +');" ';
			suggest += 'onMouseOut="suggestOut('+ i +');" ';
			suggest += 'onClick="setSearch('+ i +');" ';
			suggest += 'style="height: 14px;">';
			suggest +=   '<span id="leftDiv' + i + '" class="tagSuggestLeft">'+ item +'</span>';
			suggest +=   '<span class="tagSuggestRight">'+ count +' '+ usesString +'</span>';
			suggest += '</div>';
			
			suggestDiv.innerHTML += suggest;
			suggestDiv.style.display = "";
			highlightedIndex = -1;
		}
	} else {
		hideSuggest();
		highlightedIndex = -1;
	}
}

//Mouse over function
function suggestOver(id) {
	highlightedIndex = -1
	for (i = 0; i < results["tag"].length; i++){
		var div = $(i);
		div.className = "tagSuggestLink";
	}
	var div = $(id);
	div.className = "tagSuggestLinkHover";
}

//Mouse out function
function suggestOut(id) {
	var div = $(id);
	div.className = "tagSuggestLink";
}

//Click function
function setSearch(id) {
	if (id >= 0) {
		$('tagField').value = $('leftDiv' + id).innerHTML;
		setTimeout("hideSuggest()", 150);
		highlightedIndex = -1;
	} else {
		//Had to set a delay so this function wouldn't run until after the text was added to the text box
		setTimeout("hideSuggest()", 150);
		highlightedIndex = -1;
	}
}

//Hide the suggestion Div
function hideSuggest() {
	$('tagSuggestDiv').style.display = "none";
	hightlightedIndex = -1;
}

//Show the suggestion Div
function showSuggest() {
	$('tagSuggestDiv').style.display = "";
	hightlightedIndex = -1;
}

//See what key was pressed and react accordingly
function keyCheck(e) {
	if ($('tagField').value != ""){

		//Cursor Down
		if (e.keyCode == 40) {
			if (highlightedIndex >= -1 && highlightedIndex < results["tag"].length - 1){
				//alert("Down " + results["tag"].length);
				cursorDownPressed();
			}

		//Cursor Up
		} else if (e.keyCode == 38){
		//setInputFocus();
			if (highlightedIndex >= 0 && highlightedIndex <= results["tag"].length - 1){
				//alert("Up " + highlightedIndex);
				cursorUpPressed();
			}

		//Enter
		} else if (e.keyCode == 13){
			// The enter key is handled automatically in you're inside a form
			// Otherwise, you should manually handle the enter key by adding the following to the tagField:
			// onKeyDown="if(event.keyCode==13) addTag();"

		//Escape
		} else if (e.keyCode == 27){
			hideSuggest();
			$('tagField').value = tagQuery;

		//Anything else
		} else {
			tagSuggest();
		}
	//If there was a keypress, but the text field is blank, hide the suggestion Div
	} else {
		hideSuggest();
	}
}

/**
 * Called when the down key is pressed.
**/
function cursorDownPressed()
{
	showSuggest();
	highlightedIndex++;
	
	// Remove highlighting from the previous element if needed
	if(highlightedIndex > 0)
	{
		var previousHighlight = $(highlightedIndex - 1);
		previousHighlight.className = "tagSuggestLink";
	}
	
	// Highlight the current element
	highlight = $(highlightedIndex);
	highlight.className = "tagSuggestLinkHover";
	
	// Update the text field with the slected tag
	$('tagField').value = $('leftDiv' + highlightedIndex).innerHTML;
}

//If the up cursor was pressed, handle it
function cursorUpPressed() {
	showSuggest();
	highlightedIndex--;
	//Remove highlighting from the previous element if needed
	if (highlightedIndex >= -1 && highlightedIndex < results["tag"].length - 1){
		var previousHighlight = $(highlightedIndex + 1);
		previousHighlight.className = "tagSuggestLink";
	}
	//If we're at the top of the list, show the user's original query in the text field
	if (highlightedIndex == -1) {
		$('tagField').value = tagQuery;
	} else {
		//Otherwise, highlight the current item
		highlight = $(highlightedIndex);
		highlight.className = "tagSuggestLinkHover";
		$('tagField').value = $('leftDiv' + highlightedIndex).innerHTML;
		return;
	}
}

/**
 * Set focus on the text field
**/
function setInputFocus()
{
	$('tagField').focus();
}

