// 2006-09-15 10:00

var v_oldInputFieldValue = "";
var v_currentInputFieldValue = "";
var H = "";
var v_eventKeycode = "";
var v_highlightedSuggestionIndex = -1;
var v_highlightedSuggestionDiv = null;
var v_completeDivRowCount = -1;
var v_completeDivRowCount_2 = 5;
var v_completeDivList = null;
var v_divTag = "div";
var v_spanTag = "span";
var v_documentForm = null;
var v_inputField = null;
var v_dropdownDiv = null;
var v_submitButton = null;
var v_cursorUpDownPressed = false;
var v_resultCache = new Object();
var v_borderLR = 1;
var v_borderTB = 1;
var v_lastKeyCode = -1;
var v_theTime = (new Date()).getTime();
var v_hasXMLHTTP = false;
var v_xmlHttp = null;
var v_completeURI = null;
var v_frame=null;
var v_searchScript = null;
var v_timeoutAdjustment = 0;
var v_inputFieldValue = null;
var v_spanRefWidth = 60;
var v_submitted = false;

var v_logArea = null;

Suggest = function(documentForm, inputField, submitButton, searchScript, lang, logArea) {

	// Workaround fuer Mozilla Bug (Exception)
	inputField.setAttribute('autocomplete','off');
	
	v_documentForm = documentForm;
	v_inputField = inputField;
	v_submitButton = submitButton;
	v_logArea = logArea;
	
	if(!searchScript) {
		searchScript = "search";
	}
	v_searchScript = searchScript;
	
	init();
};

function init() { 

	if(getXMLHTTP()) { 
		v_hasXMLHTTP = true;
	} else {
		v_hasXMLHTTP = false;
	}

	v_completeURI = "/rotary/distrikt/" + v_searchScript;
	
	v_documentForm.onsubmit = submitHandler;
	v_inputField.autocomplete = "off";
	v_inputField.onblur = onBlurHandler;
	//v_inputField.onfocus = lc;
	
	if(v_inputField.createTextRange)
		v_inputField.onkeyup = new Function("return keyPressedHandler(event); ");
	else
		v_inputField.onkeyup = keyPressedHandler;
		
	v_inputField.onsubmit = submitHandler;
	v_currentInputFieldValue = v_inputField.value;
	v_oldInputFieldValue = v_currentInputFieldValue;
	
	v_dropdownDiv = document.createElement("DIV");
	v_dropdownDiv.id = "dropdownDiv";
	v_dropdownDiv.style.borderRight = "black " + v_borderLR + "px solid";
	v_dropdownDiv.style.borderLeft = "black " + v_borderLR + "px solid";
	v_dropdownDiv.style.borderTop = "black " + v_borderTB + "px solid";
	v_dropdownDiv.style.borderBottom = "black " + v_borderTB + "px solid";
	v_dropdownDiv.style.zIndex = "1";
	//v_dropdownDiv.style.paddingRight = "0";
	//v_dropdownDiv.style.paddingLeft = "0";
	//v_dropdownDiv.style.paddingTop = "0";
	//v_dropdownDiv.style.paddingBottom = "0";
	
	setDropdownSize();
	
	v_dropdownDiv.style.visibility = "hidden";
	v_dropdownDiv.style.position = "absolute";
	v_dropdownDiv.style.backgroundColor = "white";
	document.body.appendChild(v_dropdownDiv);
	
	cacheResults("", new Array(), new Array());
	
	setStyleForElement(v_dropdownDiv, "mAutoComplete")
	
	var div = document.createElement("DIV");
	div.style.visibility = "hidden";
	div.style.position = "absolute";
	//div.style.left = "-10000";
	//div.style.top = "-10000";
	div.style.width = "0";
	div.style.height = "0";
	
	var iframe = document.createElement("IFRAME");
	iframe.dropdownDiv = v_dropdownDiv;
	iframe.name = "completionFrame";
	iframe.id = "completionFrame";
	iframe.src = v_completeURI;
	
	div.appendChild(iframe);
	document.body.appendChild(div);
	
	if(frames && (frames["completionFrame"] && frames["completionFrame"].frameElement)) {
		v_frame = frames["completionFrame"].frameElement;
	} else {
		v_frame = document.getElementById("completionFrame");
	}
		
	window.onresize = setDropdownSize;
	document.onkeydown = keyDownHandler;

	if(document.createEventObject) {
		var eventObject = document.createEventObject();
		eventObject.ctrlKey = true;
		eventObject.keyCode = 70;
		document.fireEvent("onkeydown", eventObject);
	}
}

