var isSuggestVisible = false;
var isInputHelpVisible = false;
var sgrows=0; // number of suggest rows in the suggest table
var sgcols; // array of number of suggest aspects in the suggest table rows
var selrow=-1;
var suggestTimerId = null;
var suggestTimeout = 400; //msec
var suggestTimerRunning = false;
var showSuggest = true;
var blockLostFocus = false;
var closeText = "";
var lastInputValue = "";
var lastUserInput = "";
var lastSuggestInput = "";
var KEY_BACKSPACE=8,KEY_DEL=46,KEY_UP=38,KEY_DOWN=40,KEY_ENTER=13,KEY_ESCAPE=27,KEY_HOME=36,KEY_END=35,KEY_PAGEDOWN=34,KEY_PAGEUP=33,KEY_SHIFT=16;
var inputHelpDivId = "ihdiv";
var initialStringsCount = 0;
var LOCAL_TEST = true; // this variable should be set to FALSE before commit!!!!

var scoocs = new Object();
var ajax = new Object();
ajax.lastresponsetime = (new Date).getTime();
var MAX_SUGGEST_COUNT = 10;
var webAppPath;
var isComboSubmit = false;
var isStartSite = false;
var searchAnywhere = false;

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
        for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
            var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
    },
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
            string: navigator.userAgent,
            subString: "iPhone",
            identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
};
BrowserDetect.init();

if (window.XMLHttpRequest == undefined) {
    scoocs.XMLHttpRequest = function() {
        try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
          catch(e) {}
        try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
          catch(e) {}
        try { return new ActiveXObject("Msxml2.XMLHTTP"); }
          catch(e) {}
        try { return new ActiveXObject("Microsoft.XMLHTTP"); }
          catch(e) {}
        throw new Error("This browser does not support XMLHttpRequest.");
    }
} else {
    scoocs.XMLHttpRequest = function() {
        return new XMLHttpRequest;
    }
}
function setWebPath(webPath) {
    webAppPath = webPath;
}
function sendSuggestRequest(inputid, divid, parnametimestamp, parnameinput, paramtab, paramlimit, paramqualifier1, paramqualifier2, defaultaspects, separator) {
    var currInputValue = getInputValue(inputid);
    if (currInputValue != lastUserInput) lastUserInput = currInputValue;
    if (lastUserInput.length > 0) {
        if (lastSuggestInput != lastUserInput) {
            var get = scoocs.XMLHttpRequest();
            var timestampstr = (new Date).getTime().toString();
            get.onreadystatechange = function() {
                if (get.readyState == 4) { // completed
                    if (get.status == 200) { // successful
                        var response = get.responseText;
                        if (response != null) {
                            var newSuggests = getSuggests(response.split('|'));
                            if (newSuggests != null) {
                                ajax.suggests = newSuggests;
                                updateSuggests(inputid, divid);
                                lastSuggestInput = lastUserInput;
                            } else {
                                destroySuggestDiv(divid);
                                lastSuggestInput = lastUserInput;
                                var tokens = concatTokens(lastSuggestInput.normalize().tokenize());
                                highlightIHS(tokens.length);
                            }
                        }
                    }
                }
            };
            var url = (LOCAL_TEST) ? ("/suggest?") : ("/" + webAppPath + "/suggest?"); 
            url += parnametimestamp + "=" + timestampstr;
            url += "&" + parnameinput + "=" + encodeURIComponent(lastUserInput);
            url += "&" + paramlimit + "=" + MAX_SUGGEST_COUNT;
            url += "&" + paramtab;
            if (!searchAnywhere) {
                var qualifier1 = document.getElementById(inputid+paramqualifier1);
                var defaults = defaultaspects.split(separator);
                if (qualifier1 != null) {
                    if (!isDefaultAspectQualifier(defaults, qualifier1.innerHTML)) {
                        url += "&" + paramqualifier1 + "="+encodeURIComponent(qualifier1.innerHTML);
                    }
                }
                var qualifier2 = document.getElementById(inputid+paramqualifier2);
                if (qualifier2 != null) {
                    if (!isDefaultAspectQualifier(defaults, qualifier2.innerHTML)) {
                        url += "&" + paramqualifier2 + "="+encodeURIComponent(qualifier2.innerHTML);
                    }
                }
            }
            get.open("GET", url, true);
            get.send(null);
        }
    } else {
        destroySuggestDiv(divid);
    }
    suggestTimerRunning = false;
}
function getSuggests(responseData) {
    var responsetime = parseInt(responseData[0]);
    var newSuggests = null;
    if (responseData.length > 1) {
        if (ajax.lastresponsetime < responsetime) {
            ajax.lastresponsetime = responsetime;
            // update suggests array
            newSuggests = new Array(responseData.length-1);
            for(var i=0; i < newSuggests.length; i++) {
                var suggests = responseData[i+1].split(';');
                if (suggests.length > 1) {
                    newSuggests[i] = new Array(suggests.length+1);
                    var ranglists = suggests[suggests.length-1].trim();
                    var separatorPos = ranglists.indexOf('#');
                    if (separatorPos >= 0){
                        var j=0;
                        var ranglist1 = ranglists.substring(0, separatorPos);
                        var ranglist2 = ranglists.substr(separatorPos+1);
                        for (;j < suggests.length-1; j++) {
                            newSuggests[i][j] = suggests[j];
                        }
                        newSuggests[i][j] = ranglist1;
                        newSuggests[i][j+1] = ranglist2;
                    } else {
                        // no separator
                        var j = 0;
                        for (; j < suggests.length; j++) {
                            newSuggests[i][j] = suggests[j];
                        }
                        newSuggests[i][j] = "";
                    }
                }
            }
        }
    }
    return newSuggests;
}

function hideInitialText(input, is1,is2,is3, maincolor) {
    if(input.value == getInitialInputText(is1,is2,is3)) {
        input.value = '';
        input.style.fontWeight = "normal";
        input.style.color = maincolor;
        var strArray = [is1, is2, is3];
        var restoreSiteType = false;
        if (!isStartSite) {isStartSite = true; restoreSiteType = true;}
        createInputHelperDiv(input, inputHelpDivId, strArray);
        if (restoreSiteType) isStartSite = false;
    }
}
function restoreInitialText(input, is1, is2, is3, initialcolor) {
    if(input.value == '') {
        input.value = getInitialInputText(is1,is2, is3);
        input.style.color = initialcolor;
        input.style.fontWeight = "bold";
        destroyInputHelperDiv(inputHelpDivId);
    }
}
function fillInputField(inputid, text, close) {
    var input = document.getElementById(inputid);
    if (input != null) {
        input.value = text;
    }
    if (close != null && close != "undefined") closeText = close;
}
function replaceInitialText(inputid, initialtext, newtext, newcolor) {
    if (newtext != null && newtext.toLowerCase() != "null") {
        var input = document.getElementById(inputid);
        if (input != null) {
            var initialstrings = initialtext.split(" ");
            if (initialstrings.length > 0) {
                hideInitialText(input, initialstrings.length>0?initialstrings[0]:null,initialstrings.length>1?initialstrings[1]:null,initialstrings.length>2?initialstrings[2]:null, newcolor);
            }
            if (newtext != null && newtext != "undefined") {
                while (newtext != newtext.replace("&dquot",'"')) {
                    newtext = newtext.replace("&dquot",'"');    
                }
                var tokens = concatTokens(newtext.normalize().tokenize());
                highlightIHS(tokens.length+1);
                input.value = newtext;
            }
            input.focus();
        }
    }
}
function getInitialInputText(is1, is2, is3) {
    return (((is1 != null && is1 != "null") ? is1 + " " : "") + ((is2 != null && is2 != "null") ? is2 + " " : "") + ((is3 != null && is3 != "null") ? is3: "")).trim();
}
function getInputFieldWidth(inputfield) {
    return inputfield.clientWidth;
}
function getInputFieldHeight(inputfield) {
    return inputfield.clientHeight;
}
function getElementPos(element) {
    var pos = new Object();
    var parent = element.offsetParent;
    var offsetLeft = element.offsetLeft;
    var offsetTop = element.offsetTop;
    while((parent != null)) {
        offsetLeft += parent.offsetLeft;
        offsetTop += parent.offsetTop;
        parent = parent.offsetParent;
    }
    pos.x = offsetLeft;
    pos.y = offsetTop;
    return pos;
}
function computeSuggestPos(input, div) {
    var inputfield = input;
    if (typeof inputfield =="string") {
        inputfield = document.getElementById(input+"tbl");
    }
    var sgstdiv = div;
    if (typeof sgstdiv =="string") {
        sgstdiv = document.getElementById(div);
    }
    if (inputfield != null && sgstdiv != null) {
        var width = getInputFieldWidth(inputfield);
        var height = getInputFieldHeight(inputfield);
        var pos = getElementPos(inputfield);
        if (BrowserDetect.browser=="Firefox") {
            if (!isStartSite) width -= 1;
            else pos.y += 2;
            pos.y -= BrowserDetect.version >= "3.0" ? 4 : 3;
            pos.x -= 1;
        } else if(BrowserDetect.browser=="Opera" || BrowserDetect.browser=="Chrome" || BrowserDetect.browser=="Safari") {
            if (!isStartSite) {
                if (BrowserDetect.browser=="Opera") pos.y -= 4;
                else pos.y -=2;
                width -=2;
            } else {
                pos.y +=1;
            }
        } else if (BrowserDetect.browser=="Explorer") {
            pos.y -= 4;
            width += 4;
            if (isStartSite) { width += 2; pos.y += 4;}
        }
        sgstdiv.style.top = "" + (pos.y + height + 1) + "px";
        sgstdiv.style.left = "" + pos.x + "px";
        sgstdiv.style.width = ""+ width +"px";
    }
}
function getSuggestHTML(suggests, inputid, divid) {
    var html = "<table id=\"tbl" + divid + "\" width=\"100%\">";
    sgrows = suggests.length;
    sgcols = new Array(suggests.length);
    for (var row=0; row < suggests.length; row++) {
        var suggest = suggests[row];
        var sgstcount = suggest.length;
        sgcols[row] = sgstcount - 1; // last element is a rank list element
        // top border
        html += "<tr><td id=\"t"+row+"\" class=\"sgtb\" colspan=\"10\" width=\"100%\"><img src=\"/images/invisible_transp.gif\"/></td></tr>"
        // suggest row border
        html += "<tr class=\"sgr\" id=\""+row+"\" onmousemove=\"mouseMoved("+row +",'"+inputid+"')\" onclick=\"mouseClicked('"+divid+"','"+inputid+"');\" onmouseover=\"blockFocus();\" onmouseout=\"unblockFocus();\" >"
        for(var col=0; col < sgstcount; col++) {
            html += "<td id=\""+row+"_"+col+"\" class=\"" + ((col==sgstcount-2 || col==sgstcount-1) ? "sgrl" : "sg") + "\"";// id="i_j", i,j - indices
            if (suggest[col].length  > 40) {
                html += ">";
            } else {
                html += " nowrap>";
            }
            html += suggest[col];
            if (col == sgstcount-2 && suggest[col].length > 0 && suggest[col+1].length > 0) {
                html += ",";    
            }
            html += "</td>";
        }
        html += "</tr>"
        // bottom border
        html += "<tr><td id=\"b"+row+"\" class=\"sgtb\" colspan=\"10\" width=\"100%\"><img src=\"/images/invisible_transp.gif\"/></td></tr>"
    }
    // close link
    html += "<tr><td width=\"100%\" colspan=\"10\">";
    html += "<table width=\"100%\"><tr class=\"clbtn\"><td class=\"nobtn\" width=\"100%\">&nbsp;</td><td class=\"clbtnimg\" onclick=\"closeSuggest('"+divid+"');\" onmouseover=\"blockFocus();\" onmouseout=\"unblockFocus();\"><img src=\"/images/close_circle.gif\"/></td><td class=\"clbtntd\" onclick=\"closeSuggest('"+divid+"');\" onmouseover=\"blockFocus();\" onmouseout=\"unblockFocus();\">&nbsp;"+closeText+"</td></tr></table>"
    html += "</td></tr>";
    html += "</table>";
    return html;
}
function highlightSuggestRow(row) {
    if (row < sgrows) {
        var tr;
        // suggest row
        tr = document.getElementById(""+row);
        if (tr != null) {
            var cl ="sgrs";
            tr.setAttribute("class", cl);
            tr.className = cl;
        }
        // top border
        tr = document.getElementById("t"+row);
        if (tr != null) {
            tr.setAttribute("class", "sgtbs");
            tr.className = "sgtbs";
        }
        // bottom border
        tr = document.getElementById("b"+row);
        if (tr != null) {
            tr.setAttribute("class", "sgtbs");
            tr.className = "sgtbs";
        }
    }
}
function removeSgstHighlight() {
    if (selrow >= 0) {
        var tr;
        // suggest row
        for(var col=0; col<=sgcols[selrow]; col++){
            tr = document.getElementById(""+selrow);
            if (tr != null) {
                var cl = "sgr";
                tr.setAttribute("class", cl);
                tr.className = cl;
            }
        }
        // top border
        tr = document.getElementById("t"+selrow);
        if (tr != null) {
            tr.setAttribute("class", "sgtb");
            tr.className = "sgtb";
        }
        // bottom border
        tr = document.getElementById("b"+selrow);
        if (tr != null) {
            tr.setAttribute("class", "sgtb");
            tr.className = "sgtb";
        }
    }
}
function destroySuggestDiv(divid) {
    var sgstDiv = document.getElementById(divid);
    if (sgstDiv != null) {
        isSuggestVisible = false;
        sgrows = 0; sgcols = null;
        sgstDiv.style.display = "none";
        document.body.removeChild(sgstDiv);
    }
    destroySuggestTimer();
    lastSuggestInput = "";
}
function closeSuggest(divid) {
    showSuggest = false;
    destroySuggestDiv(divid);
    unblockFocus();
}
function blockFocus() {
    blockLostFocus = true;
}
function unblockFocus() {
    blockLostFocus = false;
}
function lostInputFocus(sgstDivId, inputid) {
    if (!blockLostFocus) {
        var input = document.getElementById(inputid);
        if (input != null) {
            var inputtext = input.value;
            if (inputtext != null && inputtext.length > 0) {
                var tokens = concatTokens(inputtext.normalize().tokenize());
                highlightIHS(tokens.length+1);
            }
        }
        destroySuggestDiv(sgstDivId);
    }
}
function getSuggestRowHTML(text, boldtext) {
    if (text != null && boldtext != null) {
        if (text.toLowerCase().indexOf(boldtext.toLowerCase(),0)==0) {// starts with bold text
            return "<b><font color=\"#CC3300\">"+ text.substr(0, boldtext.length) + "</font></b>" + text.substr(boldtext.length, text.length-boldtext.length);
        }
    }
    return text;
}
// Enhancement of String-Object. Deletes whitespaces or given charakters (clist) form start of the string
String.prototype.trimleft = function (clist) {
  if (clist) // In diesem Fall sollen nicht Whitespaces, sondern alle Zeichen aus dieser Liste gelöscht werden, die am Anfang des Strings stehen.
    return this.replace (new RegExp ('^[' + clist + ']+'), '');
  return this.replace (/^\s+/, '');  // Führende Whitespaces aus dem String entfernen und das resultierende String zurückgeben.

}

