/*
* smx_sm: Ergänzung um Browsercheck und Positionsbestimmung für IE z-index Fix!
*/

/*Browsercheck object*/
function cm_bwcheck(){
    //In theory we should use object detection, but this script needs work-arounds for almost every browser...
    this.ver=navigator.appVersion
    this.agent=navigator.userAgent.toLowerCase()
    this.dom=document.getElementById?1:0
    this.ns4=(!this.dom && document.layers)?1:0;
    this.op=window.opera
    this.moz=(this.agent.indexOf("gecko")>-1 || window.sidebar)
    this.ie=this.agent.indexOf("msie")>-1 && !this.op
    if(this.op){
        this.op5=(this.agent.indexOf("opera 5")>-1 || this.agent.indexOf("opera/5")>-1)
        this.op6=(this.agent.indexOf("opera 6")>-1 || this.agent.indexOf("opera/6")>-1)
        this.op7=this.dom&&!this.op5&&!this.op6 //So all higher opera versions will use it
    }else if(this.moz) this.ns6 = 1
    else if(this.ie){
        this.ie4 = !this.dom && document.all
    this.ie5 = (this.agent.indexOf("msie 5")>-1)
    this.ie55 = (this.ie5 && this.agent.indexOf("msie 5.5")>-1)
    this.ie6 = this.dom && !this.ie4 && !this.ie5 && ! this.ie55
    }
    this.mac=(this.agent.indexOf("mac")>-1)
    this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.op5 || this.op6 || this.op7)
    this.usedom= this.ns6||this.op7//Use dom creation
    this.reuse = this.ie||this.op7||this.usedom //Reuse layers
    this.px=this.dom&&!this.op5?"px":""
    return this
}
var bw=new cm_bwcheck()

function findPos(ename, offsetX, offsetY){
    x=0; y=0; var el,temp
    el = bw.ie4?document.all[ename]:document.getElementById(ename);
    if(el.offsetParent){
    temp = el
    while(temp.offsetParent){ //Looping parent elements to get the offset of them as well
        temp=temp.offsetParent;
        x+=temp.offsetLeft
        y+=temp.offsetTop;
    }
    }
    x+=el.offsetLeft
    y+=el.offsetTop

    x += offsetX;
    y += offsetY;

    //Returning the x and y as an array
    return [x,y];
}


