/**
	Glossary Live Search jQuery plugin
		by Chris Jones
		copyright (c) 2008 Chris Jones
**/

(function($){
	$.fn.glossary = function(options) {

		// search box
		var search_box = $(options.searchBox);

		// clear button
		var clear_button = $(options.clearButton);

		// none found message
		var none_found;

		// dictionary
		var dl = $(this);

		// number of matches
		var matches = 0;


		function search() {
			var term = search_box.val();
			
			if (term == '') {
				// no search term, so show everything
				dl.find('dt, dd').show();
				
				clear_button.hide();
			} else {
				clear_button.show();
				
				matches = 0;
				
				// perform a search
				dl.find('dt').each(function () {
					var re = new RegExp($.trim(term).split(' ').join('|'), 'i');
					
					if (re.test($(this).text()) || re.test($(this).next('dd').text())) {
						matches += 1;
						
						$(this).show().next('dd').show();
					} else {$(this).hide().next('dd').hide();}
				});
				
				// if none found, show none found message
				none_found[matches == 0 ? 'show' : 'hide']();
			}
		}


		function clear() {
			search_box.val('');
			search();
			return false
		}


		function setup_glossary() {
			if (search_box.val() == '') {clear_button.hide();}
			
			none_found = dl.after("<p>Your search returned no results.</p>").next('p:first').hide();
			
			search_box.keyup(function(e) {
				if (e.which == 27) {
					// catch ESC key
					clear();
				} else if (!e.ctrlKey && !e.altKey) {
					// ignore CTRL/ALT/CMD
					search();
				}
			});
			
			clear_button.click(clear);
		}

		setup_glossary();

		return $(this);
	};
})(jQuery);