// Enhancement of String-Object. Deletes whitespaces or given charakters (clist) form end of the string
String.prototype.trimright = function (clist) {
    if (clist) return this.replace (new RegExp ('[' + clist + ']+$'), '');
    return this.replace (/\s+$/, '');
}

// Enhancement of String-Object. Deletes whitespaces or given charakters (clist) form start and end of the string
String.prototype.trim = function (clist) {
  if (clist)
    return this.trimleft(clist).trimright(clist);
  return this.trimleft().trimright();
};

String.prototype.normalize = function () {
    // replace multiple spaces of this string with single spaces
    var res;
    res = this.trim().replace(/\s+/g, ' ');
    return res;
}

String.prototype.tokenize = function () {
    if (this.indexOf('"', 0) < 0) {
        return this.split(' ')
    } else {
        var alltokens = this.split(' ');
        var notemptytokens = new Array(alltokens);
        for (var a=0,n=0; a < alltokens.length; a++) {
            var token = alltokens[a].trim();
            if (token.indexOf('"') == 0 && token.indexOf('"', token.length-1) != token.length-1) {
                a++;
                notemptytokens[n] = token;
                while (a < alltokens.length && (token = alltokens[a].trim()).indexOf('"', token.length-1) != token.length-1) {
                    a++;
                    notemptytokens[n] += ' '+token;
                }
                if (a < alltokens.length) notemptytokens[n] += ' '+token;
                notemptytokens[n] = notemptytokens[n].trim('"');
                n++;
            } else {
                notemptytokens[n++] = token.trim('"');
            }
        }
        return notemptytokens;
    }
}

function unquote(s) {
    return s.trim().trim("\"");
}

function isInputChanged(inputid) {
    var input = document.getElementById(inputid);
    if (input != null) {
        if (lastInputValue == input.value.toLocaleLowerCase()) {
            return false;
        } else {
            lastInputValue = input.value.toLocaleLowerCase();
            return true;
        }
    }
    return true;
}
function getKeyCode(e) {
    var keycode = 0;
    var evt=(e) ? e : (window.event) ? window.event : null;
    if (evt) {
        keycode = (evt.charCode) ? evt.charCode :((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which:0));
    }
    return keycode;
}
function getInputValue(inputid){
    var input = document.getElementById(inputid);
    if (input != null) return input.value.trim();
    else return "";
}
function processKeyUp(event, inputid, divid, parnametimestamp, parnameinput, paramtab, paramlimit, paramqualifier1, paramqualifier2, defaultaspects, separator) {
    if (showSuggest) {
        var keycode = getKeyCode(event);
        if (keycode != KEY_ESCAPE ) {
            if (isInputChanged(inputid)) {
                lastUserInput = getInputValue(inputid).toLowerCase();
                if (suggestTimerRunning) destroySuggestTimer();
                suggestTimerId = setTimeout("sendSuggestRequest('"+inputid+"','"+divid+"','"+parnametimestamp+"','"+parnameinput+"','"+paramtab+"','"+paramlimit+"','" + paramqualifier1 + "','" + paramqualifier2 + "','" + defaultaspects + "','" + separator + "')", suggestTimeout);
                suggestTimerRunning = true;
            }
        } else {
            destroySuggestDiv(divid);
            removeIHShighlight();
            fillInputField(inputid, "", null);
        }
    }
    return true;
}
function processKeyDown(event, inputid) {
    if (showSuggest) {
        var keycode = getKeyCode(event);
        var newpos;
        if (keycode == KEY_DOWN) {
            if (selrow + 1 == sgrows) newpos = -2;
            else if (selrow < 0) newpos = 0;
            else newpos = selrow + 1;
            moveSgstMarkerTo(newpos, inputid, false);
        } else if (keycode == KEY_UP) {
            if(selrow == 0) newpos = -1;
            else if(selrow < 0) newpos = sgrows-1;
            else newpos = selrow -1;
            moveSgstMarkerTo(newpos, inputid, false);
        }
    }
}
function updateInputField(inputid) {
    //update input text
    var input = document.getElementById(inputid);
    if (input != null) {
        var text = "";
        for(var col=0; col < sgcols[selrow]-1; col++) {
            var td = document.getElementById(""+selrow+"_"+col);
            if (td != null) {
                var tdtext=getTDtext(td).trim().trim(",");
                if(text.length > 0 && tdtext.length > 0) text += "  ";
                if (tdtext.indexOf(" ",0) > 0) { // multiple words
                    tdtext = "\""+tdtext+"\"";
                }
                text += tdtext;
            }
        }
        input.value = text;
        lastInputValue = text.toLocaleLowerCase();
    }
}
function mouseMoved(row, inputid) {
    if (selrow != row)  moveSgstMarkerTo(row, inputid, true);
}
function mouseClicked(divid, inputid) {
    updateInputField(inputid);
    updateInputRanklistQualifiers(inputid + "rl1", inputid + "rl2");
    unblockFocus();
    lostInputFocus(divid, inputid);
    // click submit button to display selected rankprofile
    document.getElementById("ranksearch").click();
}
function moveSgstMarkerTo(nepos, inputid, isMouseEvent){
    removeSgstHighlight();
    var input = document.getElementById(inputid);
    if (input != null) {
        selrow = nepos;
        if (nepos < 0) {
            input.value = lastUserInput;
        } else {
            highlightSuggestRow(nepos);
            if (!isMouseEvent) updateInputField(inputid);
        }
        updateSuggestHTML(concatTokens(input.value.normalize().tokenize()));
        if (!isMouseEvent) updateInputRanklistQualifiers(inputid + "rl1", inputid + "rl2");
    }
}
function updateInputRanklistQualifiers(irlid1, irlid2){
    var irl1 = document.getElementById(irlid1);
    var selrl1 = document.getElementById(""+selrow+"_"+(sgcols[selrow] - 1));
    var currText = null;
    if (irl1 != null && selrl1 != null) {
        currText = removeHTMLTags(selrl1.innerHTML.trim(","));
        var combo = getComboById(getComboId(irlid1));
        if (currText.length > 0) {
            if (isStartSite) irl1.value = currText;
            else irl1.innerHTML = currText;
        } else if (combo != null) {
            irl1.innerHTML = combo.firstitem;
        }
        if (combo!= null && combo.slaveTDids != null && combo.slaveTDids != "undefined") {
            for (var i=0; i < combo.slaveTDids.length; i++) {
                switchSlave(combo, combo.slaveTDids[i], (!isDefaultRanglist(combo, currText) || currText.length == 0) ? "display" : "hide");
            }
        }
    }
    var irl2 = document.getElementById(irlid2);
    var selrl2 = document.getElementById(""+selrow+"_"+(sgcols[selrow]));
    if (irl2 != null && selrl2 != null) {
        currText = removeHTMLTags(selrl2.innerHTML.trim(","));
        var combo = getComboById(getComboId(irlid2));
        if (currText.length > 0) {
            if (isStartSite) irl2.value = currText;
            else irl2.innerHTML = currText;
        } else {
            irl2.innerHTML = combo.firstitem;
        }
        if (combo!= null && combo.slaveTDids != null && combo.slaveTDids != "undefined") {
            for (var i=0; i < combo.slaveTDids.length; i++) {
                switchSlave(combo, combo.slaveTDids[i], (!isDefaultRanglist(combo, currText)) ? "display" : "hide");
            }
        }
    }
}
function setInputRanklistQualifiers(irlid1,irlid2,qual1,qual2){
    var irltd;
    if (qual1 != null && qual1.toLowerCase() != "null" && qual1.length > 0 && irlid1 != null) {
        irltd = document.getElementById(irlid1);
        if (irltd != null) irltd.innerHTML = qual1;
    }
    if (qual2 != null && qual2.toLowerCase() != "null" && qual2.length > 0 && irlid2 != null) {
        irltd = document.getElementById(irlid2);
        if (irltd != null) irltd.innerHTML = qual2; 
    }
}
function destroySuggestTimer() {
    if (suggestTimerRunning && suggestTimerId != null) {
        suggestTimerRunning = false;
        clearTimeout(suggestTimerId);
        suggestTimerId = null;
    }
}
function updateSuggests(inputid, divid) {
    var inputtxt = getInputValue(inputid);
    if (inputtxt == null || inputtxt.length == 0) {
        destroySuggestDiv(divid);
        removeIHShighlight();
    } else {
        if(!isSuggestVisible) {
            createSuggestDiv(inputid, divid);
        } else {
            var sgdiv = document.getElementById(divid);
            if (sgdiv != null) sgdiv.innerHTML = getSuggestHTML(ajax.suggests, inputid, divid);
        }
        updateSuggestHTML(concatTokens(inputtxt.normalize().tokenize()));
        document.getElementById(divid).style.width = document.getElementById("tbl"+divid).clientWidth+"px";
    }
    removeSgstHighlight();
    selrow = -1;
    destroySuggestTimer();
}
function concatTokens(tokens) {
    if (tokens.length > initialStringsCount) {
        var ctokens = new Array(initialStringsCount);
        var i=0;
        for(i; i < initialStringsCount; i++) {
            ctokens[i] = tokens[i];
        }
        for (var j=i; j < tokens.length; j++) {
            ctokens[i-1] += ' ' + tokens[j];
        }
        return ctokens;
    } else {
        return tokens;
    }
}
function updateSuggestHTML(tokens) {
    for (var tok=0; tok < tokens.length; tok++) { // all tokens
        for (var col=tok; col < sgcols[0]+1; col++) { // columns from token index!
            for (var row=0; row < sgrows; row++) { // all rows
                var td = document.getElementById(""+row+"_"+col); // <td> element
                if (td != null) {
                    var textContent = getTDtext(td);
                    if (textContent != null && textContent.toLocaleLowerCase() != 'undefined') {
                        td.innerHTML = getSuggestRowHTML(textContent, tokens[tok]);
                    }
                }
            }
        }
    }
    highlightIHS(tokens.length);
}
function getTDtext(td) {
    var textContent = td.textContent;
    if (textContent == null || textContent.toLocaleLowerCase() == 'undefined') {
        textContent = td.innerText;
    }
    return textContent;
}

function createSuggestDiv(inputid, divid) {
    destroySuggestDiv(divid);
    var sgstDiv = document.createElement("div");
    sgstDiv.innerHTML = getSuggestHTML(ajax.suggests, inputid, divid);
    sgstDiv.id = divid;
    sgstDiv.style.position = "absolute";
    sgstDiv.style.visibility = "visible";
    sgstDiv.style.zIndex = "1000";
    sgstDiv.style.border = "1px solid #b0b0b0";
    sgstDiv.style.backgroundColor = "white";
    sgstDiv.style.width = "100%";
    sgstDiv.height = "100%";
    computeSuggestPos(inputid, sgstDiv);
    document.body.appendChild(sgstDiv);
    sgstDiv.style.width = document.getElementById("tbl"+divid).clientWidth+"px";
    isSuggestVisible = true;
}