function keyDownHandler(event) {

	if(!event && window.event) {
		event = window.event;
	}
	if(event) {
		v_lastKeyCode = event.keyCode;
	}
		
	// 8 = Backspace		
	if(event && event.keyCode == 8) {
		if( v_inputField.createTextRange 
				&& (event.srcElement == v_inputField && (positionOfSelectionStart(v_inputField) == 0 && lengthOfSelection(v_inputField) == 0))){
					
			if(v_inputField.createTextRange) {
				var u = v_inputField.createTextRange();
				u.moveStart("character", v_inputField.value.length);
				u.select();
			} else if (v_inputField.setSelectionRange) {
				v_inputField.setSelectionRange(v_inputField.value.length, v_inputField.value.length);
			}
			
			event.cancelBubble = true;
			event.returnValue = false;
			return false;
		}
	}
}

function calcDropdownWidth() {
	if(navigator && navigator.userAgent.toLowerCase().indexOf("msie") == -1) {
		// kein IE
		return v_inputField.offsetWidth - v_borderLR * 2;
	} else {
		// IE
		return v_inputField.offsetWidth;
	}
}

function calcDropdownOffsetLeft(_inputField){
	var _offset = 0;
	while(_inputField) {
		_offset += _inputField["offsetLeft"];
		_inputField = _inputField.offsetParent;
	}
	return _offset;
}

function calcDropdownOffsetTop(_inputField){
	var _offset = 0;
	while(_inputField) {
		_offset += _inputField["offsetTop"];
		_inputField = _inputField.offsetParent;
	}
	return _offset
}

function setDropdownSize() {
	if(v_dropdownDiv) {
		v_dropdownDiv.style.left = calcDropdownOffsetLeft(v_inputField) + "px";
		v_dropdownDiv.style.top = calcDropdownOffsetTop(v_inputField) + v_inputField.offsetHeight -1 + "px";
		v_dropdownDiv.style.width = calcDropdownWidth() + "px";
	}
}

function onBlurHandler(event) {
	if(!event && window.event)
		event = window.event;
	if(!v_cursorUpDownPressed){
		hideDropdown();
		// falls <tab> gedrueckt wurde
		if(v_lastKeyCode == 9) {
			v_submitButton.focus();
			v_lastKeyCode = -1;
		}
	}
	v_cursorUpDownPressed = false
}

keyPressedHandler = function(event){
	
	v_eventKeycode = event.keyCode;
	v_inputFieldValue = v_inputField.value;
	
	// 38 cursor-up, 40 cursor-down
	if(v_eventKeycode == 40 || v_eventKeycode == 38) {
		v_cursorUpDownPressed = true;
		v_inputField.blur();
		
		setTimeout("v_inputField.focus();", 10);
		//setTimeout("setInputFieldFocus();", 10);
	}
		
	var _lengthOfSelect = lengthOfSelection(v_inputField);
	var w = positionOfSelectionStart(v_inputField);
	var _inputFieldValue = v_inputField.value;
	if(v_eventKeycode != 0) {
		if(_lengthOfSelect > 0 && w != -1)
			_inputFieldValue = _inputFieldValue.substring(0, w);
			
		// 13 enter, 3
		if (v_eventKeycode == 13 || v_eventKeycode == 3) {
			var f = v_inputField;
			if(f.createTextRange) {
				var u = f.createTextRange();
				u.moveStart("character", f.value.length);
				u.select()
			} else if (f.setSelectionRange) {
				f.setSelectionRange(f.value.length, f.value.length)
			}
		} else {
			if(v_inputField.value != _inputFieldValue)
				selectEntry(_inputFieldValue)
		}
	}
	v_currentInputFieldValue = _inputFieldValue;
	
	//log("KEY: " + v_eventKeycode);
	
	if(checkNavKeys(v_eventKeycode) && v_eventKeycode != 0)
		updateDropdown(v_dropdownDiv, valueOfCAutoComplete)
	
};

