String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
var ftAutoDiv = null;
var ftTBody = null;
var oldResults = null;
var oldSearchValue = null;
var ftInputId = "txtAutoComplete";
var searchCriteriaBeingEntered = false;

var ftRows = null;
var ftCurrentRow = null;
var ftProcess = true;
var ftOrignialValue = ""
var ftDropBoxMaxSize = 8;
var ftClosePopUpTimer = null;

function loadFullTextSearch(){
	if($(ftInputId) != null && $(ftInputId) !== undefined) {
		Event.observe($(ftInputId), "keydown", ftKeyDown);
		Event.observe($(ftInputId), "keyup", ftChange);
		
		//$(ftInputId).observe('keypress', ftChange);
		//$(ftInputId).observe('keydown', ftKeyDown);
		isFTSearckEnalbled();
	}
}

function isFTSearckEnalbled() {
	new Ajax.Request(message['appContext'] + "/checkFTSearchEnabled.ajax", {
        method: "get",
        parameters: '',
        onSuccess: function(transport) {
			if( transport.responseText.length > 0){
				var showFTBox = transport.responseText;
				if (showFTBox == 'N') {
					$("ftSearch").style.display = "none";
				} else {
					$("ftSearch").style.display = "block";
				}
			}
        },
        onFailure: function(transport){
        },
        onException: function(transport){
        }
    });
}

function ftResize(){
	if(ftAutoDiv != null){
		var inputObj =$(ftInputId); 
		var left = findLeftPos(inputObj.parentNode)
		ftAutoDiv.style.left = left + "px";
	}
}

function removeDropdown() {
	ftClearTimer();
	if (ftAutoDiv != null) {
		ftAutoDiv.innerHTML = "";
		ftAutoDiv.parentNode.removeChild(ftAutoDiv);
		ftAutoDiv = null;
	}
	oldResults = null;
	
	ftRows = null;
	ftCurrentRow = null;
}

function ftCreateDiv(){
	var inputObj =$(ftInputId);
	var ftAutoDiv= document.createElement("div");
	ftAutoDiv.name = "ftAutoSuggestDiv";
	ftAutoDiv.id = "ftAutoSuggestDiv";
	ftAutoDiv.className="ftOptions";
	
	var top = findPos(inputObj.parentNode)+ inputObj.parentNode.offsetHeight;
	var left = findLeftPos(inputObj.parentNode);
	ftAutoDiv.style.top = top + "px";
	ftAutoDiv.style.left = left + "px";
	ftAutoDiv.style.width = "280px";
	ftAutoDiv.style.zIndex = 5000;
	
	var table = document.createElement("table");
	ftTBody = document.createElement("tbody");
	ftTBody.id = "ftTBody";
	
	ftAutoDiv.appendChild(table);
	table.appendChild(ftTBody);
	
	return ftAutoDiv
}

