
$(document).ready(function() {

	function dashDebounce( fn, threshold ) {
		var timeout;

		return function dashDebounced() {
			if ( timeout ) {
				clearTimeout( timeout );
			}

			function dashDelayed() {
				fn();
				timeout = null;
			}
			setTimeout( dashDelayed, threshold || 100 );
		}
	}


	$('.dashboard-search').keyup( function() {
		var el = $(this);

		var check = function(el) {
			
			var parent	= el.closest(".sitemap-col").parent(),
				items	= parent.find(".dashboard-content"),
				search	= el.val().split(" "),				
				none	= parent.find(".no-results");

			if (items.length > 0){ 
				items.each(function() {
					var tr		= $(this).parent(),
						itext	= $(this).text().replace("\"" , " ").replace("\"" , " "),
						res		= null;

					if (search.length > 0){
						for (i in search){

							res = itext.match( new RegExp( search[i], 'gi' ) );			

							if (!res) {
								tr.hide().addClass("xhidden");
								return true;
							}
						}
					}

					tr.show().removeClass("xhidden");
					tr.siblings(".dashboard-item-title").show().removeClass("xhidden");

				});
			}

			var sets	= parent.find(".dashboard-item-title:not(.xhidden)");

			if (sets.length > 0) {
				sets.each(function() {

					var el		= $(this),
						sib		= el.siblings(".dashboard-item:not(.xhidden)");

					if (!el.hasClass("xhidden") && !sib.length) {
						el.siblings(".dashboard-item").show().removeClass("xhidden");
					}

				});
			}

			//results = parent.find(".dashboard-item:not('.xhidden')");

			results = $(".sitemap-col-1 .dashboard-item:not('.xhidden')");
			none	= $(".sitemap-col-1 .no-results");

			if (results.length) {
				none.hide();
			} else {
				none.show();
			}

			results = $(".sitemap-col-2 .dashboard-item:not('.xhidden')");
			none	= $(".sitemap-col-2 .no-results");

			if (results.length) {
				none.hide();
			} else {
				none.show();
			}

		}

		dashDebounce( check(el), 100);
	});

});