function stripCR(s) {
	for(var c=0, wa="", Ib="\n\r"; c < s.length; c++)
		if(Ib.indexOf(s.charAt(c)) == -1)
			wa += s.charAt(c);
		else
			wa += " ";
		return wa
}

function findSpanValueForClass(div, style) {
	
	var _element = div.getElementsByTagName(v_spanTag);
	if(_element) {
		for(var c=0; c<_element.length; ++c){
			if(_element[c].className == style) {
				var _value = _element[c].innerHTML;
				
				if(_value == "&nbsp;")
					return "";
				else {
					var _value2 = stripCR(_value);
					return _value2;
				}
			}
		}
	} else {
		return ""
	}
}


function valueOfCAutoComplete(value) {
	if(!value) {
		return null;
	}
	return findSpanValueForClass(value, "cAutoComplete")
}

function hideDropdown(){
	document.getElementById("dropdownDiv").style.visibility = "hidden"
}

function showDropdown(){
	document.getElementById("dropdownDiv").style.visibility = "visible";
	setDropdownSize();
}

function cacheResults(inputFieldValue, array1, array2){
	v_resultCache[inputFieldValue] = new Array(array1, array2)
}

sendSuggest = function(frame, inputFieldValue, array1, array2) {
	
	if(v_timeoutAdjustment > 0)
		v_timeoutAdjustment--;
	
	if(!frame)
		frame = v_frame;
	
	cacheResults(inputFieldValue, array1, array2);
	var _dropdownDiv = frame.dropdownDiv;

	displaySuggestList(_dropdownDiv, array1, array2);
	updateDropdown(_dropdownDiv, valueOfCAutoComplete);
	
	if(v_completeDivRowCount_2 > 0) {
		_dropdownDiv.height = 16 * v_completeDivRowCount_2 + 4;
	} else {
		hideDropdown();
	}
};

function submitHandler(){
	hideDropdown();
	v_documentForm.submit();
	return true
}

function encodeURI(uri){
	if(encodeURIComponent)
		return encodeURIComponent(uri);
	if(escape)
		return escape(uri)
}

function adjustTimeout(Ub) {
	var I = 100;
	for(var p=1; p <= (Ub-2)/2; p++) {
		I = I * 2
	}
	I = I + 50;
	return I
}

mainLoop = function(){

	if(v_oldInputFieldValue != v_currentInputFieldValue) {
	
		if(!v_submitted){
			var uri = encodeURI(v_currentInputFieldValue);		
			var cacheEntry = v_resultCache[v_currentInputFieldValue];
						
			if(cacheEntry) {
				v_theTime = -1;
				sendSuggest(
					v_frame,
					v_currentInputFieldValue,
					cacheEntry[0],
					cacheEntry[1])
			} else {
				v_timeoutAdjustment++;
				v_theTime = (new Date()).getTime();
				if(v_hasXMLHTTP) {
					getServerResponse(uri)
				} else {
					setCookie("qu", uri, null, F, null, null);
					frames["completionFrame"].document.location.reload(true)
				}
			}
			v_inputField.focus()
		}
		v_submitted = false
	}
	v_oldInputFieldValue = v_currentInputFieldValue;
	setTimeout("mainLoop()", adjustTimeout(v_timeoutAdjustment));
	return true
};

setTimeout("mainLoop()", 10);

var f_onMouseDown = function() {
	selectEntry(valueOfCAutoComplete(this));
	v_submitted = true;
	submitHandler()
};

var f_onMouseOver = function() {
	if(v_highlightedSuggestionDiv)
		setStyleForElement(v_highlightedSuggestionDiv, "aAutoComplete");
	setStyleForElement(this, "bAutoComplete")
};

var f_onMouseOut = function(){
	setStyleForElement(this, "aAutoComplete")
};

function highlightNewValue(D){ 
	v_currentInputFieldValue = H;
	selectEntry(H);

	if(!v_completeDivList || v_completeDivRowCount <= 0) {
		return;
	}
	showDropdown();
	if(D >= v_completeDivRowCount) {
		D = v_completeDivRowCount - 1
	}
	if(v_highlightedSuggestionIndex != -1 && D != v_highlightedSuggestionIndex) {
		setStyleForElement(v_highlightedSuggestionDiv, "aAutoComplete");
		v_highlightedSuggestionIndex = -1;
	}
	if(D < 0) {
		v_highlightedSuggestionIndex = -1;
		v_inputField.focus();
		return;
	}
	v_highlightedSuggestionIndex = D;
	v_highlightedSuggestionDiv = v_completeDivList.item(D);
	setStyleForElement(v_highlightedSuggestionDiv, "bAutoComplete");
	v_currentInputFieldValue = H;
	selectEntry(valueOfCAutoComplete(v_highlightedSuggestionDiv))
}