function removeDefaultSearchText() {
	if (searchCriteriaBeingEntered == false) {
		if ($("txtAutoComplete").value == defaultSearchValue){
			$("txtAutoComplete").value = "";
		}
		searchCriteriaBeingEntered = true;
		$("txtAutoComplete").style.color = 'black';
	}
}
function ftSetTimer(){
	if(ftClosePopUpTimer != null){
		ftClearTimer();
	}
	ftClosePopUpTimer = setTimeout ('removeDropdown();',4000);
}
function ftClearTimer(){
	if(ftClosePopUpTimer != null){
		clearTimeout (ftClosePopUpTimer);
		ftClosePopUpTimer = null;
	}
}
var thiscount = 0;
function ftKeyDown(event){
	ftSetTimer()
	if (searchCriteriaBeingEntered == false) {
		if ($("txtAutoComplete").value == "for example: jeep wrangler yellow") {
			$("txtAutoComplete").value = "";
		}
		searchCriteriaBeingEntered = true;
		$("txtAutoComplete").style.color = 'black';
	}
	var key = event.which || event.keyCode;
	// escape key pressed, remove the dropdown
	
	if (key == Event.KEY_UP){
		if(ftRows == null){
			return
		}
		
		if(ftCurrentRow == null){
			ftCurrentRow = ftRows.length -1;
		}else {
			ftClearAll();
			ftCurrentRow--;
		}

		if(ftCurrentRow < 0){
			ftCurrentRow = null;
			$(ftInputId).value = ftOrignialValue;
		}else{			
		
			var lastSpaceIndex = ftOrignialValue.lastIndexOf(' ');
			if(lastSpaceIndex > -1){
				$(ftInputId).value = ftOrignialValue.substring(0,lastSpaceIndex);
				$(ftInputId).value += " " + oldResults[ftRows[ftCurrentRow].index].value;
			}else{
				$(ftInputId).value = oldResults[ftRows[ftCurrentRow].index].value;
			}
			ftSetRow(ftCurrentRow);
		}
		ftProcess = false;
		Event.stop(event);
		return;
	}
	
	
	if (key == Event.KEY_DOWN){		
		thiscount++;
		if(ftRows == null){
			Event.stop(event);
			return
		}
		
		if(ftCurrentRow == null){
			ftCurrentRow = 0;
		}else{
			ftClearAll();
			ftCurrentRow++
		}
		
		if(ftCurrentRow >= ftRows.length){
			ftCurrentRow = null;
			$(ftInputId).value = ftOrignialValue;
		}else{
			
			var lastSpaceIndex = ftOrignialValue.lastIndexOf(' ');
			if(lastSpaceIndex > -1){
				$(ftInputId).value = ftOrignialValue.substring(0,lastSpaceIndex);
				$(ftInputId).value += " " + oldResults[ftRows[ftCurrentRow].index].value;
			}else{
				$(ftInputId).value = oldResults[ftRows[ftCurrentRow].index].value;
			} 

			ftSetRow(ftCurrentRow);
		}
		ftProcess = false;
		Event.stop(event);
		return;
	}
	
	
	if (key == Event.KEY_ESC) {
		removeDropdown();
		Event.stop(event);
		ftRows = null;
		ftCurrentRow = null;
		ftProcess = false;
		return
	}
}

function ftClearAll(){
	for(var i=0; i<ftRows.length; i++){
		ftClearRow(i);
	}
}
function ftClearRow(rowIdx){
	var row = ftRows[rowIdx];
	row.firstChild.className = "autoCompleteTableTD";
	
}

function ftSetRow(rowIdx){
	var row = ftRows[rowIdx];
	row.firstChild.className = "autoCompleteTableOverTD";
}

function ftMouseOver(e){
	var data = $A(arguments);
	var rowIdx = data[1];
	ftClearTimer();
	ftClearAll();
	ftSetRow(rowIdx);
	ftCurrentRow = rowIdx;
}

function ftMouseOut(e){
	ftSetTimer()
}

