//Search Results//
//Extended Function, so that when you press enter, it autocompletes the form

jQuery.widget('ui.myAutocomplete', jQuery.extend({}, jQuery.ui.autocomplete.prototype, {
    _suggest : function(items) {
        var element = $(this);
        // Call ui.autocomplete's parent method
        jQuery.ui.autocomplete.prototype._suggest.call(element, items);
        
        // Find the first list item
        var item = element.menu.element.children()[0];
        
        // Make this item active.
        // An event is expected so a fake one is passed as a parameter.
        jQuery('#custom_search').live('keypress', function(e) {
            var keyCode = e.keyCode || e.which;

            if (keyCode == 9) { 
                e.preventDefault();
                element.menu.activate(new jQuery.Event('null.event'), jQuery(item));
                //jQuery("#ui-active-menuitem").css("background", "green");
                jQuery("#ui-active-menuitem").trigger('click');
            }
        });
    }
}));
            
//Main function for search autocomplete
jQuery(function() {
    var cache = {},
    lastXhr;
    jQuery( "#custom_search" ).myAutocomplete({
        minLength: 1,
        source: function( request, response ) {
            var term = request.term;
            if ( term in cache ) {
                response( cache[ term ] );
                return;
            }
            lastXhr = jQuery.getJSON( "http://store.youngcomposers.com/custom_classes/js/searchdata.php", request, function( data, status, xhr ) {
                cache[ term ] = data;
                if ( xhr === lastXhr ) {
                    response( data );
                }
            });
        }
    });
});

