/*
 * __divID            - ID of the DIV element holding the suggestions.
 * __minWordLength    - Minimum word length for performing suggestions.
 * __suggestURL       - Location of the script providing the suggestions.
 * __suggestParameter - Parameter name used to pass the input field content.
 */
var __divID = 'autocompletion';
var __minWordLength = 2;
var __suggestUrl = '/cps/autocompletion/autocompletion.jsp';
var __suggestParameter = 'word';
var __languageParameter = 'lang';
/*
 * Internal use.
 */
var __maxSelect = -1;
var __selection = -1;
var __suggestField = false;
var __suggestLanguage = 'de';
/**
 * Set the field to display the suggestions for.
 */
function setSuggestField(fieldId) {
	__suggestField = document.getElementById(fieldId);
	if (!__suggestField) {
		alert('Input field id "' + fieldId + '" not found. Continuing without suggestions.');
	}
}
/**
 * Set the language which will be passed to Verity to select suggestions.
 */
function setSuggestLanguage(language) {
	__suggestLanguage = language;
}
/**
 * Function called when loading XML is finished: Update the forms in the
 * HTML document.
 */
function alertContents(httpRequest, updateFunction) {
	if (!httpRequest) {
		/*alert('Invalid HttpRequest object.');*/
	}
	else if (httpRequest.readyState == 4) {
		if (httpRequest.status == 200) {
			try {
				updateFunction(httpRequest.responseXML);
			}
			catch (e) {
				/*alert('Caught Exception: ' + e.description);*/
			}
		}
		else {
			/*alert('There was a problem with the request: ' + httpRequest.status);*/
		}
	}
}
/**
 * Create an XMLHttpRequest object depending on the browser.
 *
 * @see http://developer.mozilla.org/en/docs/AJAX:Getting_Started
 */
function getHttpRequest() {
	var httpRequest = false;
	/*
	 * Create a XMLHttpRequest object.
	 */
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
		/*
		 * Force MIME type for some versions of Mozilla.
		 */
		if (httpRequest.overrideMimeType) {
			httpRequest.overrideMimeType('text/xml');
		}
	}
	else if (window.ActiveXObject) { // IE
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				// ignore.
			}
		}
	}
	/*
	 * Check, if a valid XMLHttpObject was created.
	 */
	if (!httpRequest) {
		alert('Giving up :o( Cannot create an XMLHTTP instance');
	}
	return httpRequest;
}
/**
 * Update the suggestion data used in the search box.
 *
 * @see http://developer.mozilla.org/en/docs/AJAX:Getting_Started
 */
function suggest(queryText) {
	var httpRequest = getHttpRequest();
	if (queryText.length < __minWordLength) {
		__hide();
	}
	else if (httpRequest) {
		httpRequest.onreadystatechange = function() { alertContents(httpRequest, updateSuggest); };
		httpRequest.open(
			'GET',
				  __suggestUrl
				+ '?' + __suggestParameter + '=' + escape(queryText)
				+ '&' + __languageParameter + '=' + escape(__suggestLanguage),
			true
		);
		httpRequest.send(null);
	}
}
/**
 * Update the suggestion list.
 *
 * @param xmlDoc XML document returned by autocompletion.jsp
 */
function updateSuggest(xmlDoc) {
	var wordlist = xmlDoc.getElementsByTagName('word');
	__maxSelect = wordlist.length;
	/*
	 * Hide the suggestionslist, if no entries are available.
	 */
	if (__maxSelect == 0) {
		__hide();
	}
	else {
		/*
		 * Create the suggestionlist entries.
		 */
		var inputLength = __suggestField.value.length;
		var text = '';
		for (var i = 0; i < wordlist.length; i++) {
			text += '<div '
				+ 'id="suggest-' + i + '" '
				+ 'onclick="__click(this.id);" '
				+ 'onmouseout="__mouseOut(this.id);" '
				+ 'onmouseover="__mouseOver(this.id);" '
				+ '>'
				+ '<b>' + wordlist[i].firstChild.nodeValue.substring(0, inputLength) + '</b>'
				+ wordlist[i].firstChild.nodeValue.substring(inputLength)
				+ '</div>';
		}
		/*
		 * Get the suggestionlist, set its position relative to the input box
		 * and add the entries.
		 */
		var suggestionlist = getSuggestionlist();
		if (suggestionlist) {
			with (suggestionlist.style) {
				//left = findPosX(__suggestField) + 'px';
				//top = (findPosY(__suggestField) + __suggestField.offsetHeight) + 'px';
				//width = __suggestField.offsetWidth + 'px';
				display = 'block';
			} 
			suggestionlist.innerHTML = text;
		}
	}
}
/**
 * Clear the currently highlighted suggestion.
 */
