// Author: Ryan Heath
// Edited by Julien Vernet
// http://rpheath.com

(function($) {
	$.searchbox = {};

	$.extend(true, $.searchbox, {
		settings: {
			url: '/search',
			param: 'query',
			dom_id: '#results',
			delay: 100,
			loading_css: '#loading'
		},

		loading: function() {
			$($.searchbox.settings.loading_css).show();
		},

		resetTimer: function(timer) {
			if (timer) clearTimeout(timer);
		},

		idle: function() {
			$($.searchbox.settings.loading_css).hide();
		},

		process: function(terms) {
			// Add class for ajax spinner
			$('#ticket_subject').addClass('wpas-loading');

			// Check if search string is empty
			var blank_check = terms.replace(/\s/g, '');
			if(blank_check === ''){
				$('#ticket_subject').removeClass('wpas-loading');
				$('#wpas-search-results').html('');
				return false;
			}

			var path = $.searchbox.settings.url.split('?'),
			query = [$.searchbox.settings.param, '=', terms].join(''),
			base = path[0], params = path[1], query_string = query;

			if (params) query_string = [params.replace('&amp;', '&'), query].join('&');

			$.get([base, '?', query_string].join(''), function(data) {
				$($.searchbox.settings.dom_id).html(data);
			});
		},

		start: function() {
			$(document).trigger('before.searchbox');
			$.searchbox.loading();
		},

		stop: function() {
			$.searchbox.idle();
			$(document).trigger('after.searchbox');
		}
	});

$.fn.searchbox = function(config) {
	var settings = $.extend(true, $.searchbox.settings, config || {});

	$(document).trigger('init.searchbox');
	$.searchbox.idle();

	return this.each(function() {
		var $input = $(this);

		$input
		// .focus()
		// .ajaxStart(function() { $.searchbox.start(); })
		// .ajaxStop(function() { $.searchbox.stop(); })
		.keyup(function() {
			if ($input.val() != this.previousValue) {
				$.searchbox.resetTimer(this.timer);

				this.timer = setTimeout(function() {
					$.searchbox.process($input.val());
				}, $.searchbox.settings.delay);

				this.previousValue = $input.val();
			}
		});

		// As of jQuery 1.8, the .ajaxStart() method should only be attached to document. (http://api.jquery.com/ajaxStart/)
		$(document).ajaxStart(function() { $.searchbox.start(); });
	
		// As of jQuery 1.8, the .ajaxStop() method should only be attached to document. (http://api.jquery.com/ajaxStop/)
		$(document).ajaxStop(function() { $.searchbox.stop(); });
	});
};
})(jQuery);