function destroyInputHelperDiv(id) {
    var ihDiv = document.getElementById(id);
    if (ihDiv != null) {
        isInputHelpVisible = false;
        ihDiv.style.display = "none";
        document.body.removeChild(ihDiv);
        var rltext = document.getElementById("rltext");
        if (rltext != null) {
            rltext.style.visibility = "hidden";
        }
    }
}
function computeInputHelperPos(input, div) {
    var inputfield = input;
    if (typeof inputfield =="string") {
        inputfield = document.getElementById(input);
    }
    var ihdiv = div;
    if (typeof ihdiv =="string") {
        ihdiv = document.getElementById(div);
    }
    if (inputfield != null && ihdiv != null) {
        var pos = getElementPos(inputfield);
		if(BrowserDetect.browser == "Opera"){
			pos.y +=1;
		}
        ihdiv.style.top = "" + (pos.y - ihdiv.clientHeight - 2) + "px";
        ihdiv.style.left = "" + pos.x + "px";
    }
}
function getInputHelperHTML(initialstrings) {
    initialStringsCount = 0;
    var html = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
    for (var hs=0; hs < initialstrings.length; hs++) {
        var helpstr = initialstrings[hs];
        if (helpstr != null && helpstr != "null") {
            html += "<td class=\"hsu\" id=\"hs"+hs+"\" name=\"tdhs\" nowrap>" + helpstr + "<img id=\"hsi"+hs+"\" name=\"hsim\" style=\"visibility:hidden;padding-left:3px;\" src=\"/images/hook_green.gif\" border=\"0\"></img></td>";
            initialStringsCount++;
        }
    }
    html += "</tr></table>"
    return html;
}
function getElementsById(idtemplate) { // getDocumentsByName does not works sometimes in IE
    var elements = new Array();
    for (var i=0; i < 10; i++) {
        var element = document.getElementById(idtemplate+i);
        if (element != null) {
            elements[i] = element;
        } else {
            return elements;
        }
    }
    return new Array();
}
function removeIHShighlight() {
    var hslist = getElementsById("hs");
    var imglist = document.getElementsByName("hsim");
    for (var i=0; i<hslist.length; i++) {
        hslist[i].setAttribute("class","hsu");
        hslist[i].className = "hsu";
        imglist[i].style.visibility = "hidden";
    }
}
function highlightIHS(tokencount) {
    var hs;
    removeIHShighlight();
    // highlight the las element
    hs = document.getElementById("hs"+(tokencount-1));
    if (hs != null) {
        hs.setAttribute("class","hss");
        hs.className="hss";
    }
    for (var i=0; i<tokencount-1; i++) {
        hs = document.getElementById("hsi"+i);
        if (hs != null) {
            hs.style.visibility = "visible";
        }
    }
}
function createInputHelperDiv(input, divid, initialstrings) {
    destroyInputHelperDiv(divid);
    var ihDiv = document.createElement("div");
    ihDiv.innerHTML = getInputHelperHTML(initialstrings);
    ihDiv.id = divid;
    ihDiv.style.position = "absolute";
    if (isStartSite) ihDiv.style.display = "none";
    else ihDiv.style.visibility = "visible";
    ihDiv.style.zIndex = "1000";
    document.body.appendChild(ihDiv);
    computeInputHelperPos(input, ihDiv);
    isInputHelpVisible = true;
    var rltext = document.getElementById("rltext");
    if (rltext != null) {
        rltext.style.visibility = "visible";
    }
}
function getFormElementById(form, id) {
    for (var i=0; i < form.elements.length; i++) {
        if (id == form.elements[i].id) return form.elements[i];
    }
    return null;
}
function submitRankQuery(form, inputid, rankobjdescrid, inputranklistid1, ranklistid1, inputranklistid2, ranklistid2, defaultAspects, separator, defaultintext, webranking, emptyInputAction, comboSubmitAction, actionid, rewriteIndex, currentTab){
    var inputRankList1 = document.getElementById(inputranklistid1);
    var inputRankList2 = document.getElementById(inputranklistid2);
    var rankListHidden1 = getFormElementById(form, ranklistid1);
    var rankListHidden2 = getFormElementById(form, ranklistid2);
    var rankObjectdescr = getFormElementById(form, rankobjdescrid);
    var inputField = getFormElementById(form, inputid);
    var defaultQualifiers = (defaultAspects != null) ? defaultAspects.split(separator) : new Array[0];
    var defaultQualifierFound = false;
    if (inputField != null && rankObjectdescr != null) {
        if (isStartSite) {
            if (inputRankList1 != null && rankListHidden1 != null) {
                if(!isDefaultAspectQualifier(defaultQualifiers, inputRankList1.innerHTML)) rankListHidden1.value = encodeURIComponent(inputRankList1.innerHTML.trim().replace("&amp;","&"));
                else {
                    rankListHidden1.removeAttribute("name");
                    if (rankListHidden2 != null && getComboById(inputranklistid2+"cb").data.length < 3) rankListHidden2.removeAttribute("name");
                }
            }
            if (inputRankList2 != null && rankListHidden2 != null) {
                if(!isDefaultAspectQualifier(defaultQualifiers, inputRankList2.innerHTML)) rankListHidden2.value = encodeURIComponent(inputRankList2.innerHTML.trim().replace("&amp;","&"));
                else {
                    rankListHidden2.removeAttribute("name");
                    if (rankListHidden1 != null && getComboById(inputranklistid1+"cb").data.length < 3) rankListHidden1.removeAttribute("name");
                }
            }
        } else {
            if (!searchAnywhere && inputRankList1 != null && rankListHidden1 != null) {
                if (!isDefaultAspectQualifier(defaultQualifiers, inputRankList1.innerHTML)) {
                    rankListHidden1.value = encodeURIComponent(inputRankList1.innerHTML.trim().replace("&amp;","&"));
                } else if (inputRankList2 != null && rankListHidden2 != null && comboBoxList[0] != null) {
                    if (isDefaultRanglist(comboBoxList[0], inputRankList1.innerHTML.trim()) || inputRankList1.innerHTML.trim() == webranking) {
                        defaultQualifierFound = true;
                        rankListHidden1.value = encodeURIComponent(inputRankList2.innerHTML.trim().replace("&amp;","&"));
                    } else {
                        rankListHidden1.removeAttribute("name");
                        if (rankListHidden2 != null && getComboById(inputranklistid2+"cb").data.length < 3) rankListHidden2.removeAttribute("name");
                    }
                }
            } else if (rankListHidden1 != null) {
                rankListHidden1.removeAttribute("name"); // don't submit
            }
            if (!searchAnywhere && !defaultQualifierFound && inputRankList2 != null && rankListHidden2 != null && !isDefaultAspectQualifier(defaultQualifiers, inputRankList2.innerHTML)) {
                rankListHidden2.value = encodeURIComponent(inputRankList2.innerHTML.trim().replace("&amp;","&"));
            } else if (rankListHidden2 != null) {
                rankListHidden2.removeAttribute("name"); // don't submit
                if (rankListHidden1 != null && getComboById(inputranklistid1+"cb").data.length < 3) rankListHidden1.removeAttribute("name");
            }
        }
        if (inputField.value != defaultintext && inputField.value.length > 0) {
            rankObjectdescr.value = encodeURIComponent(normalizeRequest(inputField.value).replace("&amp;","&"));
        } else {
            rankObjectdescr.removeAttribute("name"); // don't submit
            var actionfield = document.getElementById(actionid);
            if (actionfield != null) {
                if (isComboSubmit) actionfield.value = comboSubmitAction;
                else actionfield.value = emptyInputAction;
            }
        }
        if (rewriteIndex != "undefined" && currentTab != "undefined" && form.action) {
            form.action = form.action.substring(0, form.action.lastIndexOf("/")+1) + currentTab + "/" + rewriteIndex; // rewrite form action: index.jsp -> tab_name/index.html 
        }
        form.submit();
    }
}
function submitSelector(form, inputranklistid1, ranklistid1, inputranklistid2, ranklistid2, defaultAspects, separator) {
    var inputRankList1 = document.getElementById(inputranklistid1);
    var inputRankList2 = document.getElementById(inputranklistid2);
    var rankListHidden1 = getFormElementById(form, ranklistid1);
    var rankListHidden2 = getFormElementById(form, ranklistid2);
    var defaultQualifiers = (defaultAspects != null) ? defaultAspects.split(separator) : new Array[0];
    if (inputRankList1 != null && rankListHidden1 != null) {
        if(!isDefaultAspectQualifier(defaultQualifiers, inputRankList1.innerHTML)) rankListHidden1.value = encodeURIComponent(inputRankList1.innerHTML.trim().replace("&amp;","&"));
        else rankListHidden1.removeAttribute("name");
    }
    if (inputRankList2 != null && rankListHidden2 != null) {
        if(!isDefaultAspectQualifier(defaultQualifiers, inputRankList2.innerHTML)) rankListHidden2.value = encodeURIComponent(inputRankList2.innerHTML.trim().replace("&amp;","&"));
        else rankListHidden2.removeAttribute("name");
    }
    form.submit();
}
function isDefaultAspectQualifier(defaultQualifiers, aspectqual){
    for (var i=0; i<defaultQualifiers.length; i++) {
        if (aspectqual == defaultQualifiers[i]) return true;
    }
    return false;
}
function normalizeRequest(requestStr) {
    var normalizedStr = "";
    var tokens = requestStr.split(" ");
    if (tokens.length > 0) {
        for (var i=0; i < tokens.length; i++) {
            if (tokens[i].length > 0) {
                if (normalizedStr.length > 0) normalizedStr += " ";
                normalizedStr += tokens[i];
            }
        }
    } else {
        normalizedStr = requestStr.trim();
    }
    return normalizedStr;
}
//#############################################
// Ranklist combobox
//#############################################

var comboBoxList = new Array(2); // limit with 2 popups
var lastComboInput = "";
var filteringSuccess = false;
var checkSuccessInterval = -1;

