var activeTooltip = null;

$(function () {
	$('#champion_list li img.champion_icon').each(function() {
		var tooltip = $(this).parent().parent().find('.champion_tooltip');
		tooltip.appendTo('body');
		
		$(this).hover(
			function() { 
				activeTooltip = tooltip;
			},
			function() { 
				activeTooltip.hide();
				activeTooltip = null;
			}
		);
	});
	
	
	$(document).mousemove(function(e) {			
		var middle = $('#champion_list').outerWidth() / 2;
		
		var obj = $('#champion_list')[0];
		
		do {
			middle += obj.offsetLeft;
		} while (obj = obj.offsetParent);
		
		if (activeTooltip != null) {
			activeTooltip.css({
				left: (e.pageX > middle ? e.pageX - activeTooltip.outerWidth() - 5 : e.pageX + 10), 
				top: e.pageY + 10
			});
			
			if (activeTooltip.is(':hidden')) {
				activeTooltip.show();
			}
		}
	}); 
	
	// Capture change events to check boxes.
	
	$('.filter').click(function () {
		$('#champion_text_filter').val('');
		refreshFilters();
	});
	
	$('#show_all_filter').click(function() {
		var checked = $('#show_all_filter').attr('checked');
		
		if (checked) {
			$('.filter').each(function(i, el) {
				$(el).attr('checked', false);
			});
		}
		
		refreshFilters();
	});
	
	var oldValue = '';
	$('#champion_text_filter').keyup(function() {
		if (this.value != oldValue) {
			oldValue = this.value;
		} else {
			return;
		}
		
		if (this.value.length > 0) {
			$('.filter:checked').attr('checked', false);
		}
		
		$('#champion_text_filter').stopTime();
		$('#champion_text_filter').oneTime(300, function() { refreshFilters(); });
	});
	
	refreshFilters();
});

function refreshFilters() {
	var keywordEmpty = $('#champion_text_filter').val().length == 0;
	var checksEmpty = $('.filter:checked').length == 0;

	$('#show_all_filter').attr('checked', keywordEmpty && checksEmpty);
	
	var selectors = 'li';
	
	if (!$('#show_all_filter').attr('checked')) {
		if (!checksEmpty) {
			$('.filter:checked').each(function(i,el) {
				selectors += '.' + el.value;
			});
		} else if (!keywordEmpty) {
			selectors += ':contains(' + $('#champion_text_filter').val() + ')';
		}
	}

	$('#champion_list').filterList(selectors);
}