(function($) {
$.fn.quickSearch = function(options) {
var settings = {
url: '/',
delay: 600,
holder: $('#item-list'),
loader: '<%= asset_path 'forge/ajax-loader.gif' %>'
};
if ( options )
$.extend( settings, options );
var previousValue = "";
this.each(function() {
$(this).keyup($.debounce(settings.delay, runUpdate));
});
function runUpdate() {
var currentValue = $(this).val();
// Do nothing if the search hasn't changed
if (currentValue == previousValue) {
return;
}
// Hide the default content if this is the first time the search is entered
if (previousValue == '') {
hideDefaultContent();
}
previousValue = currentValue;
// Restore the old content if search is cleared
if (currentValue == '') {
restoreDefaultContent();
return;
}
// Show a loader
var loader = $('
').css('text-align', 'center').html($('
').attr('src', settings.loader))
settings.holder.html(loader);
// Run the query
$.ajax({
url: settings.url,
data: {q: currentValue},
dataType: 'HTML',
success: function(data) {
if ($.trim(data) == '') {
var noResult = $('')
.addClass('no-search-results')
.html("Sorry, we couldn't find anything for " + currentValue + ".
Why don't you try a broader search term, we'll do our best to find what you're looking for!")
settings.holder.html(noResult);
} else {
settings.holder.html(data);
}
if(typeof searchTrigger == 'function') {
searchTrigger();
}
}
})
}
function hideDefaultContent() {
$('').html(settings.holder.html()).css('display', 'none').appendTo('body');
$('#item-list-bottom div.regular').fadeOut('fast', function() {
$('#item-list-bottom div.search-results').fadeIn('fast');
});
}
function restoreDefaultContent() {
settings.holder.html($('#hidden-quick-search-content').html());
$('#item-list-bottom div.search-results').fadeOut('fast', function() {
$('#item-list-bottom div.regular').fadeIn('fast');
});
}
}
})(jQuery);