var pPreviousPattern = '' ;

function liveSearch_ExecuteSearch () {
    var pOptions = document.getElementById ( "mSearchModule").value ;
    var pPattern = document.getElementById ( "mSearchPattern" ).value ;

    if ( pPattern != pPreviousPattern && pPattern.length >= 4 ) {
        $( '#searchresult' ).load ( "zubehoer/ajax/liveSearch.php?" , { options : pOptions , keyword : pPattern } , function ( pContent , pState ) { if ( pState == 'success' ) { $( '#searchresult' ).show () } } ) ;
    }

    pPreviousPattern = pPattern ;
}

function liveSearch_ClearSearch ( noValue ) {
    $( '#searchresult' ).hide () ;

    if ( noValue == true ) {
        document.getElementById ( "mSearchPattern" ).value = '' ;
    }

    pPreviousPattern = '' ;
}

function liveSearch_Init () {
    var pObject   = document.getElementById ( "mSearchPattern" ) ;
    var pFunction = liveSearch_KeyPressed ;

    if ( navigator.userAgent.indexOf ( "Safari" ) > 0 ) {
        pObject.addEventListener ( "keydown" , pFunction , false ) ;
    } else if ( navigator.product == "Gecko" ) {
        pObject.addEventListener ( "keypress" , pFunction , false ) ;
    } else {
        pObject.attachEvent ( "onkeydown" , pFunction ) ;
    }

    $( "#searchPattern" ).attr ( "autocomplete" , "off" ) ;
}

function liveSearch_KeyPressed ( pNum ) {

    var pResult    = document.getElementById ( "result" ) ;
//     var pDirection = pNum.keyCode == 40 ? getNextNode : getPreviousNode ;
    var pPattern   = document.getElementById ( "mSearchPattern" ).value ;

    switch ( pNum.keyCode ) {
        case 37 : // key left
            document.getElementById ( "mSearchPattern" ).value = pPattern.substring( 0 , pPattern.length - 1 ) ;
            return false ;
            break ;

        case 40 : // key down
        case 38 : // key up
            if ( !document.getElementById ( "pointer" ) ) {
//                 var pActivate = pDirection ( pResult , "a" , "self" ) ;
            } else {
                if ( pDirection ( document.getElementById ( "pointer" ).parentNode , "a" ) ) {
                    var pActivate = pDirection ( document.getElementById ( "pointer" ).parentNode , "a" ) ;
                } else {
                    var pActivate = pDirection ( pResult , "a" , "self" ) ;
                }

                document.getElementById ( "pointer" ).id = '' ;
            }

            pActivate.id = "pointer" ;

            break ;

        case 27 : // ESC
            liveSearch_ClearSearch ( true ) ;
            break ;

        case 13 : // Enter
            if ( document.getElementById ( "pointer" ) ) {
                document.location.href = document.getElementById ( "pointer" ).href ;
            }
            break ;
    }
}