function checkNavKeys(keycode) {

	// 40 cursor down
	if(keycode == 40){
		highlightNewValue(v_highlightedSuggestionIndex + 1);
		return false
	// 38 cursor up
	} else if (keycode == 38) {
		highlightNewValue(v_highlightedSuggestionIndex - 1);
		return false
	// 13 enter
	} else if (keycode == 13 || keycode == 3) {
		return false
	}
	return true
}

function updateDropdown(_dropdownDiv, _valueOfCAutoComplete) {
	
	var _inputField = v_inputField;
	var _match = false;
	v_highlightedSuggestionIndex = -1;
	var _completeDivList = _dropdownDiv.getElementsByTagName(v_divTag);
	var _rowCount = _completeDivList.length;
	
	v_completeDivRowCount = _rowCount;
	v_completeDivList = _completeDivList;
	v_completeDivRowCount_2 = _rowCount;
	H = v_currentInputFieldValue;
	
	if(v_currentInputFieldValue == "" || _rowCount == 0) {
		hideDropdown();
	} else {
		showDropdown();
	}
	
	if (v_currentInputFieldValue.length > 0) {
	
		for (var c=0; c < _rowCount; c++) {
				var _currentInputFieldValue = v_currentInputFieldValue;
				
				// true, if Schrobenhausen-Aichach = Schr			
				if(	_valueOfCAutoComplete(_completeDivList.item(c)).toUpperCase().indexOf(_currentInputFieldValue.toUpperCase()) == 0 ) {				
					_match = true;
				}

			if(_match) {
				break
			}
		}
	}
	
	if(_match) {
		v_highlightedSuggestionIndex = c;
	}
	for(var c=0; c<_rowCount; c++) {
		setStyleForElement(_completeDivList.item(c), "aAutoComplete");
	}
	if(_match) {
		v_highlightedSuggestionDiv = _completeDivList.item(v_highlightedSuggestionIndex);
	} else {
		v_highlightedSuggestionIndex = -1;
		v_highlightedSuggestionDiv = null
	}
	
	var _deletePressend = false;
	switch(v_eventKeycode) {
		case 8:
			// backspace
		case 33:
			// page up
		case 34:
			// page down
		case 35:
			// end
		case 36:
			// home
		case 37:
			// left arrow
		case 39:
			// right arrow
		case 45:
			// insert
		case 46:
			// delete
			_deletePressend = true;
			break;
		default:
			break;
	}
	
	if(!_deletePressend && v_highlightedSuggestionDiv) {
		var _currentInputFieldValue = v_currentInputFieldValue;
		setStyleForElement(v_highlightedSuggestionDiv, "bAutoComplete");
		
		var A;
		if(_match) {
			A = _valueOfCAutoComplete(v_highlightedSuggestionDiv).substr(0);
		} else {
			A = _currentInputFieldValue;
		}
			
		if(A != _inputField.value) {
			if(_inputField.value != v_currentInputFieldValue) {
				return;
			}

			if(_inputField.createTextRange || _inputField.setSelectionRange) {
				selectEntry(A);
			}
			if(_inputField.createTextRange) {
				var u = _inputField.createTextRange();
				u.moveStart("character", _currentInputFieldValue.length);
				u.select();
			} else if (_inputField.setSelectionRange) {
				_inputField.setSelectionRange(_currentInputFieldValue.length, _inputField.value.length);
			}

		}
	} else {
		v_highlightedSuggestionIndex = -1;
	}
}

function lengthOfSelection(_inputField) {
	var _length = -1;
	if(_inputField.createTextRange) {
		var ha = document.selection.createRange().duplicate();
		_length = ha.text.length;
	} else if (_inputField.setSelectionRange) {
		_length = _inputField.selectionEnd - _inputField.selectionStart;
	}
	return _length;
}

