var locationName = '';

$(document).ready(function(){
	$("#sportFilterBox img.sport_filter_button").click(
		function(){
			sport = extractID($(this).attr("id"));
			if(sport == undefined || sport == 'allsports'){
				sport = '';
			}else{
				sport = sport.replace('-',' ');
			}

			updateDisplay();
			return false;
		}
	).addClass("clickable");
	
	$("#emptyResultHint a").click (
		function ()
		{
			sport = '';
			locationID = 0;
			updateDisplay ();
			return false;
		}
	);
		
	updateDisplay();
	
});

function updateDisplay(){
	//	apply filters
	var results = applyFilters();
	
	setSportButtonStatuses(sport);
	
	if (locationID != 0)
	{
		$("#locationFilterDescription div").html("Results for " + locationName + ".");
		show($("#locationFilterDescription"));
	}
	
	if (results["Found"] == 0 && results["Total"] > 0)
	{
		show($("#emptyResultHint"),300);
	}
	else
	{
		hide($("#emptyResultHint"),300);
	}
}

function applyFilters(){
	var resultCount = 0;
	var totalCount = 0;
	
	hide($("div.currentLeague"));
		
	$("div.currentLeague").each(
		function(){
			var leagueID = extractID($(this).attr("id"));
			var ok = true;
			++totalCount;
			
			//filter by sport, if required
			if(sport != "" && sport != leagues[leagueID]["Sport"]){
				ok = false;
			}
			
			//filter by location and/or neighborhood, if required
			if(locationID != 0){
				var found = false;
				for(locID in leagues[leagueID]["Locations"]){
					if(locID == locationID)
					{
						if (locationName == '')
						{
							locationName = leagues[leagueID]["Locations"][locID]["LocationName"];
						}
						found = true;
						break;
					}
				}
				if(!found)
				{
					ok = false;
				}
			}
			
			if(ok){
				++resultCount;
				show($(this),300);
			}
		}
	);
	return {"Found":resultCount,"Total":totalCount};
}

//toggle whether the day given by daySelect is a part of the filter
function toggleDays(daySelect){
	if(daySelect == "AllDays"){
		days = new Array();
	}else{
		var foundIndex = indexOf(daySelect,days);
	
		if(foundIndex == -1){
			// not part of the filter, add it
			days.push(daySelect);
			$("#filter_" + daySelect).addClass("current");
		}else{
			// already part of the filter, remove it
			days.splice(foundIndex,1);
			$("#filter_" + daySelect).removeClass("current");
		}
	}
}

function updateDayDisplay(){
	$("#dayFilterBox li").each(function(){
		if(indexOf(extractID($(this).attr("id")),days) == -1){
			$(this).removeClass("current");
		}else{
			$(this).addClass("current");
		}
	});
	if(days.length == 0){
		$("#filter_AllDays").addClass("current");
	}else{
		$("#filter_AllDays").removeClass("current");
	}
}