function __clearHighlight() {
	__mouseOut('suggest-' + __selection);
}
/**
 * Retrieve the HTML element holding the suggestionlist.
 */
function getSuggestionlist() {
	var suggestionlist = document.getElementById(__divID);
	if (!suggestionlist) {
		alert('There is no <div id="' + __divID + '"></div> !');
	}
	return suggestionlist;
}
/**
 * Hide the suggestionlist.
 */
function __hide() {
	var suggestionlist = getSuggestionlist();
	if (suggestionlist) {
		suggestionlist.style.display = 'none';
	}
}
/**
 * Hilight the currently selected suggestion.
 */
function __highlight() {
	var div = document.getElementById('suggest-' + __selection);
	__suggestField.value = div.innerHTML.replace(/<.*?>/g, '');
	__mouseOver('suggest-' + __selection);
}
/**
 * Handle keyboard presses.
 */
function __keyDown(event) {
	if (event) {
		switch (getKeyCode(event)) {
			case  9: // tab
			case 27: // escape
				__hide();
				break;
			case 13: // enter
				break;
			case 38: // up
				if (__selection > 0) {
					__clearHighlight();
					__selection--;
					__highlight();
				}
				break;
			case 40: // down
				if (__selection < __maxSelect - 1) {
					__clearHighlight();
					__selection++;
					__highlight();
				}
				break;
		}
	}
}
/**
 * Handle keyboard releases.
 */
function __keyUp(event) {
	if (event) {
		//
		// ignore alt and ctrl combinations.
		//
		if (event.altKey || event.ctrlKey) {
			return;
		}
		//
		// ignore key down triggers.
		//
		switch (getKeyCode(event)) {
			case 13: // enter
			case 27: // escape
			case 38: // up
			case 40: // down
				return;
		}

		__selection = -1;
		suggest(__suggestField.value);
	}
}
/**
 * Clear a suggestion highlight after the mouse pointer is not over it any longer.
 */
function __mouseOut(id) {
	var div = document.getElementById(id);
	if (div) {
		div.className = '';
	}
}
/**
 * Highlight a suggestion when the mouse is over it.
 */
function __mouseOver(id) {
	__clearHighlight();
	var div = document.getElementById(id);
	if (div) {
		__selection = id.substring(id.indexOf('-') + 1);
		div.className = 'highlight';
	}
}
/**
 * Handle mouse clicks on a suggestion.
 */
function __click(id) {
	var div = document.getElementById(id);
	if (div) {
		__suggestField.value = div.innerHTML.replace(/<.*?>/g, '');
		setCaretPosition(__suggestField, __suggestField.value.length);
	}
}
/**
 * Determine the X position of an object.
 */
function findPosX(obj) {
	var posX = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent && (obj.className != "pageContainer")) {
			posX += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x) {
		posX = obj.x;
	}
	return posX;
}
/**
 * Determine the Y position of an object.
 */
function findPosY(obj) {
	var posY = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent && (obj.className != "pageContainer")) {
			posY += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y) {
		posY = obj.y;
	}
	return posY;
}
/**
 * Retrieve the key code contained in the given event.
 */
function getKeyCode(event) {
	return (event.which) ? event.which : event.keyCode;
}
/**
 * Set the cursor position inside a textbox or textarea.
 *
 * @param element Element to set the cursor position in.
 * @param caretPosition cursor position (starting with 0).
 */
function setCaretPosition(element, caretPosition) {
	if (element != null) {
		if (element.createTextRange) {
			var textRange = element.createTextRange();
			textRange.move('character', caretPosition);
			textRange.select();
		}
		else if (element.selectionStart) {
			element.focus();
			element.setSelectionRange(caretPosition, caretPosition);
		}
		else {
			element.focus();
		}
	}
}
