var inputForm = null;
var inputField = null;      
var suggBox = null;         
var suggVisible = false;
var xmlhttp = null;
var lastHighlightedId = -1;
var suggCount = -1;
var callcounter = 0;
var searchDelay = 250;      
var fixedwidth = -1;        // if -1, width is calculated automatically; can be set in the setup function
var normalfg = "black";
var normalbg = "white";
var highlightfg = "white";
var highlightbg = "#C4B04D";
var requestURL = "";        // URL to be called for the request. 

function clearSearchbox() {
   if (inputField.value == "Suchbegriff") inputField.value = "";
}

function aLive(message) {
   alert(message);
}

function doBlur(event) {
    if (!event && window.event) {
        event = window.event;
    }
    hideSuggBox();
}

function doFieldKeyDown(event) {
    if (!event && window.event) {
        event = window.event;
    }
    if (!xmlhttp) return;
    switch (event.keyCode) {
        case 37: {
            // left
            break;
        }
        case 39: {
            // right
            break;
        }
        case 40: {
            // down
            if (!suggVisible) {
                setTimeout("doSearch()", 10);
            } else
                if (suggCount > 0) {
                    if ((lastHighlightedId < suggCount - 1) || (lastHighlightedId == 'User')) {
                        if (lastHighlightedId == -1) {
                            selectRow('User');
                        }else if (lastHighlightedId == 'User') {
                            selectRow(0);
                        } else {
                            selectRow(lastHighlightedId + 1);
                        }
                        showSuggBox();
                    }
                    if (event.cancelBubble) event.cancelBubble();
                    break;
                }
        }
        case 38: {
            // up
            if (suggCount > 0) {
                if (lastHighlightedId >= 0) {
                    var rowIndex = lastHighlightedId - 1;
                    if (rowIndex < 0) {
                        selectRow('User');
                    } else {
                        selectRow(lastHighlightedId - 1);
                    }
                    showSuggBox();
                }
                if (event.cancelBubble) event.cancelBubble();
                break;
            }
        }
        case 33: {
            // PgUp
            if (suggVisible && (suggCount > 0)) {
                selectRow(0);
                if (event.cancelBubble) event.cancelBubble();
                break;
            }
        }
        case 34: {
            // PgDn
            if (suggVisible && (suggCount > 0)) {
                selectRow(suggCount - 1);
                if (event.cancelBubble) event.cancelBubble();
                break;
            }
        }
        case 35: {
            // End
            if (suggVisible && (suggCount > 0)) {
                selectRow(suggCount - 1);
                if (event.cancelBubble) event.cancelBubble();
                break;
            }
        }
        case 36: {
            // Home
            if (suggVisible && (suggCount > 0)) {
                selectRow(0);
                if (event.cancelBubble) event.cancelBubble();
                break;
            }
        }
        case 13: {
            // Enter
            if (suggVisible && (lastHighlightedId >= 0)) {
                hideSuggBox();
                var row = document.getElementById("suggRow" + lastHighlightedId);
                if (event.cancelBubble) event.cancelBubble();
                if (row) {
                    var fx = row.onmousedown;
                    fx();
                }
            }
            break;
        }
        case 27: {
            // Escape
            if (suggVisible) {
                selectRow(-1);
                hideSuggBox();
                if (event.cancelBubble) event.cancelBubble();
                // restore input value after a short time
                backupValue = inputField.value;
                setTimeout("inputField.value = backupValue", 180);
            }
            break;
        }
        default: {
            callSearch();
        }
    }
}


function getXMLHTTP() {
  var result = false;
  if(typeof XMLHttpRequest != "undefined") {
    result = new XMLHttpRequest();
  } else {
    try {
        result = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            result = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (ie) {}
    }
  }
  return result;
}

function getParentProps(elem, prop) {
    // returns the sum of the property "prop" along the offsetParent row of elem
    var result = 0;
    while (elem != null) {
        result += elem[prop];
        elem = elem.offsetParent;
    }
    return result;
}

function selectRow(row) {
    if ((lastHighlightedId > -1) || (lastHighlightedId == 'User')) {
        rowDiv = document.getElementById("suggRow" + lastHighlightedId);
        rowDiv.style.backgroundColor = normalbg;
        rowDiv.style.color = normalfg;
    }
    lastHighlightedId = row;
    rowDiv = document.getElementById("suggRow" + row);
    if (rowDiv) {
        rowDiv.style.backgroundColor = highlightbg;
        rowDiv.style.color = highlightfg;
    }
}

