/**
 * fastLiveFilter jQuery plugin 1.0.3
 * 
 * Copyright (c) 2011, Anthony Bush
 * License: <http://www.opensource.org/licenses/bsd-license.php>
 * Project Website: http://anthonybush.com/projects/jquery_fast_live_filter/
 **/
!function ($) {
	$.fn.fastLiveFilter = function(list, item, tar, options) {
		// Options: input, list, timeout, callback
		options = options || {};
		list = $(list);
		var input = this;
		var target = $(tar);
		var timeout = options.timeout || 0;
		var callback = options.callback || function() {};
		
		var keyTimeout;
		
		// NOTE: because we cache lis & len here, users would need to re-init the plugin
		// if they modify the list in the DOM later.  This doesn't give us that much speed
		// boost, so perhaps it's not worth putting it here.
		var lis = list.find(item);
		var len = lis.length;
		var oldDisplay = len > 0 ? lis[0].style.display : "block";
		callback(len); // do a one-time callback on initialization to make sure everything's in sync
		
		input.change(function() {
			// var startTime = new Date().getTime();
			var filter = input.val().toLowerCase();
			var li;
			var numShown = 0;
			for (var i = 0; i < len; i++) {
				li = lis.eq(i);
				if ((li.find(target).text()).toLowerCase().indexOf(filter) >= 0) {
					if (li.hasClass("mark")) {
						li.removeClass('mark');
						
						// for Orbit
							// var showTags = lis.not('.mark').find('input[type="checkbox"]:checked').length;
							// if(lis.showTags) {
							// 	$('#deselect, #deleteTags').removeClass('hide')
							// }
					}
					numShown++;
				} else {
					if (!li.hasClass("mark")) {
						li.addClass('mark');

						// for Orbit
							// var showTags = lis.not('.mark').find('input[type="checkbox"]:checked').length;
							// if(showTags == 0) {
							// 	$('#deselect, #deleteTags').addClass('hide')
							// }

							
							// li.children('.card').removeClass('active').children('input').attr('checked', false);
							// if($('.tags input[type="checkbox"]:checked').length == 0) {
							// 	$('#deselect, #deleteTags, #addDefault').addClass('hide')
							// }
					}
				}
			}
			callback(numShown);
			// var endTime = new Date().getTime();
			// console.log('Search for ' + filter + ' took: ' + (endTime - startTime) + ' (' + numShown + ' results)');
			return false;
		}).keydown(function(e) {
			// TODO: one point of improvement could be in here: currently the change event is
			// invoked even if a change does not occur (e.g. by pressing a modifier key or
			// something)
			clearTimeout(keyTimeout);
			keyTimeout = setTimeout(function() { input.change(); }, timeout);
			if(e.which == '13') {
				e.preventDefault();
			}
			// } else if(e.which == '8') {
			// 	clearTimeout(keyTimeout);
			// 	keyTimeout = setTimeout(function() { input.change(); }, timeout);
			// }
		});
		return this; // maintain jQuery chainability
	}
}(window.jQuery);