function positionOfSelectionStart(_inputField) {
	var _pos = 0;
	if(_inputField.createTextRange) {
		var ha = document.selection.createRange().duplicate();
		ha.moveEnd("textedit", 1);
		_pos = _inputField.value.length - ha.text.length;
	} else if (_inputField.setSelectionRange) {
		_pos = _inputField.selectionStart;
	} else {
		_pos = -1;
	}
	return _pos;
}


function setStyleForElement(element, style) {
	element.className = style;

	switch(style.charAt(0)) {
		case "m":
			element.style.fontSize = "13px";
			element.style.fontFamily = "arial,sans-serif";
			element.style.wordWrap = "break-word";
			break;
		case "l":
			element.style.display = "block";
			//element.style.paddingLeft = "3";
			//element.style.paddingRight = "3";
			element.style.height = "16px";
			element.style.overflow = "hidden";
			break;
		case "a":
			element.style.backgroundColor = "white";
			element.style.color = "black";
			if (element.displaySpan) {
				element.displaySpan.style.color = "green"
			}
			break;
		case "b":
			element.style.backgroundColor = "#3366cc";
			element.style.color = "white";
			if (element.displaySpan) {
				element.displaySpan.style.color = "white"
			}
			break;
		case "c":
			//element.style.width = v_spanRefWidth + "%";
			element.style.width = "80%";
			element.style.cssFloat = "left";
			break;
		case "d":
			element.style.cssFloat = "right";
			//element.style.width = 100 - v_spanRefWidth + "%";
			element.style.width = "20%";

			element.style.fontSize = "10px";
			element.style.textAlign = "right";
			element.style.color = "green";
			//element.style.paddingTop = "3px"
			break;
	}
}

function displaySuggestList(_dropdownDiv, _array1, _array2) {
	while(_dropdownDiv.childNodes.length > 0)
		_dropdownDiv.removeChild(_dropdownDiv.childNodes[0]);
	
	for(var c=0; c<_array1.length; ++c) {
		var _div = document.createElement("DIV");
		setStyleForElement(_div, "aAutoComplete");
		_div.onmousedown = f_onMouseDown;
		_div.onmouseover = f_onMouseOver;
		_div.onmouseout = f_onMouseOut;
		
		var _span1 = document.createElement("SPAN");
		setStyleForElement(_span1, "lAutoComplete");
		
		var _span2 = document.createElement("SPAN");
		_span2.innerHTML=_array1[c];
		
		var _span3 = document.createElement("SPAN");
		setStyleForElement(_span3, "dAutoComplete");
		setStyleForElement(_span2, "cAutoComplete");
		
		_div.displaySpan = _span3;
		_span3.innerHTML = _array2[c];
		
		_span1.appendChild(_span2);
		_span1.appendChild(_span3);
		_div.appendChild(_span1);
		_dropdownDiv.appendChild(_div)
	}
}

function getXMLHTTP() {
	var C = null;
	try {
		C = new ActiveXObject("Msxml2.XMLHTTP")
	} catch(e){
		try {
			C = new ActiveXObject("Microsoft.XMLHTTP")
		} catch(sc){
			C = null
		}
	}
	if (!C && typeof XMLHttpRequest!="undefined") {
		C = new XMLHttpRequest()
	}
	return C
}

function getServerResponse(query) {
	if(v_xmlHttp && v_xmlHttp.readyState != 0) {
		v_xmlHttp.abort()
	}
	v_xmlHttp = getXMLHTTP();
	if(v_xmlHttp) {
		v_xmlHttp.open("GET", v_completeURI + "?c=" + query, true);
		v_xmlHttp.onreadystatechange = function() {
			if(v_xmlHttp.readyState == 4 && v_xmlHttp.responseText) {
				if(v_xmlHttp.responseText.charAt(0) == "<") {
					v_timeoutAdjustment--;
				} else {
					eval(v_xmlHttp.responseText);
				}
			}
		};
		v_xmlHttp.send(null);
	}
}

function selectEntry(value) {
	v_inputField.value = value;
	v_inputFieldValue = value;
}

// ---------------

function log(logMessage) {
	var _jetzt = new Date();
	var _j_s = _jetzt.getHours() + ":" +
			_jetzt.getMinutes() + ":" +
			_jetzt.getSeconds() + "." +
			_jetzt.getMilliseconds();
			
	v_logArea.value = _j_s + " --> " + logMessage + "\n" + v_logArea.value;
}