function ftChange(event){
	var searchString;
	var inputObj = $(ftInputId);
	var val = inputObj.value;
	
	if (ftProcess == false || val.length == 1) {
		ftProcess = true;
		return;
	}
	ftOrignialValue = val;
	
	// escape key pressed, remove the dropdown
	if (val.trim().length == 0) {
		removeDropdown();
		Event.stop(event);
		return
	}

	if (val.substr(val.length - 1) == ' ') {
		oldResults = null;
		return;
	}
	
	val = val.trim();
	if (oldSearchValue != null && oldSearchValue.length > val.length) {
		// Indicates the search string was edited backwards, pressed backspace button. Get new search results from DB.
		oldResults = null;
	}
	
	oldSearchValue = val;
	
	// find the last space
	var lastSpace = val.lastIndexOf(' ');
	var textOffset = val.length - lastSpace -1;
	if (lastSpace < 0) {
		searchString = val;
	}
	else {
		if (lastSpace == val.length - 1) {
			oldResults = null;
			return
		}
		searchString = val.substr(lastSpace + 1);
	}
	
	searchStringTillLastSpace = val.substring(0, lastSpace);
/****************************************	
	if (oldResults != null) {
		// Old resultset is still valid for auto complete list.
		var filteredData = [];
		var data = oldResults;
		var jsondata = data;
		var input = searchString.toUpperCase();
		var index = 0;
		
		for (var i = 0; i < oldResults.length; i++) {
			if (index < ftDropBoxMaxSize) {
				var toCompare = oldResults[i].value.substr(0, input.length);
				// indexOf function is case sensitive, and it misses some of the matches from the result.
				var iPos = toCompare.toUpperCase().indexOf(input.toUpperCase());
				if (iPos != -1) {
					filteredData[index] = oldResults[i];
					filteredData[index].index = i;
					index = index + 1;
				}
			}
		}
	
		// oldResults = filteredData;
		
		if (ftAutoDiv == null) {
			ftAutoDiv = ftCreateDiv();
			document.getElementsByTagName("body")[0].appendChild(ftAutoDiv);
		}
		else {
			// ftAutoDiv.firstChild.firstChild.innerHTML = "";
			// clear out table by removing old tbody and adding a new one
			ftAutoDiv.firstChild.removeChild(ftAutoDiv.firstChild.firstChild);
			ftAutoDiv.firstChild.appendChild(document.createElement("tbody"))
		}
		
		if (filteredData.length == 0) {
			removeDropdown();
		}

		for (var i = 0; i < filteredData.length; i++) {
			if (i < ftDropBoxMaxSize) {
				ftAutoDiv.firstChild.firstChild.appendChild(buildRow(filteredData[i], i, val, textOffset));
			}
		}
		if (ftAutoDiv == null) {
			ftTBody = null;
			ftRows = null;
			ftCurrentRow = null;
			
		}
		else {
			ftTBody = ftAutoDiv.firstChild.firstChild
			ftRows = ftTBody.childNodes;
			ftCurrentRow = null;
		}
		return;
	}
******************************************/	
	var ftsOpt = 'OR'
	if ($F("ftOptionAND") != null) {
		ftsOpt = "AND";
	}

	new Ajax.Request(message['appContext'] + "/gsaAutoComplete.ajax", {
		method: "get",
//		parameters: 'startsWith=' + searchString + '&',
		parameters: 'startsWith=' + encodeURIComponent(val) + '&' + 'ftsOpt='+ ftsOpt +'&'+'scope=' + $('searchScope').value ,
		onSuccess: function(transport){
		
			if (ftAutoDiv == null) {
				ftAutoDiv = ftCreateDiv();
				document.getElementsByTagName("body")[0].appendChild(ftAutoDiv);
			}
			else {
				// ftAutoDiv.firstChild.firstChild.innerHTML = "";
				// clear out table by removing old tbody and adding a new one
				ftAutoDiv.firstChild.removeChild(ftAutoDiv.firstChild.firstChild);
				ftAutoDiv.firstChild.appendChild(document.createElement("tbody"))
			}
			
			if (transport.responseText.length > 0) {
				var results = eval(transport.responseText)
				oldResults = results;
				if (results.length == 0) {
					removeDropdown();
					return
				}
				
				for (var i = 0; i < results.length; i++) {
					results[i].index = i;
					if (i < ftDropBoxMaxSize) {
						ftAutoDiv.firstChild.firstChild.appendChild(buildRow(results[i], i, val, textOffset));
					}
					
				}
				ftTBody = ftAutoDiv.firstChild.firstChild
				ftRows = ftTBody.childNodes;
				ftCurrentRow = null;
			}
		},
		onFailure: function(transport){
			//           redirectOnFailure(view);
		},
		onException: function(transport){
			//           redirectOnFailure(view);
		}
	});
}

/**
 * This method will check if special characters were entered into a field
 * and present our special character message. We can pass space separated
 * exclusions per field that we will remove from our regex.
 * @param {Object} data - {value, index }
 * @param {Object} exclusions - space delimited characters to ignore as special.
 */
function buildRow(data, rowIndex, prefix, textOffset){

	var DIV = document.createElement("div");
	DIV.style.cursor = "default";
	DIV.style.width = "100%";
	
	if((prefix != null)&&(prefix.length > 0)){
		var bold = document.createElement("b");
		bold.appendChild(document.createTextNode(prefix.toUpperCase()));
		DIV.appendChild(bold);
	}
	
	if(textOffset > 0){
		var txt = data.value
		if(txt.length > textOffset){
			txt = txt.substring(textOffset);
			DIV.appendChild(document.createTextNode(txt));
		}
	}
	
	Event.observe(DIV, "mouseover", ftMouseOver.bindAsEventListener(this, rowIndex));
	Event.observe(DIV, "click", ftSetText.bindAsEventListener(this, data.value));
	Event.observe(DIV, "mouseout", ftMouseOut);

	var TD = document.createElement("td");
	TD.setAttribute("class", "autoCompleteTableTD");
	TD.setAttribute("width", "380px");
	TD.appendChild(DIV);

	var TR = document.createElement("tr");
	TR.appendChild(TD);	
	TR.index = data.index;
	return TR;
}


