/*
	livesearch ported to jquery, from zope livesearch
*/

jQuery(document).ready( function() {
    function hideLSResult()
    {
        jQuery('#LSResult').fadeOut();
        jQuery('body').unbind('click', hideLSResult);
    }

    function LSKeyPress(event){        
        var highlight = jQuery("#LSHighlight");
        if (event.keyCode == 40 )
        //KEY DOWN
        {
            if (highlight.length==0) {
                highlight = jQuery(".LSRow:first");
            } else {
                highlight.attr("id","");
                highlight = highlight.next(".LSRow");
            }
            if (highlight)
                highlight.attr("id","LSHighlight");
            event.preventDefault();
        }
        //KEY UP
        else if (event.keyCode == 38 ) {
            if (highlight.length==0) {
                highlight = jQuery(".LSRow:last");
            }
            else {
                highlight.attr("id","");
                highlight = highlight.prev('.LSRow');
            }
            if (highlight)
                highlight.attr("id","LSHighlight");
            event.preventDefault();
        }
        //ESC
        else if (event.keyCode == 27) {
            if (highlight)
                highlight.attr("id","");
            hideLSResult();
        }
        else if (event.keyCode == 13) {
            if (highlight) {
                window.location = highlight.find("a").get(0).href;
                event.preventDefault();                
            }
        }
    }
    
    function LSKeyDown(event){
        if (window.LSt) {
            window.clearTimeout(window.LSt);
        }
        var code = event.keyCode;
        if (code!=40 && code!=38 && code!=27 && code!=37 && code!=39) {
            window.LSt = window.setTimeout(LSDoSearch, 200);
        }
    }
    
    function LSDoSearch(){
        if (jQuery('#searchGadget').val().length < 2)
            return;
        
        jQuery("#LSShadow").load('/livesearch/?q=' + jQuery('#searchGadget').val(), 
            function() {
                jQuery('#LSResult').fadeIn();
                jQuery('body').bind('click', hideLSResult);
            });     
    }

    jQuery('#searchGadget').keydown( LSKeyDown );
    jQuery('#searchGadget').keypress( LSKeyPress );

});

