$(document).ready(function() {
    // Standard autocomplete
    $('.auto').focus(function() {
        var cache = {}, lastXhr;
        var auto_type = this.name;
        var options = {
            source: function( request, response ) {
                var term = extractLast(request.term);
                // Check cache first
                if ( term in cache ) {
                    response( cache[ term ] );
                    return;
                }
                // Get from source
                lastXhr = $.getJSON( "/index/autocomplete", {type: auto_type, term: term}, function( data, status, xhr ) {
                    cache[ term ] = data;
                    if ( xhr === lastXhr ) {
                        response( data );
                    }
                });
            }
        };
        
        // If frontend search, auto-submit form
        if (auto_type == 'query') {
            options.select = function(event, ui) {
                $(this).parent().submit();
            };
        }
        
        $(this).autocomplete(options);
    });

    // Multiple autocomplete
    $('.auto-multi').focus(function() {
        var auto_type = this.name;
        var sep = (auto_type == 'keywords' ? ',' : '');
        var cache = {}, lastXhr;
        $(this).autocomplete({
            source: function( request, response ) {
                var term = extractLast(request.term, sep);
                // Check cache first
                if ( term in cache ) {
                    response( cache[ term ] );
                    return;
                }
                // Get from source
                lastXhr = $.getJSON( "/index/autocomplete", {type: auto_type, term: term}, function( data, status, xhr ) {
                    cache[ term ] = data;
                    if ( xhr === lastXhr ) {
                        response( data );
                    }
                });
            },
            
            focus: function() {
                return false;
            },
            
            select: function(event, ui) {
                var terms = split(this.value, sep);
                terms.pop();
                terms.push(ui.item.value);
                this.value = terms.join(sep + ' ') + sep + ' ';
                return false;
            }
        });
    });
    
    if (typeof(replace)!="undefined") {
        $('.replace').each( function(i, el) {
            $(el).html($(el).text().replace(new RegExp('('+replace+')', 'i'), '<mark>$1</mark>'));
        });
    }
});
    
function split( val, sep ) {
    if (sep == '') {
        reg = /\s+/;
    } else {
        reg = /,\s+/;
    }
    return val.split( reg );
}
function extractLast( term, sep ) {
    return split( term, sep ).pop();
}