function RanklistCombo(comboid, slaveTDids, referencedSlaveComboId, defaultQualifiers, separator, fixedwidth, onselect, ondeselect, checkInput) {
    this.id = comboid;
    this.popuptop = 0;
    this.popupleft = 0;
    this.popupwidth = 0;
    this.popupheight = 0;
    this.data = new Array();
    this.dataString = "";
    this.datalength = 0;
    this.popup = null;
    this.storeTDHtml = "";
    this.selectedItem = null;
    this.lastSelectedIndex = 0;
    this.slaveTDids = slaveTDids;
    this.referencedSlaveComboId = referencedSlaveComboId;
    this.slaves = null;
    this.storeParent = null;
    this.initialItem =  null;
    this.complete = "";
    this.defaultQualifiers = defaultQualifiers;
    if (defaultQualifiers != null && defaultQualifiers != "undefined") {
        this.defaultQualifiers = defaultQualifiers.split(separator);
    }
    this.onselect = null;
    if (onselect != null && onselect != "undefined") {
        this.onselect = onselect;
    }
    this.ondeselect = null;
    if (ondeselect != null && ondeselect != "undefined") {
        this.ondeselect = ondeselect;
    }
    this.fixedwidth = fixedwidth;
    this.checkInput = true;
    if (checkInput != null && checkInput != "undefined") {
        this.checkInput = checkInput;
    }
    var combocount = 0;
    while (comboBoxList[combocount] != undefined) combocount++;
    comboBoxList[combocount] = this;
    this.addData = function(data, separator) {
        this.data = data.split(separator);
        this.dataString = data.toLowerCase();
        this.firstitem = this.data[0];
    }
    this.setInitialItem = function(itemstr) {
        if(itemstr!=null&&itemstr!="undefined"&&itemstr.length>0) this.initialItem=itemstr;
    }
}
function recomputePopupPosition(inputid) {
    for (var i=0; i < comboBoxList.length; i++) {
        if (comboBoxList[i] != null && comboBoxList[i] != "undefined") {
            computePopupPos(getInputId(getTDId(comboBoxList[i].id)), comboBoxList[i]);
        }
    }
}
function getComboId(tdid) {
    return "" + tdid + "cb";
}
function getInputId(tdid) {
    return tdid + "i";
}
function getTDId(comboId) {
    if (comboId != null && comboId != undefined && comboId.length > 2) {
        return comboId.substr(0,comboId.length-2);
    }
    return "";
}
function getComboById(comboid) {
    for (var i=0; i < comboBoxList.length; i++) {
        if (comboBoxList[i] != undefined && comboBoxList[i] != null) {
            if (comboid == comboBoxList[i].id) {
                return comboBoxList[i];
            }
        }
    }
    return null;
}
function getSlaveComboBySlaveId(slaveid) {
    for (var i=0; i < comboBoxList.length; i++) {
        if (comboBoxList[i] != undefined && comboBoxList[i] != null) {
            if (slaveid == comboBoxList[i].referencedSlaveComboId) {
                return comboBoxList[i];
            }
        }
    }
    return null;
}
function lostFocus(tdid) {
    if (!blockLostFocus) {
        switchCombo(tdid);
    }
    return true;
}
function switchCombo(tdid) {
    var td = document.getElementById(tdid);
    if (td != null) {
        var comboid = getComboId(tdid);
        var combo = getComboById(comboid);
        if (combo == null) {
            combo = new RanklistCombo(comboid);
        }
        if (combo.storeTDHtml.length == 0) {
            combo.storeTDHtml = td.innerHTML;
//            if (combo.fixedwidth) {
                td.innerHTML = "<input class=\"fcombo\" type=\"text\" style=\"width:100%;border:0;\" id=\""+getInputId(tdid) +
                               "\" value=\"\" onblur=\"lostFocus('"+tdid+"')\" onkeyup=\"comboKeyUp(event, '"+tdid+"')\" onkeydown=\"comboKeyDown(event, '"+tdid+"')\" onkeypress=\"comboKeyPress(event, '"+tdid+"')\" autocomplete=\"off\"/>";
//            } else {
//                td.innerHTML = "<input type=\"text\" style=\"width:300px;padding-top:0;padding-bottom:0\" id=\""+getInputId(tdid) +
//                               "\" value=\"\" onblur=\"lostFocus('"+tdid+"')\" onkeyup=\"comboKeyUp(event, '"+tdid+"')\" onkeydown=\"comboKeyDown(event, '"+tdid+"')\" onkeypress=\"comboKeyPress(event, '"+tdid+"')\" autocomplete=\"off\"/>";
//            }
            var inputid = getInputId(tdid);
            showPopup(inputid, combo);
            setTimeout("setInputFocus('"+inputid+"')", 100); // block the event onblur by creating/displaying the popup div
            combo.lastSelectedIndex = 0;
            if(combo.initialItem != null) {
                lastComboInput = combo.initialItem.toLowerCase();
                filterComboItems(comboid, false);
                combo.initialItem=null;
            }
        } else {
            hidePopup(td, combo);
        }
    }
    return true;
}
function checkComboInputChanged(inputid) {
    var input = document.getElementById(inputid);
    if (input != null) {
        var inputvalue = input.value.trim();
        if (lastComboInput != inputvalue.toLowerCase()) {
            lastComboInput = inputvalue.toLowerCase();
            return true;
        }
    }
    return false;
}
function scrollToVisible(item, keycode) {
    var parent = item.parentNode;
    if (parent != undefined && parent != null) {
        var parentCHeight   = parent.clientHeight;
        var itemOffsetTop   = item.offsetTop;
        if (typeof itemOffsetTop == "object") {
            itemOffsetTop = itemOffsetTop.offsetTop;
        }
        var parentOffsetTop = parent.scrollTop;
        var itemHeight = item.clientHeight;
        if (itemHeight == undefined || itemHeight == 0) {
            itemHeight = item.scrollHeight;
        }
        if (((keycode == KEY_DOWN || keycode == KEY_PAGEDOWN || keycode == 0) && itemOffsetTop + itemHeight >= parentCHeight + parentOffsetTop) || ((keycode == KEY_UP || keycode == KEY_PAGEUP || keycode == 0) && itemOffsetTop <= parentOffsetTop)) {
            parent.scrollTop = itemOffsetTop + ((keycode == KEY_DOWN|| keycode == KEY_PAGEDOWN) ? (itemHeight - parentCHeight) : 0);
        }
        if (parent.parent) {
            scrollToVisible(parent);
        }
    }
}
function getItems(comboid) {
    var combo = comboid;
    if (typeof comboid =="string") {
        comboid = getComboById(comboid);
    }
    if (combo != undefined && combo != null && combo.popup.childNodes && combo.popup.childNodes.length > 0 && combo.popup.childNodes[0].childNodes) {
        return combo.popup.childNodes[0].childNodes;
    }
    return null;
}
function filterComboItems(comboid, readInputValue) {
    var returnValue = false;
    var combo = getComboById(comboid);
    var items = getItems(combo);
    var input;
    if (items != null) {
        if (readInputValue) {
            input = document.getElementById(getInputId(getTDId(comboid)));
            if (input != null) {
                lastComboInput = removeHTMLTags(input.value);
            }
        }
        try {
            var ind = document.getElementById("indexfinder").findindex(combo.dataString, "^", lastComboInput.toLowerCase());
            if (ind != -1) {
                combo.lastSelectedIndex = ind;    
            }
        } catch (e) {
            combo.lastSelectedIndex = 0;
        }
        for (var i=combo.lastSelectedIndex; i < items.length; i++) {
            var item = items[i];
            if (removeHTMLTags(item.innerHTML.toLowerCase()).indexOf(lastComboInput) == 0) {
                combo.lastSelectedIndex = i;
                returnValue = true;
                markUpItem(item, comboid);
                scrollToVisible(item, 0);
                input = document.getElementById(getInputId(getTDId(comboid)));
                if (input != null) {
                    combo.complete = removeHTMLTags(item.innerHTML).substr(lastComboInput.length);
                    if (input.setSelectionRange) {
                        input.value = lastComboInput + combo.complete;
                        input.setSelectionRange(lastComboInput.length, input.value.length);
                    } else if (input.createTextRange) {
                        input.value = lastComboInput + combo.complete;
                        var range = input.createTextRange();
                        if (range.findText) {
                            if (combo.complete.length > 0) range.findText(combo.complete);
                        } else range.move("character", (lastComboInput != "undefined" && lastComboInput != null) ? lastComboInput.length : 0);
                        if (combo.complete.length > 0) range.select();
                    }
                }
                break;
            }
        }
    }
    filteringSuccess = returnValue;
    return returnValue;
}
function comboKeyUp(event, tdid) {
    var keycode = getKeyCode(event);
    if (keycode == KEY_ESCAPE ) {
        hideAllPopups();
        return false;
    } else if (keycode == KEY_ENTER) {
        selectItem(getComboId(tdid));
        return false;
    } else if (keycode != KEY_DOWN && keycode != KEY_UP && keycode != KEY_HOME && keycode != KEY_END && keycode != KEY_PAGEDOWN && keycode != KEY_PAGEUP && keycode != KEY_DEL && keycode != KEY_BACKSPACE && keycode != KEY_SHIFT) {
        var storeLastcomboInput = lastComboInput;
        if (checkComboInputChanged(getInputId(tdid))) {
            if (!filterComboItems(getComboId(tdid))) {
                var input = document.getElementById(getInputId(tdid));
                if (input != undefined && input != null) {
                    lastComboInput = storeLastcomboInput;
                    input.value = lastComboInput;
                    filterComboItems(getComboId(tdid));
                }
            }
        }
    }
    return false;
}
function comboKeyDown(event, tdid) {
    var keycode = getKeyCode(event);
    if ((keycode == KEY_DOWN || keycode == KEY_UP || keycode == KEY_PAGEDOWN || keycode == KEY_PAGEUP) && (BrowserDetect.browser=="Explorer" || BrowserDetect.browser=="Chrome" || BrowserDetect.browser=="Safari")) {
        return comboKeyPress(event, tdid);
    }
    return false;
}
function comboKeyPress(event, tdid) {
    var keycode = getKeyCode(event);
    var firstselection = false;
    if (keycode == KEY_DOWN || keycode == KEY_UP || keycode == KEY_PAGEDOWN || keycode == KEY_PAGEUP) {
        var combo = getComboById(getComboId(tdid));
        if (combo != null) {
            var newSelectedItem = null;
            var items = getItems(combo);
            if (items != null && items.length > 0)
                if (combo.selectedItem == null) {
                    combo.selectedItem = items[0];
                    if (keycode != KEY_PAGEDOWN) {
                        newSelectedItem = combo.selectedItem;
                    }
                }
                if (newSelectedItem == null) {
                    if (keycode == KEY_DOWN) {
                        newSelectedItem = combo.selectedItem.nextSibling;
                    } else if (keycode == KEY_UP) {
                        newSelectedItem = combo.selectedItem.previousSibling;
                    } else if (keycode == KEY_PAGEUP) {
                        newSelectedItem = combo.selectedItem;
                        for (var i=11; i >0; i--) {
                            var currentitem = newSelectedItem.previousSibling;
                            if (currentitem == undefined || currentitem == null) break;
                            else newSelectedItem = currentitem;
                        }
                    } else if (keycode == KEY_PAGEDOWN) {
                        newSelectedItem = combo.selectedItem;
                        for (var i=0; i < 11; i++) {
                            var currentitem = newSelectedItem.nextSibling;
                            if (currentitem == undefined || currentitem == null) break;
                            else newSelectedItem = currentitem;
                        }
                    }
                }
                if (newSelectedItem != undefined && newSelectedItem != null) {
                    markUpItem(newSelectedItem, getComboId(tdid));
                    if (newSelectedItem) scrollToVisible(newSelectedItem, keycode);
                    var input = document.getElementById(getInputId(tdid));
                    if (input != undefined && input != null) {
                        input.value = removeHTMLTags(newSelectedItem.innerHTML.replace("&amp;","&"));
                    }
                }
        }
        if (event.preventDefault) event.preventDefault();
        return false;
    } else if (keycode == KEY_BACKSPACE || keycode == KEY_DEL) {
        var combo = getComboById(getComboId(tdid));
        if (combo != null) {
            combo.lastSelectedIndex = 0; // the filtering should be started from the first item
            if (keycode == KEY_BACKSPACE) {
                if (BrowserDetect.browser == "Explorer") {
                    setTimeout("comboBackspace('"+ getInputId(tdid) +"','"+combo.id+"','"+tdid+"')",100);
                } else {
                    var input = document.getElementById(getInputId(tdid));
                    var newinput = removeHTMLTags(lastComboInput);
                    input.value = newinput.substr(0,newinput.length-1);
                    lastComboInput = input.value;
                    setTimeout("filterComboItems('"+combo.id+"')", 100);
                    return false;
                }
            } else {
                var storeLastcomboInput = lastComboInput;
                lastComboInput = "";
                setTimeout("filterComboItems('"+combo.id+"',true)", 100);
                filteringSuccess = "undefined";
                checkSuccessInterval = setInterval("checkFilteringSuccess('"+ getInputId(tdid) +"','"+ combo.id +"','"+ storeLastcomboInput +"')",100);
            }
        }
    } else if (keycode == KEY_ENTER) {
        var combo = getComboById(getComboId(tdid));
        if (combo != null) {
            selectItem(combo.id);
        }
    }
    return true;
}
function checkFilteringSuccess(inputid, comboid, storeLastcomboInput) {
    if (filteringSuccess != "undefined" && !filteringSuccess) {
        var input = document.getElementById(inputid);
        if (input != undefined && input != null) {
            lastComboInput = storeLastcomboInput;
            input.value = lastComboInput;
            filterComboItems(comboid);
            clearInterval(checkSuccessInterval);
        }
    } else if (filteringSuccess) {
        clearInterval(checkSuccessInterval);
    }
}