function mouseEnter(id) {
    selectRow(id);
}

function submitString(string, catid) {
    inputField.value = string;
    document.quick_find.mode.value = catid;
    inputForm.submit();
}

function setDivSize() {
    if (suggBox) {
            suggBox.style.top =
            getParentProps(inputField, "offsetTop") + inputField.offsetHeight + "px";
            suggBox.style.left = getParentProps(inputField, "offsetLeft") + "px";
            // suggBox.style.width = (fixedwidth < 0 ? inputField.offsetWidth : fixedwidth);
            suggBox.style.minWidth = (fixedwidth < 0 ? '40%' : fixedwidth);
            // if (is_ie) {
            //     suggBox.style.width = '45%';
            // }
    }
}

function fillDiv(astrings, bstrings, cstrings) {
    // user input
    var userInput = document.quick_find.keywords.value;
    // remove previous elements
    while (suggBox.hasChildNodes()) {
        suggBox.removeChild(suggBox.firstChild);
    }

    // create Row for user input
    iDiv = document.createElement("div");
    iDiv.onmouseover = new Function("omoUser", "mouseEnter('User')");
    iDiv.onmousedown = new Function("omdUser", "submitString('" + userInput.replace(/'/g, "\"") + "', 'Ihre Eingabe')");
    iDiv.id = "suggRowUser";
    iDiv.className = "suggUserRow";
    iDiv.style.cursor = "pointer";
    iDiv.innerHTML = "<div class='suggItem'><div class='suggProduct'><nobr>" + userInput + "&nbsp;&nbsp;</nobr></div><div class='suggCat'><nobr>Ihre Eingabe</nobr></div></div>";
    suggBox.appendChild(iDiv);

    // Textzeile mit Ueberschrift
    iDiv = document.createElement("div");
    iDiv.id = "suggRowHelp";
    iDiv.className = "suggRow";
    iDiv.style.cursor = "pointer";
    iDiv.innerHTML = "<div class='suggItem'><div class='suggProduct'><nobr><span style='color: #000000; font-weight: bold;'>Einige Vorschl&auml;ge zu Ihrem Suchbegriff:&nbsp;&nbsp;</span></nobr></div><div class='suggCat'>&nbsp;<nobr></nobr></div></div>";
    suggBox.appendChild(iDiv);

    // append suggests
    for (i = 0; i < astrings.length; i++) {
        iDiv = document.createElement("div");
        iDiv.onmouseover = new Function("omo" + i, "mouseEnter(" + i + ")");
        iDiv.onmousedown = new Function("omd" + i, "submitString('" + astrings[i].replace(/'/g, "\"") + "', " + cstrings[i] + ")");
        iDiv.id = "suggRow" + i;
        // jr
        /* iDiv.className = "suggRow";
        iDiv.style.cursor = "hand";
        iDiv.innerHTML = "<span class='suggItem'><nowrap>" +
            "<div class='suggProduct'>" + astrings[i] + "</div>" +
            "<div class='suggCat'>" + bstrings[i] +"</div>" +
            "</nowrap></span>"; */
        iDiv.className = "suggRow";
        iDiv.style.cursor = "pointer";
        iDiv.innerHTML = "<div class='suggItem'><div class='suggProduct'><nobr>" + astrings[i] + "&nbsp;&nbsp;</nobr></div><div class='suggCat'><nobr>" + bstrings[i] + "</nobr></div></div>";
        suggBox.appendChild(iDiv);
    }
    lastHighlightedId = -1;

    // Textzeile mit Hilfelink
    iDiv = document.createElement("div");
    iDiv.onmousedown = new Function("omdHelpLink", "document.location.href = '/service/suggest.htm'");
    iDiv.id = "suggRowLink";
    iDiv.className = "suggHelpRow";
    iDiv.style.cursor = "pointer";
    //iDiv.innerHTML = "<div class='suggItem'><div class='suggProduct'><nobr>&nbsp;&nbsp;</nobr></div></div>";
    suggBox.appendChild(iDiv);
}

function sendRPCDone(fr, is, astrings, bstrings, cstrings, pr) {
    suggCount = astrings.length;
    fillDiv(astrings, bstrings, cstrings);
    // no results?
    if (astrings.length == 0) {
        hideSuggBox();
        return;
    }
    showSuggBox();
}

function callSearch() {
    callcounter++;
    setTimeout("doSearch()", searchDelay);
}

function doSearch() {
    if (callcounter > 0)
        callcounter--;
    if (callcounter > 0) return;
    if (inputField.value.length < 2) {
        hideSuggBox();
        return;
    }
    if (!xmlhttp) return;
    // search running right now?
    if (xmlhttp.readyState != 0) {
        // cancel current search
        xmlhttp.abort();
    }
    xmlhttp.open("GET", requestURL + escape(inputField.value), true);
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.responseText) {
        if (xmlhttp.responseText.charAt(0) == "<") {
        } else {
          // The response text gets executed as javascript...
           try {
             eval(xmlhttp.responseText);
          } catch (e) {
            // error - probably due to special characters ('), try again after character substitution
            var txt = xmlhttp.responseText.replace(/\'/g, "''");
            try { 
                eval(txt);
            } catch (ie) {
                // still errors? don't display anything
                hideSuggBox();
            }
          }
        }
      }
    };
    xmlhttp.send(null);
}

function SetupAutoSuggest(request, input, width, nfg, nbg, hfg, hbg) {
    requestURL = request;
    inputForm = input.form;
    inputField = input;

    if (typeof width != "undefined") {
        fixedwidth = width;
    }
    if (typeof nfg != "undefined") normalfg = nfg;
    if (typeof nbg != "undefined") normalbg = nbg;
    if (typeof hfg != "undefined") highlightfg = hfg;
    if (typeof hbg != "undefined") highlightbg = hbg;

    xmlhttp = getXMLHTTP();
    if (!xmlhttp) {
        return;
    }

    if (typeof netscape != 'undefined' && typeof netscape.security !=
        'undefined') {
        try {

            netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
        }
        catch (e) {
//          alert('Error ' + e.message + ' occurred.');
        }
    }

    input.autocomplete = "off";
    input.onblur = doBlur;
    input.onkeydown = doFieldKeyDown;
    input.onmousedown = doBlur;
    input.onselect = doBlur;

    suggBox = document.createElement("div");
    suggBox.name = "suggBox";
    document.body.appendChild(suggBox);

    suggBox.className = "suggBox";
    suggBox.id = "suggBox";
    setDivSize();

    window.onresize = setDivSize;
}

function toggleSelectBox(displayStyle) {
    var selectBoxen = new Array('tpkat', 'herstellerfilter', 'preisfilter', 'shopfilter');
    for (var i = 0; i < selectBoxen.length; i++) {
        if (document.getElementById(selectBoxen[i]) && (is_ie)) {
            document.getElementById(selectBoxen[i]).style.visibility=displayStyle;
        }
    }
}

function showSuggBox() {
    productMaxSize = 0;
    categoryMaxSize = 0;
    es = document.getElementsByTagName('div');
    for (i = 0; i < es.length; i++) {
        if (es[i].className=="suggProduct") {
            tmp = es[i].childNodes[0].offsetWidth;
            if (tmp > productMaxSize) productMaxSize = tmp;
        }
        if (es[i].className=="suggCat") {
            tmp = es[i].childNodes[0].offsetWidth;
            if (tmp > categoryMaxSize) categoryMaxSize = tmp;
        }
    }
    boxwidth = productMaxSize+categoryMaxSize+40;
    suggBox.style.width = boxwidth+"px";
    es = document.getElementsByTagName('div');
    for (i = 0; i < es.length; i++) {
        if (es[i].className=="suggProduct") {
            es[i].style.width= productMaxSize +'px';
        }
        if (es[i].className=="suggCat") {
            es[i].style.width= categoryMaxSize +'px';
        }
    }

    document.getElementById("suggBox").style.visibility="visible";
    toggleSelectBox("hidden");
    suggVisible = true;
}

function hideSuggBox() {
    document.getElementById("suggBox").style.visibility="hidden";
    toggleSelectBox("visible");
    suggVisible = false;
}