var inputForm           = null;
var inputField          = null;      // input field element
var suggBox             = null;      // suggestion box (DIV)
var suggVisible         = false;
var xmlhttp             = null;
var lastHighlightedId   = -1;
var suggCount           = -1;
var callcounter         = 0;
var searchDelay         = 1000;       // Suchverzögerung in ms
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         = "#D1D1D1";
var requestURL          = "";        // URL to be called for the request. The input field value is escaped and appended

function do_blur(event) {
    if (!event && window.event) {
        event = window.event;
    }
    // hide suggestion box
    hide_box();
    
    if ( document.form_quicksearch['qs_sys_area.name'].value == '' ) {document.form_quicksearch['qs_sys_area.name'].value = as_sys_area_name }
}

function do_keydown(event) {
   
    if (!event && window.event) {
        event = window.event;
    }
    if (!xmlhttp) return;
    switch (event.keyCode) {
        case 37: {
            // left
            break;
        }
        case 39: {
            // right
            break;
        }
        case 9: {
            // right
            break;
        }
        case 40: {
            // down
            if (!suggVisible) {
                setTimeout("do_search()", 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);
                        }
                        show_box();
                    }
                    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);
                    }
                    show_box();
                }
                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
            //return false;
            if (suggVisible && (lastHighlightedId >= 0)) {
                hide_box();
                var row = document.getElementById("suggRow" + lastHighlightedId);
                if (event.cancelBubble) event.cancelBubble();
                if (row) {
                    var fx = row.onmousedown;
                    fx();
                }
            }
            return false;
            break;
        }
        case 27: {
            // Escape
            if (suggVisible) {
                selectRow(-1);
                hide_box();
                if (event.cancelBubble) event.cancelBubble();
                // restore input value after a short time
                backupValue = inputField.value;
                setTimeout("inputField.value = backupValue", 180);
            }
            break;
        }
        default: {
            call_search();
        }
    }
}


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 set_value(string, city, sys_area_node_id) {
//    inputField.value = string;
//    //document.form_quicksearch['qs_sys_area.name'].value = city;
//}

function set_value(string) {
    inputField.value = string;
    //document.form_quicksearch['qs_sys_area.name'].value = city;
}

function setDivSize() {
    if (suggBox) {
            suggBox.style.top =
                getParentProps(inputField, "offsetTop") + inputField.offsetHeight + "px";
            suggBox.style.left = getParentProps(inputField, "offsetLeft") + "px";
            suggBox.style.minWidth = (fixedwidth < 0 ? '40%' : fixedwidth);
    }
}

function fill_box(astrings, bstrings, cstrings) {
    var userInput = document.form_quicksearch['qs_sys_area.name'].value;
    
    // altes zeugs entfernen
    while (suggBox.hasChildNodes()) {
        suggBox.removeChild(suggBox.firstChild);
    }

    if (cstrings == 0) {
       bDiv = document.createElement("div");
       //bDiv.onmouseover = new Function("omoUser", "mouseEnter('User')");
       //bDiv.onmousedown = new Function("omdUser", "submit_value('" + userInput.replace(/'/g, "\"") + "', 'Ihre Eingabe')");
       bDiv.id = "suggRowHelp";
       bDiv.className = "suggRow";
       bDiv.style.cursor = "pointer";
       bDiv.innerHTML = "<div class='suggItem'><div class='suggProduct'><nobr>" + as_sys_area_no_result + "&nbsp;&nbsp;</nobr></div></div>";
       suggBox.appendChild(bDiv);
    }
    else {

       bDiv = document.createElement("div");
       //bDiv.onmouseover = new Function("omoUser", "mouseEnter('User')");
       //bDiv.onmousedown = new Function("omdUser", "submit_value('" + userInput.replace(/'/g, "\"") + "', 'Ihre Eingabe')");
       bDiv.id = "suggRowUser";
       bDiv.className = "suggUserRow";
       bDiv.style.cursor = "pointer";
       bDiv.innerHTML = "<div class='suggItem'><div class='suggProduct'><nobr>" + as_sys_area_result + "&nbsp;&nbsp;</nobr></div></div>";
       suggBox.appendChild(bDiv);

       // append suggests
       for (i = 0; i < astrings.length; i++) {
           bDiv = document.createElement("div");
           bDiv.onmouseover = new Function("omo" + i, "mouseEnter(" + i + ")");
           bDiv.onmousedown = new Function("omd" + i, "set_value('" + astrings[i].replace(/'/g, "\"") + "')");
           bDiv.id = "suggRow" + i;
           bDiv.className = "suggRow";
           bDiv.style.cursor = "pointer";
           //bDiv.innerHTML = "<div class='suggItem'><div class='suggProduct'><nobr>" + astrings[i] + "&nbsp;&nbsp;</nobr></div><div class='suggCat'><nobr>" + bstrings[i] + "</nobr></div></div>";
           bDiv.innerHTML = "<div class='suggItem'><div class='suggProduct'><nobr>" + astrings[i] + "&nbsp;&nbsp;</nobr></div></div>";
           suggBox.appendChild(bDiv);
       }
       lastHighlightedId = -1;
   }

}

function init_box(astrings, bstrings, cstrings) {
    suggCount = astrings.length;
    

    fill_box(astrings, bstrings, cstrings);

    if (astrings.length == 0) {
        hide_box();
        return;
    }
    show_box();
}

function call_search() {
    callcounter++;
    setTimeout("do_search()", searchDelay);
}

function do_search() {
    if (callcounter > 0)
        callcounter--;
    if (callcounter > 0) return;
    if (inputField.value.length < 3) {
        hide_box();
        return;
    }
    if (!xmlhttp) return;
    if (xmlhttp.readyState != 0) {
        xmlhttp.abort();
    }
    
    xmlhttp.open("GET", requestURL + escape(inputField.value) + "&" + Math.random(), true);
    //xmlhttp.open("GET", requestURL + replace_special_chars(inputField.value), true);
    //xmlhttp.open("GET", requestURL + inputField.value + "&" + Math.random() , true);
    
    xmlhttp.onreadystatechange = function() {
      //alert ("STATE: " + xmlhttp.readyState);
      if (xmlhttp.readyState == 4 && xmlhttp.responseText) {
          //alert ("RESPTXT: " + 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
                hide_box();
            }
          }
        }
      }
    };
    xmlhttp.send(null);
}

function replace_special_chars(str) {
   //alert (str);
   str = str.replace(/\ž/, ':z');
   str = str.replace(/\š/, ':s');
   str = str.replace(/\ć/, ':c');
   str = str.replace(/\č/, ':c');
   str = str.replace(/\đ/, ':d');
   str = str.replace(/\Đ/, ':D');
   str = str.replace(/\Š/, ':S');
   str = str.replace(/\Ž/, ':Z');
   //alert (str);
   return str;
}


function setup(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) {
        }
    }
    
   
    
    input.autocomplete = "off";
    input.onblur = do_blur;
     
    input.onkeydown = do_keydown;
    
    input.onmousedown = do_blur;

    suggBox = document.createElement("div");
    suggBox.name = "suggBox";
    document.body.appendChild(suggBox);
    
    suggBox.className = "suggBox";
    suggBox.id = "suggBox";
    setDivSize();

    window.onresize = setDivSize;
}

function show_box() {

    // begin determine box width
    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';
//        }
    }
    // end determine box width

    document.getElementById("suggBox").style.visibility="visible";
    

    suggVisible = true;
}

function hide_box() {
    document.getElementById("suggBox").style.visibility="hidden";
    suggVisible = false;
}