function comboBackspace(inputid, comboid, tdid) {
    var input = document.getElementById(getInputId(tdid));
    var newinput = removeHTMLTags(lastComboInput);
    if (newinput.length > 0) input.value = newinput.substr(0,newinput.length-1);
    lastComboInput = input.value;
    filterComboItems(comboid);
}
function removeHTMLTags(str) {
    var result = "";
    if (str != null && str != "undefined") {
        var addSequence = true;
        for (var i=0; i < str.length; i++) {
            if (str.charAt(i) == '<') {
                addSequence = false;
            } else if (str.charAt(i) == '>') {
                addSequence = true;
            } else if (addSequence) {
                result += str.charAt(i);
            }
        }
    }
    return result;
}
function selectItem(comboid) {
    var combo = getComboById(comboid);
    if (combo != undefined) {
        var isNewSelection = combo.storeTDHtml && combo.storeTDHtml != removeHTMLTags(combo.selectedItem.innerHTML);
        if (combo.storeTDHtml != undefined) combo.storeTDHtml = combo.selectedItem.innerHTML;
        hideAllPopups();
        // call onselect/ondeselect function
        if (isNewSelection && combo.ondeselect != null && combo.onselect != null) {
            if (combo.ondeselect.indexOf('(') >=0 && combo.onselect.indexOf('(') >=0) {
                try {
                    if (isDefaultRanglist(combo, removeHTMLTags(combo.selectedItem.innerHTML))) {
                        if (combo.ondeselect != null) eval(combo.ondeselect); // deselect
                    } else {
                        if (combo.onselect != null) eval(combo.onselect); // select
                    }
                } catch (e) {};
            } else {
                isComboSubmit = !isDefaultRanglist(combo, removeHTMLTags(combo.selectedItem.innerHTML));
                submitComboSelection(combo.onselect, combo.ondeselect);
            }
        }
    }
}
function submitComboSelection(submitid, inputid) {
    var input = document.getElementById(inputid);
    if (input != null) {
        input.value = "";
    }
    var submit = document.getElementById(submitid);
    if (submit != null) {
        submit.click();
    }
}
function setInputFocus(inputid) {
    var input = document.getElementById(inputid);
    if (input != null) {
        input.focus();
    }
}
function isDefaultRanglist(combo, qualifier) {
    if (qualifier != null && qualifier != "undefined" && combo != null && combo.defaultQualifiers != null && combo.defaultQualifiers != "undefined") {
        for (var i=0; i < combo.defaultQualifiers.length; i++) {
            if (qualifier == combo.defaultQualifiers[i]) return true;
        }
    }
    return false;
}
function hidePopup(td, combo) {
    // Google Chrome processed innerHTML incorrectly!
    //if (td != null) td.innerHTML = removeHTMLTags(combo.storeTDHtml);
    if (td != null) {
        td.removeChild(td.childNodes[0]);
        var text = document.createTextNode(removeHTMLTags(combo.storeTDHtml).replace("&amp;","&"));
        td.appendChild(text);
    }
    if (combo.slaveTDids != null && combo.slaveTDids != "undefined") { // hide or show slaves
        var display = (!isDefaultRanglist(combo, td.innerHTML)) ? "display" : "hide";
        for (var i=0; i < combo.slaveTDids.length; i++) {
            switchSlave(combo, combo.slaveTDids[i], display);
        }
        if (display == "display") {
            combo.slaves = null;
            combo.storeParent = null;
        }
    }
    combo.storeTDHtml = "";
    if (combo.popup != null) {
        combo.popup.style.display = "none";
        combo.popuptop = 0;
        combo.popupleft = 0;
        combo.popupwidth = 0;
        combo.popupheight = 0;
    }
    lastComboInput = "";
}
function switchSlave(combo, slaveid, display) {
    var slave = document.getElementById(slaveid);
    if (display == "display") {
        if (combo.slaves != null && combo.storeParent != null) {
            slave = combo.slaves[slaveid];
            if (slave != null && slave != "undefined") {
                combo.storeParent.appendChild(slave);
                var slaveCombo = getSlaveComboBySlaveId(slave.id);
                if (slaveCombo != null) {
                    var td = document.getElementById(getTDId(slaveCombo.id));
                    if (td != null) {
                        td.innerHTML = slaveCombo.firstitem; 
                    }
                }
            }
        }
    } else if (slave != null) {
        if (combo.slaves == null) {
            combo.slaves = new Array(combo.slaveTDids.length);
        }
        combo.slaves[slaveid] = slave;
        if (combo.storeParent == null && slave != null) combo.storeParent = slave.parentNode; 
        slave.parentNode.removeChild(slave);
    }
}
function computePopupPos(input, combo) {
    var inputfield = input;
    if (typeof inputfield =="string") {
        inputfield = document.getElementById(input);
    }
    if (inputfield != null && combo != null && combo.popup != undefined && combo.popup != null) {
        var width = getInputFieldWidth(inputfield);
        var height = getInputFieldHeight(inputfield);
        var pos = getElementPos(inputfield);
        if (combo.fixedwidth) {
            pos.y -=2;
            width -= 1;
            if (BrowserDetect.browser == "Opera") {
                pos.x -=4;
                width -=2;
            } else if (BrowserDetect.browser == "Chrome" || BrowserDetect.browser == "Safari") {
                pos.x -= 2;
                pos.y += 3;
            } else pos.x -=4;
            if (BrowserDetect.browser == "Explorer") width += 3;
            else width +=5;
        } else {
            pos.y -= (BrowserDetect.browser == "Chrome" || BrowserDetect.browser == "Safari") ? 0 : 2;
            pos.x -= (BrowserDetect.browser == "Chrome" || BrowserDetect.browser == "Safari") ? 5 : 6;
            if (BrowserDetect.browser == "Explorer")
                width += isStartSite ? 25 : 29;
            else if (BrowserDetect.browser == "Opera") {
                width += 25;
            } else {
                width += 27;
            }
        }
        combo.popuptop = pos.y + height + 3;
        combo.popup.style.top = "" + combo.popuptop + "px";
        combo.popupleft = pos.x;
        combo.popup.style.left = "" + combo.popupleft + "px";
        combo.popupwidth = width + ((BrowserDetect.browser == "Firefox" && BrowserDetect.version < "2.0")? 1 : 2);
        combo.popup.style.width = "" + combo.popupwidth + "px";
    }
}
function getComboHTML(combo) {
    var html = "<div style=\"overflow-y:auto;overflow-x:hidden;" + ((combo.popupheight > 0) ? ("height:"+combo.popupheight+"px") : (""))+"\" onmousemove=\"blockFocus()\" onmouseout=\"unblockFocus()\">"
    if (combo.data.length > 0) {
        for (var i=0; i < combo.data.length; i++) {
            if (combo.data[i] != undefined && combo.data[i].length > 0)
                html += "<div class=\"cbdiv\" onmouseover=\"markUpItem(this,'"+combo.id+"')\" onclick=\"selectItem('"+combo.id+"')\">" + (i==0?"<b>":"") + combo.data[i] + (i==0?"</b>":"") + "</div>";
        }
    }
    html += "</div>"
    return html;
}
function getInitialComboHTML(combo) {
    var html = "<div style=\"overflow-y:auto;overflow-x:hidden;" + ((combo.popupheight > 0) ? ("height:"+combo.popupheight+"px") : (""))+"\">"
    html += "<table width=\"100%\" height=\"100%\"><tr><td width=\"100%\" align=\"center\">";
    html += "<img src=\"/images/wait_indicator.gif\" alt=\"\"/>"
    html += "</td></tr></table>";
    html += "</div>"
    return html;
}
function markUpItem(elm,comboid) {
    var combo = getComboById(comboid);
    if (combo != undefined && combo.selectedItem != null) {
        combo.selectedItem.setAttribute("class", "cbdiv");
        combo.selectedItem.className = "cbdiv";
    }
    if (elm != null && elm != undefined) {
        elm.setAttribute("class", "cbdivs");
        elm.className = "cbdivs";
        combo.selectedItem = elm;
    }
}
function hideAllPopups() {
    for (var i=0; i < comboBoxList.length; i++) {
        var combo = comboBoxList[i];
        if (combo != undefined && combo.popup != null && combo.popup != undefined && combo.popup.style.display == "block") {
            hidePopup(document.getElementById(getTDId(combo.id)), combo);
        }
    }
}
function loadMainHTML(comboid) {
    var combo = getComboById(comboid);
    if (combo != null) {
        combo.popup.innerHTML = getComboHTML(combo);
    }
}
function showPopup(inputid, combo) {
    hideAllPopups();
    if (combo.popup == undefined || combo.popup == null) {
        var comboDiv = document.createElement("div");
        combo.popupheight = combo.data.length > 10 ? 250 : 0;
        comboDiv.innerHTML = getInitialComboHTML(combo);
        comboDiv.id = combo.id;
        comboDiv.style.position = "absolute";
        comboDiv.style.display = "block";
        comboDiv.style.zIndex = "1000";
        comboDiv.style.border = "1px solid #b0b0b0";
        comboDiv.style.backgroundColor = "white";
        combo.popup = comboDiv;
        comboDiv.height = "" + combo.popupheight +"px";
        computePopupPos(inputid, combo);
        document.body.appendChild(comboDiv);
        if (BrowserDetect.browser == "Explorer" || (BrowserDetect.browser == "Firefox" && BrowserDetect.version < "3.0")) {
            setTimeout("loadMainHTML('"+combo.id+"')", 70);
        } else {
            loadMainHTML(combo.id);    
        }
        lastComboInput = "";
    } else {
        combo.popup.style.display = "block";
        computePopupPos(inputid, combo);
        combo.popupheight = combo.data.length > 10 ? 250 : 0;
        combo.popup.height = "" + combo.popupheight +"px";
        lastComboInput = "";
    }
}
//####################################################
// Descriptions
//####################################################
var visibleDescriptions = [null,null];
function switchDescription(alldiv, visdiv) {
    var allDiv = document.getElementById(alldiv);
    var visDiv = document.getElementById(visdiv);
    if (allDiv != null && visDiv != null) {
        var isVisible = isDescriptionVisible(allDiv);
        allDiv.style.display = (isVisible) ? "none" : "block";
        visDiv.style.display = (isVisible) ? "block" : "none";
        var snippetsSpan = document.getElementById("allsn");
        if (snippetsSpan != null) {
            if (snippetsSpan.innerHTML == null ||  snippetsSpan.innerHTML.length == 0) {
                var par3 = document.getElementById("p3");
                if (par3 != null) {
                    snippetsSpan.innerHTML = par3.innerHTML;
                }
            } else {
                snippetsSpan.innerHTML = "";
            }
        }
        if (isVisible) removeFromVisisble(allDiv);
        else addToVisisble(allDiv);
    }
}
function isDescriptionVisible(divid) {
    for(var i=0; i < visibleDescriptions.length; i++) {
        if (visibleDescriptions[i] != null && visibleDescriptions[i] == divid) return true;
    }
    return false;
}
function addToVisisble(divid) {
    for(var i=0; i < visibleDescriptions.length; i++) {
        if (visibleDescriptions[i] == null) {
            visibleDescriptions[i] = divid;
            return;
        }
    }
}
function removeFromVisisble(divid) {
    for(var i=0; i < visibleDescriptions.length; i++) {
        if (visibleDescriptions[i] != null && visibleDescriptions[i] == divid) {
            visibleDescriptions[i] = null;
            return;
        }
    }
}
function createDummiApplet(create) {
    if (create && BrowserDetect.browser == "Explorer") {
        var applet = document.createElement("applet");
        applet.id = "indexfinder";
        applet.code = "IndexFinder.class";
        applet.height = 10;
        applet.width = 10;
        document.body.appendChild(applet);
    }
}
function reset(inputid, comboid1, comboid2) {
    var input = document.getElementById(inputid);
    if (input != null) input.value = "";
    var combo = getComboById(comboid1);
    if (combo != null) {
        var comboinput = document.getElementById(getTDId(combo.id));
        if (comboinput != null) {
            comboinput.innerHTML = combo.firstitem;
        }
    }
    combo = getComboById(comboid2);
    if (combo != null) {
        var comboinput = document.getElementById(getTDId(combo.id));
        if (comboinput != null) {
            comboinput.innerHTML = combo.firstitem;
        }
    }
}
function setBGColor(combo, bgColor) {
    if (combo != null) {
        var td = document.getElementById(getTDId(combo.id));
        if (td != null) {
            td.style.backgroundColor = bgColor;
        }
    }
}
//##########################################
// Ranklist scroller
//##########################################
var breakText = "\n";
if (BrowserDetect.browser == "Explorer") {
    breakText = "\r";
} else if (BrowserDetect.browser == "Firefox" && BrowserDetect.version < "2.0") {
    breakText = "\r\n";
}
var allLimiters = new Array();
function getLimiterById(id) {
    for (var i=0; i < allLimiters.length; i++) {
        if (allLimiters[i].id == id) return allLimiters[i];
    }
    return null;
}
function RankListLimiter(ranklistcount, quantityText) {
    this.ranklistcount = ranklistcount;
    this.limits = new Array();
    this.limitcount = 0;
    this.listscroller = null;
    this.id = allLimiters.length;
    allLimiters[this.id] = this;
    this.listscroller = null;
    this.tablerowid = null;
    this.showalltext = null;
    this.quantityText = quantityText;

    this.setListScroller = function(listscroller) {
        this.listscroller = listscroller;
    }
    this.addlimit = function(limit) {
        this.limits[this.limitcount] = limit;
        if (this.limitcount == 0) this.currentLimit = limit;
        this.limitcount++;
    }
    this.getlowlimit = function() {
        if (this.limitcount > 0) {
            return this.limits[0];
        }
    }
    this.changeCurrentLimit = function(newlimit) {
        var tablerow = document.getElementById(this.tablerowid);
        if (this.currentLimit != newlimit && tablerow != null) {
            var tablerowchildren = this.listscroller.getElementChildren(tablerow, "td");
            //if (this.limits.length == tablerowchildren.length-3) {
                // first remove all limits
                for (var i=1; i < tablerowchildren.length; i++) { // first child is a title as "nach Produktkategorie:"
                    tablerow.removeChild(tablerowchildren[i]);
                }
                this.listscroller.removeTrailingNodesExcept(tablerow, "td");
                // insert new children
                this.currentLimit = newlimit;
                this.insertRanklistLimits(this.tablerowid, this.showalltext);
            //}
        }
    }
    this.insertRanklistLimits = function(tablerowid, showalltext) {
        var innerhtml = undefined;
        var tdclass;
        var isLimitSelected = false;
        if (this.ranklistcount > this.getlowlimit()) {
            if (this.tablerowid == null) {
                this.tablerowid = tablerowid;
                this.showalltext = showalltext;
            }
            for (var i=0; i < this.limitcount; i++) {
                var limit = this.limits[i];
                if (this.ranklistcount > limit) {
                    if (limit == this.currentLimit) {
                        innerhtml = limit.toString();
                        tdclass = "rlims"
                        isLimitSelected = true;
                    } else {
                        innerhtml = "<a href=\"javascript:changeLimit("+limit+","+this.id+");\">"+limit+"</a>";
                        tdclass = "rlim";
                    }
                }
                if (innerhtml) {
                    var tr = document.getElementById(tablerowid);
                    if (tablerowid != null && tablerowid != "undefined") {
                        if (i==0) { // show text "Quantity:"
                            var td = document.createElement("td");
                            td.setAttribute("class", "rlim_title");
                            td.innerHTML = this.quantityText + ":";
                            td.className = "rlim_title";
                            tr.appendChild(td);
                        }
                        var td = document.createElement("td");
                        td.setAttribute("class", tdclass);
                        td.innerHTML = innerhtml;
                        td.className = tdclass;
                        tr.appendChild(td);
                    }
                }
                innerhtml = undefined;
            }
            if (isLimitSelected) {
                innerhtml = "<a href=\"javascript:changeLimit("+(-1)+","+this.id+");\">"+showalltext+"</a>";
                tdclass = "rlim";
            } else {
                innerhtml = showalltext;
                tdclass = "rlims";
                this.currentLimit = -1;
            }
            var tr = document.getElementById(tablerowid);
            if (tablerowid != null && tablerowid != "undefined") {
                var td = document.createElement("td");
                td.setAttribute("class", tdclass);
                td.innerHTML = innerhtml;
                td.className = tdclass;
                tr.appendChild(td);
            }
        }
    }
}
function changeLimit(newlimit, limiterId) {
    var limiter = getLimiterById(limiterId);
    if (limiter != null) {
        var scroller = limiter.listscroller;
        if (scroller != null) {
            scroller.changeCurrentLimit(newlimit);
        }
    }
}
function ListScroller(listLimiter, leftDivId, rightDivId, tdid, scrollLeftId, scrollRightId) {
    this.listLimiter = listLimiter;
    this.startIndex = 0;
    this.leftDivId = leftDivId;
    this.rightDivId = rightDivId;
    this.tdid = tdid;
    this.scrollLeftId = scrollLeftId;
    this.scrollRightId = scrollRightId;
    this.selectedLetter = null;
    this.letterSelectorId = null;

    this.changeCurrentLimit = function(newLimit) {
        var oldLimit = this.listLimiter.currentLimit;
        if (oldLimit < 0) oldLimit = Number.MAX_VALUE;
        var leftDiv = document.getElementById(this.leftDivId);
        var rightDiv = document.getElementById(this.rightDivId);
        var td = document.getElementById(this.tdid);
        var leftdivchildren = this.getElementChildren(leftDiv,"a");
        var rightdivchildren = this.getElementChildren(rightDiv,"a");
        var tdchildren = this.getElementChildren(td,"a");
        if (leftDiv != null && rightDiv != null && td != null) {
            this.listLimiter.changeCurrentLimit(newLimit);
            this.showLetterSelector(newLimit > 0 && leftdivchildren.length + rightdivchildren.length + tdchildren.length > newLimit * 2);
            if (newLimit == -1) { // display all qualifiers
                // insert all children from the left div
                var currentFirstChild = td.firstChild;
                for (var i=0; i < leftdivchildren.length; i++) {
                    td.insertBefore(document.createTextNode(breakText), currentFirstChild);
                    td.insertBefore(leftdivchildren[i], currentFirstChild);
                }
                // insert all children from the right div
                for (var i=0; i < rightdivchildren.length; i++) {
                    td.appendChild(rightdivchildren[i]);
                    td.appendChild(document.createTextNode(breakText));
                }
                // hide scroller arrows
                this.showScrollerArrow(scrollLeftId);
                this.showScrollerArrow(scrollRightId);
            } else if (newLimit < oldLimit) { // reduce limit
                // remove part of qualifiers
                for (var i=newLimit; i < tdchildren.length; i++) {
                    rightDiv.appendChild(tdchildren[i]);
                }
                this.enableScrollerArrow(scrollRightId, true, true);
                this.enableScrollerArrow(scrollLeftId, leftdivchildren.length > 0, false);
            } else { // increase limit
                if (tdchildren.length + rightdivchildren.length >= newLimit) {
                    // add children only from right div
                    for (var i=0; i < newLimit - tdchildren.length; i++) {
                        td.appendChild(rightdivchildren[i]);
                        td.appendChild(document.createTextNode(breakText));
                    }
                } else {
                    // insert children from the left div and add children from the right div
                    for (var i=0; i < rightdivchildren.length; i++) {
                        td.appendChild(rightdivchildren[i]);
                        td.appendChild(document.createTextNode(breakText));
                    }
                    var insertCount = newLimit - (tdchildren.length + rightdivchildren.length);
                    for (var i=0; i < insertCount; i++) {
                        td.insertBefore(document.createTextNode(breakText), td.firstChild);
                        td.insertBefore(leftdivchildren[leftdivchildren.length-i-1], td.firstChild);
                    }
                }
                this.enableScrollerArrow(scrollRightId, this.getElementChildren(rightDiv,"a").length > 0, true);
                this.enableScrollerArrow(scrollLeftId, this.getElementChildren(leftDiv,"a").length > 0, false);
            }
        }
    }
    this.setLetterSelector = function(id) {
        this.letterSelectorId = id;
    }
    this.showLetterSelector = function(show) {
        if (this.letterSelectorId != null) {
            var element = document.getElementById(this.letterSelectorId);
            if (element != null) {
                this.resetLetterSelector();
                element.style.display = (show) ? "block" : "none"; 
            }
        }
    }
    this.scrollTo = function(letter) {
        if (this.selectedLetter == null || letter != this.selectedLetter) {
            this.selectLetter(this.selectedLetter, false);
            var td = document.getElementById(this.tdid);
            var leftdiv = document.getElementById(this.leftDivId);
            var rightdiv = document.getElementById(this.rightDivId);
            if (td != null && leftdiv != null && rightdiv != null) {
                var leftdivchildren = this.getElementChildren(leftdiv,"a");
                var rightdivchildren = this.getElementChildren(rightdiv,"a");
                var tdchildren = this.getElementChildren(td,"a");
                var index = this.findIndex(rightdivchildren, letter);
                if (index > -1) {
                    this.scrollRight(tdchildren.length + index);
                } else {
                    index = this.findIndex(leftdivchildren, letter);
                    if (index > -1) {
                        this.scrollLeft(leftdivchildren.length - index);
                    } else {
                        index = this.findIndex(tdchildren, letter);
                        if (index > -1) {
                            this.scrollRight(index);
                        }
                    }
                }
            }
        }
        this.selectedLetter = letter;
        this.selectLetter(letter, true);
    }
    this.findIndex = function(children,letter) {
        var index = -1;
        if (children.length > 0 && children[0].innerHTML.substr(0,1) <= letter && children[children.length-1].innerHTML.substr(0,1) >= letter) {
            for (var i=0; i < children.length; i++) {
                if (children[i].innerHTML.substr(0,1) == letter) {
                    index = i;
                    break;
                }
            }
        }
        return index;
    }
    this.resetLetterSelector = function() {
        if (this.selectedLetter != null) {
            this.selectLetter(this.selectedLetter, false);
        }
    }
    this.selectLetter = function(letter, select){
        if (letter != null) {
            var letterTD = document.getElementById(this.letterSelectorId+letter);
            if (letterTD != null) {
                letterTD.setAttribute("class", select? "let_s" : "let_us");
                letterTD.className = select? "let_s" : "let_us";
            }
        }
    }
    this.scrollLeft = function(movecount) {
        if (this.listLimiter != null && this.listLimiter != "undefined") {
            this.selectLetter(this.selectedLetter, false);
            var td = document.getElementById(this.tdid);
            var leftdiv = document.getElementById(this.leftDivId);
            var rightdiv = document.getElementById(this.rightDivId);
            if (td != null && leftdiv != null && rightdiv != null) {
                var leftdivchildren = this.getElementChildren(leftdiv,"a");
                var rightdivchildren = this.getElementChildren(rightdiv,"a");
                var tdchildren = this.getElementChildren(td,"a");
                if (leftdivchildren.length > 0 && tdchildren.length > 0) {
                    var childToMoveCount = movecount;
                    if (childToMoveCount == "undefined" || childToMoveCount == null || childToMoveCount == undefined) childToMoveCount = listLimiter.currentLimit;
                    if (leftdivchildren.length < childToMoveCount) {
                        childToMoveCount = leftdivchildren.length;
                    }
                    this.enableScrollerArrow(scrollRightId, true, true);
                    var currentFirstChild = null;
                    for (var i=0; i < childToMoveCount; i++) {
                        td.insertBefore(document.createTextNode(breakText), td.firstChild);
                        td.insertBefore(leftdivchildren[leftdivchildren.length-i-1],td.firstChild);
                        if (rightdivchildren.length == 0 && currentFirstChild == null) {
                            rightdiv.appendChild(tdchildren[tdchildren.length-i-1]);
                            currentFirstChild = tdchildren[tdchildren.length-i-1];
                        } else {
                            if (tdchildren.length > i) rightdiv.insertBefore(tdchildren[tdchildren.length-i-1], rightdiv.firstChild);
                            else rightdiv.insertBefore(leftdivchildren[leftdivchildren.length-i+tdchildren.length-1], rightdiv.firstChild); 
                        }
                    }
                    this.removeTrailingNodesExcept(td, "a");
                    if (leftdivchildren.length - childToMoveCount == 0) {
                        this.enableScrollerArrow(scrollLeftId, false, false);
                    }
                }
            }
        }
    }
    this.scrollRight = function(movecount) {
        if (this.listLimiter != null && this.listLimiter != "undefined") {
            this.selectLetter(this.selectedLetter, false);
            var td = document.getElementById(this.tdid);
            var leftdiv = document.getElementById(this.leftDivId);
            var rightdiv = document.getElementById(this.rightDivId);
            if (td != null && leftdiv != null && rightdiv != null) {
                var rightdivchildren = this.getElementChildren(rightdiv,"a");
                var tdchildren = this.getElementChildren(td,"a");
                if (rightdivchildren.length > 0 && tdchildren.length > 0) {
                    var childToMoveCount = movecount;
                    if (childToMoveCount == "undefined" || childToMoveCount == null || childToMoveCount == undefined) childToMoveCount = listLimiter.currentLimit;
                    if (rightdivchildren.length < childToMoveCount) {
                        childToMoveCount = rightdivchildren.length;
                    }
                    this.enableScrollerArrow(scrollLeftId, true, false);
                    for (var i=0; i < childToMoveCount; i++) {
                        if (tdchildren.length > i) leftdiv.appendChild(tdchildren[i]);
                        else {
                            leftdiv.appendChild(rightdivchildren[i-tdchildren.length]);    
                        }
                        td.appendChild(rightdivchildren[i]);
                        td.appendChild(document.createTextNode(breakText));
                    }
                    this.removeLeadingNodesBefore(td, "a");
                    if (rightdivchildren.length - childToMoveCount == 0) {
                        this.enableScrollerArrow(scrollRightId, false, true);
                    }
                }
            }
        }
    }
    this.enableScrollerArrow = function(scrollId, enable, right) {
        var scrollArrow = document.getElementById(scrollId);
        if (scrollArrow != null) {
            if (scrollArrow.style.display == "none") {
                this.showScrollerArrow(scrollId, true);
            }
            var cl = (enable) ? (right ? "rlscrarr_right" : "rlscrarr_left") : (right ? "rlscrarrd_right" : "rlscrarrd_left")
            scrollArrow.setAttribute("class", cl);
            scrollArrow.className = cl;
        }
    }
    this.showScrollerArrow = function(scrollId, show) {
        var scrollArrow = document.getElementById(scrollId);
        if (scrollArrow != null) {
            scrollArrow.style.display = (show) ? "" : "none";
        }
    }
    this.removeLeadingNodesBefore = function(element, tagname) {
        var allchildren = element.childNodes;
        for (var i=0; i<allchildren.length; i++) {
            try {
                if (allchildren[0].tagName.toLowerCase() == tagname) {
                    return;
                }
            } catch (e) {
                element.removeChild(allchildren[0]);
            }
        }

    }
    this.removeTrailingNodesExcept = function(element, tagname) {
        var allchildren = element.childNodes;
        for (var i=allchildren.length-1; i>=0; i--) {
            try {
                if (allchildren[allchildren.length-1].tagName.toLowerCase() == tagname) {
                    return;
                }
            } catch (e) {
                element.removeChild(allchildren[allchildren.length-1]);
            }
        }

    }
    this.getElementChildren = function(element, tagname) {
        var children = new Array();
        var childcount = 0;
        var allchildren = element.childNodes;
        for (var i=0; i<allchildren.length; i++) {
            try {
                if (allchildren[i].tagName.toLowerCase() == tagname) {
                    children[childcount++] = allchildren[i];
                }
            } catch (e) {};
        }
        return children;
    }
}
var maxDisplayPages = 10;
function ProfilePageScroller(profilecount, startindex, currentlimit, tablerowid, pagestext, quantitytext, requestStr, startindexparam, limitparam) {
    this.profilecount = profilecount;
    this.tablerowid = tablerowid;
    this.limits = new Array();
    this.limitcount = 0;
    this.pagestext = pagestext;
    this.currentlimit = currentlimit;
    this.quantitytext = quantitytext;
    this.startindex = startindex;
    this.currentpage = Math.round(startindex/currentlimit);
    if (startindex > 1 && startindex < currentlimit && this.currentpage == 0) {
        this.currentpage++;
    }
    this.addLimit = function(limit) {
        this.limits[this.limitcount++] = limit;
    }
    this.getStartIndex = function(pagenumber) {
        var startindex = this.startindex + (pagenumber - this.currentpage) * this.currentlimit;
        if (startindex < 0) {
            startindex = 1;
        }
        return startindex;
    }
    this.insertPages = function() {
        var innerhtml = undefined;
        var tdclass = "";
        var tr = document.getElementById(this.tablerowid);
        if (this.profilecount > this.currentlimit && tr != null) {
            var pagecount = Math.round((this.profilecount/this.currentlimit)+0.499999999);
            if (pagecount > 1) {
                var pagearray = this.getDisplayPages(pagecount);
                var td = document.createElement("td");
                td.setAttribute("class", "rlim_title");
                td.innerHTML = this.pagestext + ":";
                td.className = "rlim_title";
                tr.appendChild(td);
                if (pagearray[0] > 0) {
                    td = document.createElement("td");
                    td.setAttribute("class", "rlim");
                    td.className = "rlim";
                    td.innerHTML = "<a href=\""+((requestStr.indexOf('?')!= -1)?requestStr+'&':requestStr+'?')+startindexparam+"=" + this.getStartIndex(this.currentpage-1) + '&' + limitparam + "=" + this.getLimitIndex() + "\"><<</a>";
                    tr.appendChild(td);
                }
                for (var i=0; i < pagearray.length; i++) {
                    td = document.createElement("td");
                    if (this.currentpage == pagearray[i]) {
                        innerhtml = (pagearray[i]+1).toString();
                        tdclass = "rlims"
                    } else {
                        innerhtml = "<a href=\""+((requestStr.indexOf('?')!= -1)?requestStr+'&':requestStr+'?')+startindexparam+"=" + this.getStartIndex(pagearray[i]) + '&' + limitparam + "=" + this.getLimitIndex() + "\">"+(pagearray[i]+1)+"</a>";
                        tdclass = "rlim";
                    }
                    td.setAttribute("class", tdclass);
                    td.className = tdclass;
                    td.innerHTML = innerhtml;
                    tr.appendChild(td);
                }
                if (pagearray[pagearray.length-1] < pagecount-1) {
                    td = document.createElement("td");
                    td.setAttribute("class", "rlim");
                    td.className = "rlim";
                    td.innerHTML = "<a href=\""+((requestStr.indexOf('?')!= -1)?requestStr+'&':requestStr+'?')+startindexparam+"=" + this.getStartIndex(this.currentpage+1) + '&' + limitparam + "=" + this.getLimitIndex() + "\">>></a>";
                    tr.appendChild(td);
                }
                if (pagearray.length > 0) {
                    td = document.createElement("td");
                    td.style.width="100%";
                    td.innerHTML = "&nbsp;";
                    tr.appendChild(td);
                }
                this.insertLimits(tr);
            }
        }
    }
    this.getLimitIndex = function() {
        for (var i=0; i < this.limits.length; i++) {
            if (this.currentlimit == this.limits[i]) return i;
        }
        return 0;
    }
    this.insertLimits = function(tr) {
        if(this.limitcount > 2 && this.profilecount > this.limits[1]) {
            var td = document.createElement("td");
            td.setAttribute("class", "rlim_title");
            td.innerHTML = this.quantitytext + ":";
            td.className = "rlim_title";
            td.style.width = "100%";
            td.style.textAlign = "right";
            tr.appendChild(td);
            for (var i=0; i < this.limitcount; i++) {
                td = document.createElement("td");
                var tdclass;
                var innerhtml;
                if (this.limits[i] == this.currentlimit) {
                    tdclass = "rlims"
                    innerhtml = this.currentlimit;
                } else {
                    tdclass = "rlim"
                    innerhtml = "<a href=\""+((requestStr.indexOf('?')!= -1)?requestStr+'&':requestStr+'?')+startindexparam+"=" + this.startindex + '&' + limitparam + "=" + i + "\">"+(this.limits[i])+"</a>";
                }
                td.setAttribute("class", tdclass);
                td.className = tdclass;
                td.innerHTML = innerhtml;
                tr.appendChild(td);
            }
        }
    }
    this.getDisplayPages = function(pagecount) {
        var pagearray;
        if (pagecount > maxDisplayPages) {
            pagearray = new Array(maxDisplayPages);
            var startpage = this.currentpage - Math.round(maxDisplayPages/2 - 0.499999999);
            if (startpage < 0) startpage = 0;
            else if (startpage + maxDisplayPages > pagecount) startpage -= startpage + maxDisplayPages - pagecount;
            var arrayindex = 0;
            for (var i=startpage; i < (maxDisplayPages + startpage); i++) {
                pagearray[arrayindex++] = i;
            }
        } else {
            pagearray = new Array(pagecount);
            for (var i=0; i < pagecount; i++) {
                pagearray[i] = i;
            }
        }
        return pagearray;
    }
}