function FFSuggest() {

    var pRequest;
    var pLayer;
    // smx_sm: Referenz-DIV, anhand dessen der Autocomplete-DIV positioniert wird - nötig wegen IE z-index Problemen bei edumero!
    var pRefLayer;
    var pRefLayerName			= '';
    var ieOffsetX				= 20;
    var ieOffsetY				= 35;
    // smx_sm: Ende der neuen Parameter für IE-Fix
    var pDebug					= false;
    var pInstanceName			= '';
    var pSearchURL				= '';
    var pQueryParamName			= '';
    var pFormname 				= '';
    var pLayerName				= '';
    var pQueryInput;
    var pSuggest				= new Array();
    var pLastQuery;
    var pCurrentSelection		= 0;
    var submitted				= false;

    var pSuggestQueryClass 		= 'suggestTextQuery';
    var pSuggestTypeClass 		= 'suggestTextType';
    var pSuggestAmountClass     = 'suggestTextAmount';
    var pSuggestQueryTypedClass = 'suggestTextQueryTyped';
    var pSuggestFooterClass     = 'suggestFooter';
    var pSuggestHeaderClass     = 'suggestHeader';
    var pSuggestRowClass	    = 'suggestRow';
    var pSuggestHighlightClass  = 'suggestHighlight';

    this.init = function(searchURL, formname, queryParamName, divLayername, instanceName, debugMode, channelParamName, channel, refLayername) {
        pSearchURL			= searchURL;
        pFormname			= formname;
        pQueryParamName		= queryParamName;
        pChannelParamName	= channelParamName;
        pChannel			= channel;
        pLayerName			= divLayername;
        pInstanceName		= instanceName;
        pDebug				= debugMode;
        pRefLayerName		= refLayername;
        if (pSearchURL == '') {
            if (pDebug) alert('no searchurl defined');
            return null;
        } else if (pInstanceName == '') {
            if (pDebug) alert('no instancename defined');
            return null;
        } else if (pFormname == '') {
            if (pDebug) alert('no formname defined');
            return null;
        } else if (pQueryParamName == '') {
            if (pDebug) alert('no queryparamname defined');
            return null;
        } else if (pLayerName == '') {
            if (pDebug) alert('need a layer for output');
        }
        pQueryInput = document[pFormname][pQueryParamName];
        pQueryInput.onkeyup	= handleKeyPress;
        // smx_sm: deaktiviert, onfocus soll der Default-Text verschwinden
        //pQueryInput.onfocus	= showLayer;
        pQueryInput.onblur	= hideLayer;
        document[pFormname].onsubmit = handleSubmit;
    }


    function handleSubmit() {
        submitted = true;
        if (pSuggest[pCurrentSelection] != undefined) {
            document[pFormname][pQueryParamName].value = pSuggest[pCurrentSelection].split('###')[0];
            if(document[pFormname]['queryFromSuggest'] != null && pSuggest[pCurrentSelection].split('###')[2] != "Suchbegriff"){
                document[pFormname]['queryFromSuggest'].value = true;
            }
        }
    }

    this.handleClick = function() {
        if (pSuggest[pCurrentSelection] != undefined) {
            document[pFormname][pQueryParamName].value = pSuggest[pCurrentSelection].split('###')[0];
            if(document[pFormname]['queryFromSuggest'] != null){
                document[pFormname]['queryFromSuggest'].value = true;
            }
            document[pFormname].submit();
        }
    }

    this.handleMouseOver = function(pos) {
        var tblCell = getTableCell(pos);
        unmarkAll();
        if (tblCell != null) {
            highlightSuggest(tblCell);
            pCurrentSelection = pos;
        }
    }

    this.handleMouseOut = function(pos) {
        var tblCell = getTableCell(pos);
        if (tblCell != null) {
            unmarkSuggest(tblCell);
            pCurrentSelection = -1
        }
    }

    function handleKeyPress(evt) {
        evt = (evt) ? evt : ((event) ? event : null);
        var keyCode = evt.keyCode;
        if (keyCode == 38) {
            moveSelection('up')
        } else if (keyCode == 27) {
            hideLayer();
        } else if (keyCode == 40) {
            moveSelection('down');
        } else {
            if (pQueryInput.value == '') {
                hideLayer();
                if (pLayer != null){ pLayer.innerHTML = ''; }
                return null;
            }
            if (pLastQuery != pQueryInput.value){ startAjax(); }
            pLastQuery = pQueryInput.value;
        }
    }

    function moveSelection(direction) {
        var pos = pCurrentSelection;
        if (direction == 'up'){	pos--; }
        else{ 					pos += 1; }

        if (pos < 0) {
            unmarkAll();
            pQueryInput.focus();
            pCurrentSelection	= -1;
        } else {
            var tblCell = getTableCell(pos);
            if (tblCell != null) {
                unmarkAll();
                highlightSuggest(tblCell);
                pCurrentSelection = pos;
            }
        }

        var query = pQueryInput.value;
        pQueryInput.value = '';
        pQueryInput.focus();
        pQueryInput.value = query;
    }

    function startAjax() {
        var query = pQueryInput.value;
        var requestURL = pSearchURL +'?'+ pQueryParamName +'='+ escape(query) +'&'+ pChannelParamName +'='+ pChannel;

        try {
            if( window.XMLHttpRequest ) {
                pRequest = new XMLHttpRequest();
            } else if( window.ActiveXObject ) {
                pRequest = new ActiveXObject( "Microsoft.XMLHTTP" );
            } else {
                if (pDebug) alert( 'no ajax connection' );
            }

            pLayer = document.getElementById(pLayerName);
            if (pLayer != null) {
                if (query != '') {

                    pRequest.open( "GET", requestURL, true );
                    pRequest.onreadystatechange = callbackAjax;
                    pRequest.send( null );
                } else {
                    hideLayer();
                }
            } else {
                if (pDebug) alert( 'no layer for output found' );
            }
        } catch( ex ) {
            hideLayer();
            if (ex == undefined) {
                if (pDebug) alert( 'Error: ' + ex.getmessage );
            } else {
                if (pDebug) alert( 'Error: ' + ex );
            }
        }
    }

    function hideLayer() {
        if (pLayer != null) {
            pLayer.style.display = 'none';
            fireSuggestLayerHidden();
        }
    }

    this.hideLayerOutsideCall = function() {
        if (pLayer != null) {
            pLayer.style.display = 'none';
            fireSuggestLayerHidden();
        }
    }

    function showLayer() {
        if (pLayer != null && pSuggest != null && pSuggest.length >= 1) {
            // smx_sm: Workaround fuer IE Z-Index Probleme!
            if(bw.ie && pRefLayerName != null && pRefLayerName != '')
            {
                var pPos = findPos(pRefLayerName,0,0);
                pLayer.style.left = pPos[0] + ieOffsetX;
                pLayer.style.top = pPos[1] + ieOffsetY;
                pLayer.style.position = 'absolute';
            }
            pLayer.style.display = 'block';
        }
    }

    function callbackAjax() {
        if (submitted == false) {
            if (pRequest.readyState == 4) {
                if (pRequest.status != 200) {
                    hideLayer();
                    if (pDebug) alert( 'Error (' + pRequest.status + '): ' + pRequest.statusText );
                } else {
                    handleResponse(pRequest.responseText);
                }
            }
        }
  }

    // calls the callback for "outside" listeners if the callback is implemented
    function fireSuggestCompleted(suggestLayerIsVisible) {
        if (typeof(onSuggestCompleted) == 'function') {
            onSuggestCompleted(suggestLayerIsVisible);
        }
    }

    // calls the callback for "outside" listeners if the callback is implemented
    function fireSuggestLayerHidden() {
        if (typeof(onSuggestLayerHidden) == 'function') {
            onSuggestLayerHidden();
        }
    }

    function handleResponse(text) {
        pCurrentSelection = -1;
        pSuggest = new Array();
        pSuggest = text.split('\n');
        var outputText = '<table cellpadding="0" cellspacing="0" class="' + pLayerName + '" width="100%" border="0" onMouseDown="' + pInstanceName + '.handleClick();">';
        outputText += '<tr class="'+pSuggestHeaderClass+'" ><td nowrap="nowrap" colspan="3"><ff:jsescape><bean:message bundle="Suggest" key="header" /></ff:jsescape></td></tr>';

        var pNewSuggest = new Array();
        //for (var i in pSuggest) {
        for (var i = 0; i < pSuggest.length; i++) {
            var firstChar = pSuggest[i].charCodeAt(0);

            if (firstChar != 13 && firstChar != 10 && pSuggest[i].length >= 1) {
                pNewSuggest.push(pSuggest[i]);
            }
        }
        pSuggest = pNewSuggest;
        var query = pQueryInput.value;

        for (var i = 0; i < pSuggest.length; i++) {
            pSuggestParts = new Array();
            pSuggestParts = pSuggest[i].split("###");

            outputText += '<tr id="' + pLayerName + '_' + i + '" class="'+pSuggestRowClass+'" onMouseOver="' + pInstanceName + '.handleMouseOver(' + i + ');" onMouseOut="' + pInstanceName + '.handleMouseOut(' + i + ');">'
                                +'<td nowrap="nowrap" class="'+ pSuggestQueryClass +'">&nbsp;' + pSuggestParts[0].replace(new RegExp("("+query+")","ig"),'<span class="'+pSuggestQueryTypedClass+'">$1</span>') + '&nbsp;</td>'
                                //+'<td nowrap="nowrap" class="'+ pSuggestTypeClass +'">' + pSuggestParts[2] + '&nbsp;</td>'
                                +'<td nowrap="nowrap" class="'+ pSuggestTypeClass +'">&nbsp;</td>';
            if ( pSuggestParts[1] != undefined && pSuggestParts[1] != null && pSuggestParts[1] != "") {
            	outputText += '<td nowrap="nowrap" class="'+ pSuggestAmountClass +'">(' + pSuggestParts[1] + ')&nbsp;</td>';
            } else {
            	outputText += '<td nowrap="nowrap" class="'+ pSuggestAmountClass +'"></td>';
            }
            outputText += '</tr>';
        }
        //outputText += '<tr><td class="'+pSuggestFooterClass+'" colspan="3">&nbsp;</td></tr></table>';
        outputText += '</table>';
        if (pSuggest.length >= 1) {
            showLayer();
            pLayer.innerHTML = outputText;

            // calback for "outside" listeners
            fireSuggestCompleted(true);
        } else {
            hideLayer();
            pLayer.innerHTML = '';

            // calback for "outside" listeners
            fireSuggestCompleted(false);
        }

    }

    function highlightSuggest(tblCell) {
        tblCell.className = pSuggestHighlightClass;
    }

    function unmarkSuggest(tblCell) {
        tblCell.className = pSuggestRowClass;
    }

    function unmarkAll() {
        var tblCell;
        //for (var i in pSuggest) {
        for (var i = 0; i < pSuggest.length; i++) {
            tblCell = getTableCell(i);
            if (tblCell != null) {
                unmarkSuggest(tblCell);
            }
        }
    }

    function getTableCell(pos) {
        var tblCell;
        tblCell = document.getElementById(pLayerName + '_' + pos);
        return tblCell;
    }


}