jQuery('document').ready(function() {
	
	jQuery.extend(
		jQuery.expr[':'], {
			regex: function(a, i, m, r) {
				var r = new RegExp(m[3], 'i');
				return r.test(jQuery(a).text());
			}
		}
	);
	
	var qsTimeout, prevLength;
	prevLength = jQuery('#qs').val().length;
	
	// FUNCTIONS
	
	resetQuickSearch = function() {
		// clear the timeout
		if (qsTimeout) clearTimeout(qsTimeout);

		// clear the input field
		jQuery('#qs').val('');

		// hide the cancel button
		jQuery('#qx').hide();

		// reset the list
		filterRestaurantList();
	}
	
	filterRestaurantList = function() {
		qs = jQuery('#qs').val();
		if (qs.length) {
			/*
			jQuery('li.restaurant').hide();
			jQuery("li.restaurant:has(.keywords li:regex('"+qs+"'))").show().css('backgroundColor', 'transparent').filter(':even').css('backgroundColor', '#EEE');
			*/
		} else {
			/*
			jQuery('li.restaurant').show().css('backgroundColor', 'transparent').filter(':even').css('backgroundColor', '#EEE');
			*/
		}
	}
	
	
	// MAKE SEARCH BOX VISIBLE
	jQuery('#quick-search').submit(function(){ return false; }).css('visibility','visible');
	
	// HIDE AND SET UP THE (X)
	jQuery('#qx').click(function(){
		console.log('qx clicked');
		resetQuickSearch();
		jQuery('#qs').focus(); // refocus
	});
	
	// RESET THE SEARCH BOX
	resetQuickSearch();
	
	// SET INITIAL TEXT AND FOCUS ON THE INPUT FIELD
	jQuery('#qs').val('quick search').focus(function(){
		console.log('qs focused');
		if (jQuery(this).val() == 'quick search') jQuery(this).val('');
	});
	
	// INIT QUICK SEARCH
	jQuery('#qs').keyup(function(e){
		console.log('qs keyup');
		
		// the quick search input field
		qs = jQuery('#qs');

		// if letters are added or removed...
		// ON ESCAPE, CLEAR SEARCH
		if (e.keyCode == 27) {
			resetQuickSearch();
		} else {
			if (qs.val().length != prevLength) {

				// if there's a query string, enable the "x" button
				if (!qs.val().length) jQuery('#qx').hide();
				else jQuery('#qx').show();

				// reset the timeout
				console.log(qsTimeout);
				if (qsTimeout) clearTimeout(qsTimeout);
				qsTimeout = setTimeout(filterRestaurantList, 333);
				// save length for next go round
				prevLength = qs.val().length;
				console.log('previous string length = '+prevLength);
			}
		}
		
	});
	
});