function switchNameAttribute(checked, varId, value){
    var input = document.getElementById(varId);
    if (input != null) {
        if (checked) {
            input.setAttribute("name", value)
        } else {
            input.removeAttribute("name");
        }
    }
}
//##########################################
// Login
//##########################################
var nexttitle = null;
var nextimage = null;
function switchLoginMode(formname, anchorid, imgid, title, image) {
    var form = document.getElementsByName(formname);
    var a = document.getElementById(anchorid);
    var img = document.getElementById(imgid);
    if (form != null && form[0] && a != null && img != null) {
        var isSSL = form[0].action.indexOf("https:") >= 0;
        form[0].action = (isSSL) ? form[0].action.replace("https:","http:") : form[0].action.replace("http:","https:");
        if (nexttitle == null && nextimage == null) {
            nexttitle = a.title;
            nextimage = img.src;
            a.title = title;
            img.src = image;
        } else {
            var tmptitle = a.title;
            var tmpimage = img.src;
            a.title = nexttitle;
            img.src = nextimage;
            nexttitle = tmptitle;
            nextimage = tmpimage;
        }
    }
}
//##########################################
// User
//##########################################
function setSSLProtocol(anchorName) {
    var anchors = document.getElementsByName(anchorName);
    if (anchors != null && anchorName != "undefined") {
        for (var i=0; i < anchors.length; i++) {
            if (anchors[i].tagName.toLowerCase() == 'a') {
                anchors[i].href = anchors[i].href.replace("http:","https:");
            }
        }
    }
}
var fieldIndex = 0;
var inputFields = null;
var errorColor = "#FEA2A2";
function inputField(id, initialtext, maincolor, initialcolor, passwordId, value, check) {
    this.id = id;
    this.initialtext = initialtext;
    this.maincolor = maincolor;
    this.initialcolor = initialcolor;
    this.input = document.getElementById(this.id);
    this.blockFocus = false;
    this.value = value;
    this.check = (check != "undefined" && check != undefined) ? check : true;
    if (this.input != null) this.input.value = "";
    if (passwordId != null && passwordId != undefined && passwordId != "undefined") {
        this.password = document.getElementById(passwordId);
    } else {
        this.password = null;
    }
    addInputField(this);
    this.hideInitialText = function() {
        var strArray = [this.initialtext];
        if (this.input != null && this.input.value == this.initialtext) {
            if (this.password == null) {
                this.input.style.color = maincolor;
                this.input.parentNode.style.backgroundColor = "white";
                this.input.style.backgroundColor = "white";
                this.input.value = "";
                createInputHelperDiv(this.input.parentNode, this.id+"ih", strArray);
            } else if (this.password.style.display == "none") {
                this.input.style.display = "none";
                this.password.style.display = "block";
                this.password.parentNode.style.backgroundColor = "white";
                this.input.style.backgroundColor = "white";
                this.password.style.backgroundColor = "white";
                this.blockFocus = true;
                this.password.focus();
                this.password.select();
                createInputHelperDiv(this.password.parentNode, this.id+"ih", strArray);
            }
        }
    }
    this.restoreInitials = function() {
        if (!this.blockFocus) {
            if (this.input != null && this.input.value == "") {
                this.input.style.color = initialcolor;
                this.input.value = initialtext;
                destroyInputHelperDiv(this.id + "ih");
            }
            if (this.password != null && this.password.value == "") {
                this.password.style.display = "none"
                this.input.style.display = "table-cell";
                destroyInputHelperDiv(this.id + "ih");
            }
        } else {
            this.blockFocus = false;
        }
    }
    this.checkInput = function() {
        if (this.input != null && this.check) {
            if (this.input.style.display != "none") {
                if (this.input.value == this.initialtext || this.input.value == "") {
                    setInputBG(this.input.id, errorColor);
                    return false;
                }
            } else if (this.password != null && this.password.value == "") {
                setInputBG(this.password.id, errorColor);
                return false;
            }
        } else if (this.input != null && this.input.value == this.initialtext) {
            this.input.removeAttribute("name");    
        }
        return true;
    }
    this.setValue = function() {
        if (this.value != null && this.value != "null" && this.value != undefined && this.value != "undefined") {
            this.hideInitialText();
            this.input.value = this.value;
        }
    }
    this.restoreInitials();
}
function getInputFieldById(inputId) {
    if (inputFields != null) {
        for (var i=0; i < inputFields.length; i++) {
            if (inputFields[i].id == inputId) return inputFields[i];
        }
    }
    return null;
}
function setFormValues() {
    if (inputFields != null) {
        for (var i=0; i < inputFields.length; i++) {
            inputFields[i].setValue();
        }
    }
}
function addInputField(inputfield) {
    var tmparray = inputFields;
    inputFields = new Array(fieldIndex+1);
    inputFields[fieldIndex++] = inputfield;
    if (tmparray != null) {
        for(var i=0; i < tmparray.length; i++) {
            inputFields[i] = tmparray[i];
        }
    }
}
function changeProfileType(formname,id1,id2,id3,id4,id5,id6,actionname,actionvalue) {
    var element = document.getElementById(id1);
    if (element != null) element.removeAttribute("name");
    element = document.getElementById(id2);
    if (element != null) element.removeAttribute("name");
    element = document.getElementById(id3);
    if (element != null) element.removeAttribute("name");
    element = document.getElementById(id4);
    if (element != null) element.removeAttribute("name");
    element = document.getElementById(id5);
    if (element != null) element.removeAttribute("name");
    element = document.getElementById(id6);
    if (element != null) element.removeAttribute("name");
    var actionfield = document.getElementsByName(actionname);
    if (actionfield && actionfield.length > 0) actionfield[0].value = actionvalue; 
    var form = document.getElementsByName(formname);
    if (form.length > 0) form[0].submit();
}
function submitRegistration(form, rbName, chbId1, cbxId1, cbxId2, combo, slaveinput) {
    var submit = true;
    if (inputFields != null) {
        for (var i=0; i < inputFields.length; i++) {
            submit = inputFields[i].checkInput() && submit;
        }
    }
    var radioButtons = document.getElementsByName(rbName);
    if (radioButtons != null && radioButtons.length > 0) {
        var isChecked = true;
        for(var i=0; i < radioButtons.length; i++) {
            isChecked = radioButtons[i].checked;
            if (isChecked) break;
        }
        if (!isChecked) {
            submit = false;
            setTDBackground(rbName,errorColor);
        }
    }
    var checkBox = document.getElementById(chbId1);
    if (checkBox != null && !checkBox.checked) {
        submit = false;
        setTDBackground(chbId1, errorColor);
    }
    var comboTD = document.getElementById(getTDId(combo.id));
    if (comboTD != null) {
        var isSelected = !isDefaultRanglist(combo, removeHTMLTags(comboTD.innerHTML));
        if (!isSelected && slaveinput != null) {
            isSelected = slaveinput.checkInput();
            if (!isSelected) {
                submit = false;
                setBGColor(combo, errorColor);
                var element = document.getElementById(slaveinput.id);
                if (element != null && element.parentNode) {
                    if (element.parentNode.style.display == "none") element.parentNode.style.display = "block";
                }
                slaveinput.checkInput();
            }
        }
    }
    if (submit) {
        updateHiddenField(cbxId1);
        updateHiddenField(cbxId2);
        encodeFormInputs(form, true);
        form.submit();
        encodeFormInputs(form, false);
    }
}
function resetFormInput(combo1,combo2) {
    if (inputFields != null) {
        for (var i=0; i < inputFields.length; i++) {
            inputFields[i].input.value = "";
            inputFields[i].restoreInitials();
        }
    }
    if (combo1) {
        if (combo1.ondeselect != null) eval(combo1.ondeselect); // deselect
        document.getElementById(getTDId(combo1.id)).innerHTML = removeHTMLTags(combo1.data[0]);
    }
    if (combo2) {
        if (combo2.ondeselect != null) eval(combo2.ondeselect); // deselect
        document.getElementById(getTDId(combo2.id)).innerHTML = removeHTMLTags(combo2.data[0]);
    }
}
function submitInsertProfile(form, combo1, combo2, slaveinput1, slaveinput2, waitprofile, waitproposal) {
    var submit = true;
    var insertProfile = true;
    if (inputFields != null) {
        for (var i=0; i < inputFields.length; i++) {
            submit = inputFields[i].checkInput() && submit;
        }
    }
    if (combo1 && combo1.checkInput) { // check input if it's necessary
        var comboTD = document.getElementById(getTDId(combo1.id));
        var isSelected = false;
        if (comboTD != null) {
            isSelected = !isDefaultRanglist(combo1, removeHTMLTags(comboTD.innerHTML));
            if (!isSelected && slaveinput1 != "undefined") {
                insertProfile = false;
                slaveinput1.check = true;
                isSelected = slaveinput1.checkInput();
                slaveinput2.check = false;
                if (!isSelected) {
                    submit = false;
                    setBGColor(combo1, errorColor);
                    var element = document.getElementById(slaveinput1.id);
                    if (element != null && element.parentNode) {
                        if (element.parentNode.style.display == "none") element.parentNode.style.display = "block";
                    }
                }
            } else {
                submit = submit && isSelected;
                if (slaveinput1 != "undefined" && document.getElementById(slaveinput1.id)) document.getElementById(slaveinput1.id).removeAttribute("name");
                else if (!isSelected) setBGColor(combo1, errorColor);
            }
        }
    }
    if (combo2 && combo2.checkInput) { // check input if it's necessary
        var comboTD = document.getElementById(getTDId(combo2.id));
        var isSelected = false;
        if (comboTD != null) {
            isSelected = !isDefaultRanglist(combo2, removeHTMLTags(comboTD.innerHTML));
            if (!isSelected && slaveinput2 != "undefined") {
                insertProfile = false;
                slaveinput2.check = true;
                isSelected = slaveinput2.checkInput();
                slaveinput2.check = false;
                if (!isSelected) {
                    submit = false;
                    setBGColor(combo2, errorColor);
                    var element = document.getElementById(slaveinput2.id);
                    if (element != null && element.parentNode) {
                        if (element.parentNode.style.display == "none") element.parentNode.style.display = "block";
                    }
                }
            } else {
                submit = submit && isSelected;
                if (slaveinput2 != "undefined" && document.getElementById(slaveinput2.id)) document.getElementById(slaveinput2.id).removeAttribute("name");
                else if (!isSelected) setBGColor(combo2, errorColor);
            }
        }
    }
    if (submit) {
        if (combo1) updateHiddenField(getTDId(combo1.id));
        if (combo2) updateHiddenField(getTDId(combo2.id));
        var waitindicator = null;
        if (waitprofile!= null || waitproposal!= null) (insertProfile) ? document.getElementById(waitprofile) : document.getElementById(waitproposal);
        encodeFormInputs(form, true);
        form.submit();
        if (waitindicator != null) {
            waitindicator.style.display = "block";
        }
        encodeFormInputs(form, false);
    }
}
function encodeFormInputs(form, encode) {
    var inputFields = form.getElementsByTagName("input");
    for (var i=0; i < inputFields.length; i++) {
        if (inputFields[i].name && inputFields[i].name.length > 0 && inputFields[i].id) {
            if (encode) inputFields[i].value = encodeURIComponent(inputFields[i].value);
            else inputFields[i].value = decodeURIComponent(inputFields[i].value);
        }
    }
}
function updateHiddenField(tdId) {
    var combo = getComboById(getComboId(tdId));
    var comboTD = document.getElementById(tdId);
    if (combo != null && comboTD != null) {
        var isDefault = isDefaultRanglist(combo, removeHTMLTags(comboTD.innerHTML));
        var hiddenfield = document.getElementById(tdId + "hid");
        if (!isDefault) {
            if (hiddenfield != null) {
                hiddenfield.value = removeHTMLTags(removeHTMLTags(comboTD.innerHTML));
            }
        } else if (hiddenfield != null) {
            hiddenfield.removeAttribute("name");
        }
    }
}
function submitChanges(form, pwid1, pwid2, errorId1, errorId2) {
    var submit = true;
    if (inputFields != null) {
        for (var i=0; i < inputFields.length; i++) {
            submit = inputFields[i].checkInput() && submit;
        }
    }
    if (submit) {
        submit = checkPasswordIdentity(pwid1, pwid2, errorId1) && submit;
    }
    if (submit) {
        submit = checkPasswordStrength(pwid1, errorId2) && submit;
    }
    if (submit) form.submit();
}
function checkPasswordIdentity(pwid1,pwid2, errorId) {
    var input1 = document.getElementById(pwid1);
    var input2 = document.getElementById(pwid2);
    if (input1 != null && input2 != null) {
        var identical = input1.value == input2.value;
        if (!identical) showErrorMsg(errorId, true, pwid1, pwid2);
        return identical;
    }
    return true;
}
function showErrorMsg(errorId, show, inpid1, inpid2) {
    var errorMsg = document.getElementById(errorId);
    if (errorMsg != null) {
        errorMsg.style.display = show ? "" : "none";
    }
    if (inpid1) {
        var input = document.getElementById(inpid1);
        if (input != null) {
            input.parentNode.style.border = (show) ? "1px solid red" : "1px solid #909090";
        }
    }
    if (inpid2) {
        var input = document.getElementById(inpid2);
        if (input != null) {
            input.parentNode.style.border = (show) ? "1px solid red" : "1px solid #909090";
        }
    }
}
function checkPasswordStrength(pwdid, errorId) {
    var input = document.getElementById(pwdid);
    if (input != null) {
        if (input.value.length < 6) {
            showErrorMsg(errorId, true, pwdid);
            return false;
        }
    }
    return true;
}