function ftSetText(event)
{
	var inputObj = $("txtAutoComplete");
	var val = inputObj.value;
	var data = $A(arguments);
	var a = data[1];

	$("emptySearchString").style.display = "none";
	$("noSpecialChars").style.display = "none";
	
	// find the last space
	var lastSpace = val.lastIndexOf(' ');
	if (lastSpace < 0) {
		inputObj.value = a;	
	} else {
		if(lastSpace == val.length -1) {
			inputObj.value = inputObj.value + a;
		} else {
			inputObj.value = inputObj.value.substr(0, lastSpace + 1) + a;
		}
	}
	inputObj.focus();
	
	ftAutoDiv.innerHTML = "";
	ftAutoDiv.parentNode.removeChild(ftAutoDiv);
	ftAutoDiv = null;
	
	oldResults = null;
}
function ftHideErrorMessagges(){
		$("emptySearchString").style.display = "none";
		$("noSpecialChars").style.display = "none";
		$("minimumLength").style.display = "none";
		$("maximumLength").style.display = "none";
}

function submitTextSearch(submit) {
	var searchString = $("txtAutoComplete").value.trim();
	
	searchString = searchString.trim();
		
	if($("txtAutoComplete").value.trim()=='') {
		ftHideErrorMessagges();
		$("emptySearchString").style.display = "block";
		return false;
	}
	
	// Search string must be minimum 2 characters, display error message otherwise.
	if($("txtAutoComplete").value.trim().length < 2) {
		ftHideErrorMessagges();
		$("minimumLength").style.display = "block";
		return false;
	}
	
	// Search string must be minimum 2 characters, display error message otherwise.
	if($("txtAutoComplete").value.trim().length > 100) {
		ftHideErrorMessagges();
		$("maximumLength").style.display = "block";
		return false;
	}
	
	if (!checkSpecialCharsFT($("txtAutoComplete").value.trim(), null)) {
		ftHideErrorMessagges();
		$("noSpecialChars").style.display = "block";
		removeDropdown();
		return false;
	}
	
	$("emptySearchString").style.display = "none";
	$("noSpecialChars").style.display = "none";
	if ($F("ftOptionAND") != null) {
		$("textSearchType").value = "AND";
	}else{
		$("textSearchType").value = "OR";
	}
	$("txtAutoComplete").value = $("txtAutoComplete").value.trim();
	// Remove the characters "&" and "," from the search string before submitting to search engine.
	$("textSearch").value = searchString.replace(/&/g, '').replace(/,/g, '');
	$("filterBaseLabel").value = searchString;
	
	if($("searchScope").value == "w"){
		$("textSearchForm").action = fullTextWebSearch;  // set autocomplete.ftl
	}
	
	if(submit == null) {
		$("textSearchForm").submit();
	} else {
		return true;
	}
}
/**
 * This method will check if special characters were entered into a field
 * and present our special character message. We can pass space separated
 * exclusions per field that we will remove from our regex.
 * @param {Object} data - field value to test
 * @param {Object} exclusions - space delimited characters to ignore as special.
 */
function checkSpecialCharsFT(data, exclusions){
    var exclude = "";
    if (exclusions != null) {
        exclude = exclusions.split(" ");
    }
    var iChars = "!@#$%^()+=[]\\\';{}|\"<>?~_`";
    if (exclude.length > 0) {
        for (var i = 0; i < exclude.length; i++) {
            iChars = iChars.replace(exclude[i], "");
        }
    }
    for (var i = 0; i < data.length; i++) {
        if (iChars.indexOf(data.charAt(i)) != -1) {
            return false;
        }
    }
    return true;
}
