/******************************************************************************
* Name     : $Id: ffsuggest.js 26607 2011-02-21 10:24:51Z ottflori $
* Funktion : Vorschlagsskript
* Erstellt : 18/06/07, Jenisch
******************************************************************************/
function FFSuggest() {

	var pRequest;
	var pLayer;
	var pDebug					= false;
	var pInstanceName			= "";
	var pSearchURL				= "";
	var pQueryParamName			= "";
	var pFormname 				= "";
	var pLayerName				= "";
	var pQueryInput;
	var pSuggest				= new Array();
	var pLastQuery;
	var pCurrentSelection		= 0;
	var pCellSpacing			= 0;
	var pHighlightBgColor 		= "#173553";
	var pHighlightTextColor 	= "#FFFFFF";
	var pStandardBgColor 		= "#FCFCFC";
	var pStandardTextColor 		= "#173553";
	var pSuggestQueryStyle 		= "font-weight: bold; padding: 2px 15px 2px 10px;";
	var pSuggestTypeStyle 		= "padding: 2px 5px 2px 15px;";
	var submitted				= false;
	var pSprache                = "de";
	var pTimer					= false;
	var	pSearchDelay			= 400; // timer for request-delay between keypresses in milliseconds

	var arrTexte                = new Array();
	arrTexte["vorschlag"]       = new Array();
	arrTexte["vorschlag"]["de"] = "Vorschläge zu Ihrer Suche";
	arrTexte["vorschlag"]["nl"] = "Voorstellen naar aanleiding van uw zoekopdracht";
	arrTexte["vorschlag"]["fr"] = "Propositions pour votre recherche";
    arrTexte["vorschlag"]["it"] = "Consigli relativi alla tua ricerca";

	this.init = function(searchURL, formname, queryParamName, divLayername, instanceName, debugMode, strSprache) {
		pSearchURL		= searchURL;
		pFormname		= formname;
		pQueryParamName	= queryParamName;
		pLayerName		= divLayername;
		pInstanceName	= instanceName;
 		// pDebug			= debugMode;
		pDebug			= false;
		pSprache        = strSprache;

		if (pSearchURL == "") {
			if (pDebug) alert("no searchurl defined");
			return null;
		} else if (pInstanceName == "") {
			if (pDebug) alert("no instancename defined");
			return null;
		} else if (pFormname == "") {
			if (pDebug) alert("no formname defined");
			return null;
		} else if (pQueryParamName == "") {
			if (pDebug) alert("no queryparamname defined");
			return null;
		} else if (pLayerName == "") {
			if (pDebug) alert("need a layer for output");
		}
		if (pSearchDelay < 0) {
			// set default delay to 600ms
			pSearchDelay = 600;
		}
		pSearchTriggered 	= false;
		pQueryInput = document[pFormname][pQueryParamName];
		pQueryInput.onkeyup	= handleKeyPress;
		pQueryInput.onfocus	= showLayer;
		pQueryInput.onblur	= hideLayer;
		document[pFormname].onsubmit = handleSubmit;
	}

	this.setHighlightColors = function(highlighBackgroundColor, highlighTextColor) {
		pHighlightBgColor	= highlighBackgroundColor;
		pHighlightTextColor	= highlighTextColor;
	}

	this.setStandardColors = function(standardBackgroundColor, standardTextColor) {
		pStandardBgColor	= standardBackgroundColor;
		pStandardTextColor	= standardTextColor;
	}

	this.setCellspacing = function(cellspacing) {
		pCellSpacing = cellspacing;
	}

	function handleSubmit() {
		submitted = true;
		if (pSuggest[pCurrentSelection] != undefined) {
			if (pSuggest[pCurrentSelection].split('###')[1] == "Kategorie") {
				document[pFormname]["filterkategorie"].value = "__" + pSuggest[pCurrentSelection].split('###')[0] + "__";
				document[pFormname][pQueryParamName].value = "";
			}
			else {
				document[pFormname][pQueryParamName].value = pSuggest[pCurrentSelection].split('###')[0];
			}
		}
		// only submit when a search string is given
		if (pQueryInput.value == '') {
			submitted = false;
			return false;
		}
	}

	this.handleClick = function() {
		if (pSuggest[pCurrentSelection] != undefined) {
			if (pSuggest[pCurrentSelection].split('###')[1] == "Kategorie") {
				document[pFormname]["filterkategorie"].value = "__" + pSuggest[pCurrentSelection].split('###')[0] + "__";
				document[pFormname][pQueryParamName].value = "";
				document[pFormname].submit();
			}
			else {
				document[pFormname][pQueryParamName].value = pSuggest[pCurrentSelection].split('###')[0];
				document[pFormname].submit();
			}
		}
	}

	this.handleMouseOver = function(pos) {
		var tblCell = getTableCell(pos);
		unmarkAll();
		if (tblCell != null) {
			highlightSuggest(tblCell);
			pCurrentSelection = pos;
		}
	}

	this.handleMouseOut = function(pos) {
		var tblCell = getTableCell(pos);
		if (tblCell != null) {
			unmarkSuggest(tblCell);
			pCurrentSelection = -1
		}
	}

	function handleKeyPress(evt) {
		evt = (evt) ? evt : ((event) ? event : null);
		var keyCode = evt.keyCode;
		if (keyCode == 38) {
			moveSelection("up")
		} else if (keyCode == 40) {
			moveSelection("down");
		} else {
			if (pTimer) {
				clearTimeout(pTimer);
				pSearchTriggered = false;
			}
			if (pQueryInput.value == "") {
				hideLayer();
				if (pLayer != null) pLayer.innerHTML = "";
				return null;
			}
			// start delay timer
			if (!pSearchTriggered && pLastQuery != pQueryInput.value){
				pSearchTriggered = true;
				pTimer = setTimeout(startAjax, pSearchDelay);
			}
			pLastQuery = pQueryInput.value;
		}
	}

	function moveSelection(direction) {
		var pos = pCurrentSelection;
		if (direction == "up")	pos--;
		else 					pos += 1;

		if (pos < 0) {
			unmarkAll();
			pQueryInput.focus();
			pCurrentSelection	= -1;
		} else {
			var tblCell = getTableCell(pos);
			if (tblCell != null) {
				unmarkAll();
				highlightSuggest(tblCell);
				pCurrentSelection = pos;
			}
		}

		var query = pQueryInput.value;
		pQueryInput.value = "";
		pQueryInput.focus();
		pQueryInput.value = query;
	}

	function startAjax() {
		var query = pQueryInput.value;
		var requestURL = pSearchURL + "&" + pQueryParamName + "=" + escape(query);

		try {
			if( window.XMLHttpRequest ) {
				pRequest = new XMLHttpRequest();
			} else if( window.ActiveXObject ) {
				pRequest = new ActiveXObject( "Microsoft.XMLHTTP" );
			} else {
				if (pDebug) alert( "" );
			}

			pLayer = document.getElementById(pLayerName);
			if (pLayer != null) {
				if (query != "") {

					pRequest.open( "GET", requestURL, true );
					pRequest.onreadystatechange = callbackAjax;
					pRequest.send( null );
				} else {
					hideLayer();
				}
			} else {
				if (pDebug) alert( "no layer for output found" );
			}
		} catch( ex ) {
			hideLayer();
			if (ex == undefined) {
				if (pDebug) alert( "Error: " + ex.getmessage );
			} else {
				if (pDebug) alert( "Error: " + ex );
			}
		}
		pSearchTriggered = false;
	}

	function hideLayer() {
		if (pLayer != null) {
			pLayer.style.visibility = "hidden";
		}
	}

	this.hideLayerOutsideCall = function() {
		if (pLayer != null) {
			pLayer.style.visibility = "hidden";
		}
	}

	function showLayer() {
		if (pLayer != null && pSuggest != null && pSuggest.length >= 1) {
			pLayer.style.visibility	= "visible";
		}
	}

	function callbackAjax() {
		if (submitted == false) {
			if (pRequest.readyState == 4) {
				if (pRequest.status != 200) {
					hideLayer();
					if (pDebug) alert( "Error (" + pRequest.status + "): " + pRequest.statusText );
				} else {
					handleResponse(pRequest.responseText);
				}
			}
		}
  }

	function handleResponse(text) {
		pCurrentSelection = -1;
		pSuggest = new Array();
		pSuggest = text.split("\n");
		var outputText = '<table cellpadding="' + pCellSpacing + '" cellspacing="0" class="' + pLayerName + '" border="0" onMouseDown="' + pInstanceName + '.handleClick();">';
		outputText += '<tr class="suggestHeader" ><th class="suggestHeader" nowrap="nowrap" colspan="3">' + arrTexte["vorschlag"][pSprache] + ' ...</th></tr>';

		var pNewSuggest = new Array();
		for (var i in pSuggest) {
			var firstChar = pSuggest[i].charCodeAt(0);
			if (firstChar != 13 && firstChar != 10 && pSuggest[i].length >= 1) {
				pNewSuggest.push(pSuggest[i]);
			}
		}
		pSuggest = pNewSuggest;
		var query = pQueryInput.value;
		for (var i in pSuggest) {
			pSuggestParts = new Array();
			pSuggestParts = pSuggest[i].split("###");

			outputText += '<tr  id="' + pLayerName + '_' + i + '" style="background-color: ' + pStandardBgColor + '; padding: 2px 0px;" onMouseOver="' + pInstanceName + '.handleMouseOver(' + i + ');" onMouseOut="' + pInstanceName + '.handleMouseOut(' + i + ');">'
								+ '<td nowrap="nowrap" style="'+ pSuggestQueryStyle +';"><div class="suggestRes">' + pSuggestParts[0].replace(new RegExp("("+query+")","ig"),'<span class="suggestContent">$1</span>') + '</div></td>'
								+'<td nowrap="nowrap" style="'+ pSuggestTypeStyle +'" width="30%">' + pSuggestParts[2] + '</td>'
								+'<td nowrap="nowrap" nowrap align="right" style="'+ pSuggestTypeStyle +'" width="30%"><div style="white-space:  nowrap;">' + pSuggestParts[1] + '</div></td>'
						+'</tr>';
		}
		//outputText += '<tr><td  style="height:25px; background-color: ' + pStandardBgColor + '; color: ' + pStandardTextColor + '; border-top:solid 1px #5C637D; font-size:9px;" colspan="3" align="right"></td></tr></table>';

		if (pSuggest.length >= 1) {
			showLayer();
			pLayer.innerHTML		= outputText;
		} else {
			hideLayer();
			pLayer.innerHTML		= "";
		}
	}

	function highlightSuggest(tblCell) {
		tblCell.style.backgroundColor	= pHighlightBgColor;
		tblCell.style.color				= pHighlightTextColor;
	}

	function unmarkSuggest(tblCell) {
		tblCell.style.backgroundColor	= pStandardBgColor;
		tblCell.style.color				= pStandardTextColor;
	}

	function unmarkAll() {
		var tblCell;
		for (var i in pSuggest) {
			tblCell = getTableCell(i);
			if (tblCell != null) {
				unmarkSuggest(tblCell);
			}
		}
	}

	function getTableCell(pos) {
		var tblCell;
		tblCell = document.getElementById(pLayerName + "_" + pos);
		return tblCell;
	}
}