function setTDBackground(id, bgcolor) {
    if (id) {
        var td = document.getElementById(id + "td");
        if (td != null) {
            td.style.backgroundColor = bgcolor;
        }
    }
}
function resetCheckAtribute(id) {
    var element = document.getElementById(id);
    if (element != null) {
        element.checked = false;
    } else {
        var elements = document.getElementsByName(id);
        if (elements != null && elements.length > 0) {
            for(var i=0; i < elements.length; i++) {
                elements[i].checked = false;
            }
        }
    }
}
function itemChanged(chbId, hiddId, selected) {
    var element = document.getElementById(chbId);
    var item = "";
    if (element != null) {
        item = selected ? element.innerHTML : "";
        element.style.color = (selected) ? "black" : "#808080";
    }
    element = document.getElementById(hiddId);
    if (element != null) {
        element.value = item;
    }
}
function switchProposal(proposalId) {
    var element = document.getElementById(proposalId);
    if (element != null) {
        var parent = element.parentNode;
        if (parent != null) {
            if (parent.style.display == "none") {
                parent.style.display = "table-cell";
            } else {
                parent.style.display = "none";
                if (inputFields != null) {
                    for (var i=0; i < inputFields.length; i++) {
                        if (inputFields[i].id == proposalId) {
                            element.value = ""; 
                            inputFields[i].restoreInitials();
                        }
                    }
                }
            }
        }
    }
}
function setInputBG(inputId,color){
    var element = document.getElementById(inputId);
    if (element != null) { element.style.backgroundColor = color;
        if (element.parentNode) {
            element.parentNode.style.backgroundColor = color;
        }
    }
}
var closeTimerId;
function getInfoPopupHTML(maintext,closetext, helppopup) {
    var html = "<table width=\"100%\"><tr><td><table width=\"100%\"><tr><td width=\"15px\" class='"+(helppopup?'hlphdr':'iphdr')+"'><img src=\"/images/"+ (helppopup?'help.png':'info.png')+"\"/></td><td width=\"100%\" class='"+(helppopup?'hlphdr':'iphdr')+"'><a onclick=\"hideInfoPopup()\">"+closetext+"</a></td></tr></table></td></tr>";
    html += "<tr><td class='"+(helppopup?'hlptxt':'iptxt')+"'>"+maintext+"</td></tr></table>"
    return html;
}
function createPopup(event, maintext, closetext, popupwidth, helppopup) {
    var scrollPosition = getScrollXY();
    clearTimeout(closeTimerId);
    removeInfoPopup("infopopup");
    var evt=(event) ? event : (window.event) ? window.event : null;
    var popupDiv = document.createElement("div");
    popupDiv.innerHTML = getInfoPopupHTML(maintext,closetext, helppopup);
    popupDiv.id = "infopopup";
    popupDiv.style.position = "absolute";
    popupDiv.style.visibility = "visible";
    popupDiv.style.filter = "alpha(opacity=0)"
    popupDiv.style.opacity ="0";
    popupDiv.style.display = "block";
    popupDiv.style.zIndex = "1000";
    popupDiv.style.border = helppopup ? "1px solid #F4A66A" : "1px solid #6FB8F0";
    popupDiv.style.backgroundColor = "white";
    popupDiv.style.top = (evt.clientY + scrollPosition[1]) + "px";
    var leftpos = evt.clientX + scrollPosition[0];
    if (leftpos + popupwidth + 4 > document.body.offsetWidth) {
        leftpos -= leftpos + popupwidth - document.body.offsetWidth + 4;
        if (!(BrowserDetect.browser=="Chrome" || BrowserDetect.browser=="Safari") && document.body.scrollHeight > document.body.offsetHeight) leftpos -= 20; //scroller width
    }
    popupDiv.style.left = leftpos + "px";
    popupDiv.style.width = popupwidth+"px";
    document.body.appendChild(popupDiv);
}
function showInfoPopup(event, maintext, closetext, popupwidth) {
    var elm = event;
    if (!window.event && (elm=document.getElementById(elm)) != null) {
        var pos = getElementPos(elm);
        var evt = document.createEvent("MouseEvents");
        evt.initMouseEvent("click", true, true, window, 0, 0, 0, (pos.x-document.documentElement.scrollLeft+elm.offsetWidth/2), (pos.y-document.documentElement.scrollTop+elm.offsetHeight/2), false, false, false, false, 0, null);
        event = evt;
    }
    createPopup(event, maintext, closetext, popupwidth, false);
    changeOpacity("infopopup", true, 500);
    closeTimerId = setTimeout("hideInfoPopup()",15000);
}
function showHelpPopup(event, maintext, closetext, popupwidth) {
    createPopup(event, maintext, closetext, popupwidth, true);
    changeOpacity("infopopup", true, 500);
    closeTimerId = setTimeout("hideInfoPopup()",60000);
}
function changeOpacityStyle(elementid, opacity) {
    var element = document.getElementById(elementid);
    if (element != null) {
            element.style.opacity = (opacity/10).toString();
            element.style.filter = "alpha(opacity="+(opacity*10)+")";
   }
            // switch on the ClearType for IE (it is not supported if the filter property has been set)
   if (opacity == 10) element.style.filter = "none";
}
function changeOpacity(elementid, show, interval) {
    var step = interval / 10;
    for(var i=1; i < 11; i++) {
        var opacity = show ? i : 10-i;
        setTimeout("changeOpacityStyle('"+elementid+"',"+opacity+")", step*i);
    }
}
function removeInfoPopup(popupid) {
    var popup = document.getElementById("infopopup");
    if (popup != null) {
        document.body.removeChild(popup);
    }
}
function hideInfoPopup() {
    changeOpacity("infopopup",false,500);
    setTimeout("removeInfoPopup('infopopup')",800);
}
function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
       scrOfY = window.pageYOffset;
       scrOfX = window.pageXOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
       scrOfY = document.body.scrollTop;
       scrOfX = document.body.scrollLeft;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
       //IE standards compliant mode
       scrOfY = document.documentElement.scrollTop;
       scrOfX = document.documentElement.scrollLeft;
    }
    return [ scrOfX, scrOfY ];
}
function switchDisplay(elementId) {
    var element = document.getElementById(elementId);
    if (element==null) return;
    if (element.style.display == 'none'){
        element.style.display = 'inline';
    } else {
        element.style.display = 'none';
    }
}
function toggle(prefix, elementId) {
    switchDisplay(prefix+elementId+"-more");
    switchDisplay(prefix+elementId+"-less");
}
function switchPrices(hidePattern,showPattern,count) {
    for (var i=1; i <= count; i++) {
        var element = document.getElementById(hidePattern+i);
        if (element != null) element.style.display = "none";
        element = document.getElementById(showPattern+i);
        if (element != null) element.style.display = "table-cell";
    }
}
function showBLZ(inputId, infoId, show) {
    var element = document.getElementById(inputId);
    if (element != null) element.style.display = show?"inline":"none";
    element = document.getElementById(infoId);
    if (element != null) element.style.display = show?"block":"none";
}
function showSelector(url) {
    while (url.indexOf("#sqt#") >= 0) url = url.replace("#sqt#","'");
    while (url.indexOf("&sqt;") >= 0) url = url.replace("&sqt;","'");
    while (url.indexOf("+") >= 0) url = url.replace("+","%2B");
    window.open(encodeURI(url), "", "width=450,height=680,left=200,top=200,dependent=yes,location=no,resizable=yes,scrollbars=1");
}
function replaceHref(id) {
    var anch = document.getElementById(id);
    if (anch != null) {
        anch.href = "javascript:showEditor('"+anch.href+"');"
    }
}
function showLoginInvitation(id, maintext, closetext, popupwidth) {
    var anch = document.getElementById(id);
    if (anch != null) {
        anch.removeAttribute("href");
        anch.style.cursor="pointer";
        anch.style.textDecoration="underline";
        if( anch.addEventListener ){
            anch.addEventListener('click', function(){showInfoPopup((BrowserDetect.browser=="Safari"||BrowserDetect.browser=="Chrome"||BrowserDetect.browser=="Opera")?null:anch.id, maintext, closetext, popupwidth)}, false);
        } else {
            anch.attachEvent('onclick', function(){showInfoPopup(null, maintext, closetext, popupwidth)});
        }
    }
}
function showEditor(url) {
    while (url.indexOf("#sqt#") >= 0) url = url.replace("#sqt#","'");
    while (url.indexOf("+") >= 0) url = url.replace("+","%2B");
    window.open(encodeURI(url), "", "width=450,height=550,left=200,top=200,dependent=yes,location=no,resizable=yes,scrollbars=0");
}
var TOP_EXT,TABLE_EXT,EXPAND_EXT,EXPANCHOR_EXT,EXPIMG_EXT,EXPTXT_EXT,EXPAND_TXT,COLLAPSE_TXT,EXPAND_IMG,COLLAPSE_IMG;
function initExpBox(top,table,expand,expanc,eimg,etxt,expmsg,collmsg,expimg,collimg){
    TOP_EXT=top;
    TABLE_EXT=table;
    EXPAND_EXT=expand;
    EXPANCHOR_EXT=expanc;
    EXPIMG_EXT=eimg;
    EXPTXT_EXT=etxt;
    EXPAND_TXT=expmsg;
    COLLAPSE_TXT=collmsg;
    EXPAND_IMG=expimg;
    COLLAPSE_IMG=collimg;
}
function expand(divid) {
    var topdiv = document.getElementById(divid + TOP_EXT);
    var currheight;
    if (topdiv != null) {
        currheight = topdiv.style.height;
        if (currheight != null && currheight.length > 0) {
            topdiv.style.height = "";
            var expimg = document.getElementById(divid+EXPIMG_EXT);
            if (expimg != null) expimg.src = expimg.src.replace(EXPAND_IMG,COLLAPSE_IMG);
            var exptxt = document.getElementById(divid+EXPTXT_EXT);
            if (exptxt != null) exptxt.innerHTML = "&nbsp;"+COLLAPSE_TXT;
            var expanchor = document.getElementById(divid+EXPANCHOR_EXT);
            if (expanchor != null) expanchor.href = "javascript:collapse('"+divid+"','"+currheight+"')";
        }
    }
}
function collapse(divid, height) {
    var topdiv = document.getElementById(divid + TOP_EXT);
    if (topdiv != null) {
        if ("" == topdiv.style.height) {
            topdiv.style.height = height;
            var expimg = document.getElementById(divid+EXPIMG_EXT);
            if (expimg != null) expimg.src = expimg.src.replace(COLLAPSE_IMG,EXPAND_IMG);
            var exptxt = document.getElementById(divid+EXPTXT_EXT);
            if (exptxt != null) exptxt.innerHTML = "&nbsp;"+EXPAND_TXT;
            var expanchor = document.getElementById(divid+EXPANCHOR_EXT);
            if (expanchor != null) expanchor.href = "javascript:expand('"+divid+"')";
        }
    }
}
function checkExpandableState(id, height) {
    var element = document.getElementById(id+TABLE_EXT);
    if (element != null && parseInt(element.clientHeight.toString()) > parseInt(height.toString())) {
        element = document.getElementById(id+EXPAND_EXT);
        if (element != null) element.style.display = "inline";
        element = document.getElementById(id+EXPAND_EXT+"no");
        if (element != null) element.style.display = "none";
    } else {
        element = document.getElementById(id+TOP_EXT);
        if (element != null) element.style.height = "";
        element = document.getElementById(id+TOP_EXT+"td");
        if (element != null) element.height = "";
        element = document.getElementById(id+EXPAND_EXT+"no");
        if (element != null) element.style.display = "inline";
        element = document.getElementById(id+EXPAND_EXT);
        if (element != null) element.style.display = "none";
    }
}
function setStartSiite(startSeite) {
    isStartSite = startSeite;
}
function setBoxesHeight(divid1, divid2, divid3) {
    var element1 = document.getElementById(divid1+"_tbl");
    var element2 = document.getElementById(divid2+"_tbl");
    var element3 = document.getElementById(divid3+"_tbl");
    var maxHeight = element1 != null ? element1.clientHeight : 0;
    if (element2 != null && element2.clientHeight > maxHeight) maxHeight = element2.clientHeight;
    if (element3 != null && element3.clientHeight > maxHeight) maxHeight = element3.clientHeight;
    if (element1 != null && element1.clientHeight > 0 && element1.clientHeight < maxHeight) {
        var anchor = document.getElementById((divid1+"a"));
        if (anchor != null && anchor.offsetParent) anchor.offsetParent.style.paddingTop = (maxHeight - element1.clientHeight+5) + "px";
        else element1.style.height = (maxHeight + (BrowserDetect.browser=="Firefox"||BrowserDetect.browser=="Opera"?0:-3)) + "px";
    }
    if (element2 != null && element2.clientHeight > 0 && element2.clientHeight < maxHeight) {
        var anchor = document.getElementById((divid2+"a"));
        if (anchor != null && anchor.offsetParent) anchor.offsetParent.style.paddingTop = (maxHeight - element2.clientHeight+5) + "px";
        else element2.style.height = (maxHeight + (BrowserDetect.browser=="Firefox"||BrowserDetect.browser=="Opera"?0:-3)) + "px";
    }
    if (element3 != null && element3.clientHeight > 0 && element3.clientHeight < maxHeight) {
        var anchor = document.getElementById((divid3+"a"));
        if (anchor != null && anchor.offsetParent) anchor.offsetParent.style.paddingTop = (maxHeight - element3.clientHeight+5) + "px";
        else element3.style.height = (maxHeight + (BrowserDetect.browser=="Firefox"||BrowserDetect.browser=="Opera"?0:-3)) + "px";
    }
}
function setElementHeight(fixedHeight, id) {
    var element = document.getElementById(id+"td");
    if (element != null) {
        var headerHeight = 27;
        var borderHeight = 0;
        element = document.getElementById(id+"_exp");
        if (element !=null && element.style.display == "none") {
            element = document.getElementById(id+"_expno");
            if (element != null) {
                borderHeight = 5;
                element = document.getElementById(id);
                if (element != null) element.style.height = (fixedHeight+headerHeight-1) + "px";
                element = document.getElementById(id+"_top");
                if (element != null) element.style.height = (fixedHeight+headerHeight-borderHeight-1) + "px";
                element = document.getElementById(id+"_toptd");
                if (element != null) element.style.height = (fixedHeight+headerHeight-borderHeight) + "px";
            }
        }
    }
}
function setFixedBoxesHeight(fixedHeight, tdid1, tdid2, tdid3) {
    setElementHeight(fixedHeight, tdid1);
    setElementHeight(fixedHeight, tdid2);
    setElementHeight(fixedHeight, tdid3);
}
function encodeInput(inputid) {
    var input=document.getElementById(inputid);
    if (input != null && input.value != "undefined" && input.value.length>0) input.value=encodeURIComponent(input.value)
}
function resizeBkgImage(mainTblId, bkgTblId, maxwidth) {
    var bTbl = document.getElementById(bkgTblId);
    var mtbl=document.getElementById(mainTblId);
    var cnt=document.getElementById("content");
    if (bTbl != null && document.body.offsetWidth > maxwidth) {
        if (bTbl != null) bTbl.style.width=document.body.offsetWidth+"px";
        if (mtbl != null) mtbl.style.width=maxwidth+"px";
        if (cnt != null) cnt.style.width=maxwidth+"px";
    } else {
        if (mtbl != null) mtbl.style.width = "100%";
        if (cnt != null) cnt.style.width = "100%";
    }
}
function setSearchSpace(anywhere, inputid) {
    searchAnywhere = anywhere;
    lastSuggestInput = "";
    lastInputValue = "";
}
function showRecommendations(url) {
    var popupWidth = 650;
    var popupHeight = 500;
    var width = screen.availWidth;
    var height = screen.availHeight;
    var posx = (width / 2) - (popupWidth / 2);
    var posy = (height / 2) - (popupHeight / 2);
    if (posx < 0) posx = 0;
    if (posy < 0) posy = 0;
    window.open(encodeURI(url), "", "width="+popupWidth+",height="+popupHeight+",left="+posx+",top="+posy+",dependent=yes,location=no,resizable=yes,scrollbars=0");
}
function showUserAsPopup(url) {
    window.open(encodeURI(url), "", "width=700,height=500,left=200,top=200,dependent=yes,location=no,resizable=yes,scrollbars=0");
}

function encodeHiddenInput(inputid) {
    var input=document.getElementById(inputid);
    var hiddenField = document.getElementById("hidden_"+inputid);
    if (input != null && input.value != "undefined" && input.value.length>0 && hiddenField != null) hiddenField.value=encodeURIComponent(input.value)
}
function initField(field, value, color) {
    if (field != null) {
        field.style.color = color;
        field.value = value;
    }
}
function fieldSelected(field, defaulttext, color) {
    if (field != null && defaulttext == field.value) {
        initField(field, "", color);
    }
}
function fieldDeselected(field, defaulttext, color) {
    if (field != null && field.value == "") {
        initField(field, defaulttext, color);
    }
}
