//sport and locationID are already declared
var neighborhoodID = 0;
var skillLevelID = 0;
var days = new Array();

//	if there's only one league displaying, it looks a little different
var singleLeague = 0;

$(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");
	
	$("#locationFilterSwitcher input").click(function(){
		if($(this).attr("id") == "locationFilterView"){
			updateLocationFilters('location');
		}else{
			updateLocationFilters('neighborhood');
		}
	});
	
	$("#locationFilter").change(
		function(){
			locationID = $(this).attr("value");
			if(locationID == undefined)
				locationID = 0;
			if(locationID != 0)
				neighborhoodID = 0;
			
			updateDisplay();
		}
	);
	
	$("#dayFilterBox li").click(
		function(){
			toggleDays(extractID($(this).attr("id")));
			updateDisplay();
			return false;
		}
	).addClass("clickable");

	$("#neighborhoodFilter").change(
		function(){
			neighborhoodID = $(this).attr("value");
			if(neighborhoodID == undefined)
				neighborhoodID = 0;
			if(neighborhoodID != 0)
				locationID = 0;

			updateDisplay();
		}
	);
	
	$("#skillLevelFilter").change(
		function(){
			skillLevelID = $(this).attr("value");
			if(skillLevelID == undefined)
				skillLevelID = 0;
			updateDisplay();
		}
	);
	
	$("a.extraLocationLink").click (
		function ()
		{
			var leagueID = extractID($(this).attr("id"));
			var locationLinks = "";
			for (locationIndex in leagues[leagueID]["Locations"])
			{
				locationLinks += '<li><a href="' + leagues[leagueID]["Locations"][locationIndex]["LocationLink"] + '">' + leagues[leagueID]["Locations"][locationIndex]["LocationName"] + "</a>\n";
			}
			$("#extraLocationsList").html (locationLinks);
			$("#extraLocationsLeagueName").html (leagues[leagueID]["LeagueName"]);
			showPopup (this, $("#extraLocationPopup"));
			return false;
		}
	);
	
	updateDisplay();
	
});

function expandSingleLeague(leagueID)
{
	openDetailDisplay(leagueID);
	hide($("#hideDetails_" + leagueID));
	singleLeague = leagueID;
}

function revertSingleLeague()
{
	if(singleLeague != 0)
	{
		closeDetailDisplay(singleLeague);
		singleLeague = 0;
	}
}

function updateDisplay(){
	//	apply filters
	var resultCount = applyFilters();
	
	//	if no leagues, show the hint
	if(resultCount < 1){
		showEmptyResultHint();
	}else{
		hideEmptyResultHint();
		if(resultCount == 1)
		{
			//only one result...find it and expand it
			for(leagueID in leagues)
			{
				if(leagues[leagueID]["BadField"] == "" || leagueID == leagueIDQuery)
				{
					expandSingleLeague(leagueID);
					break;
				}
			}
		}
		else
		{
			revertSingleLeague();
		}
	}

	setSportButtonStatuses(sport);	

	//	update drop-down selections
	updateSelect(document.getElementById('locationFilter'),locationID);
	updateSelect(document.getElementById('neighborhoodFilter'),neighborhoodID);
	//updateSelect(document.getElementById('skillLevelFilter'),skillLevelID);
	
	//	make sure location menu shows if we came here with a locID
	if(locationID != 0)
		updateLocationFilters('location');
	
	//	highlight selected days in the day filter
	updateDayDisplay();	
}

function updateLocationFilters(current){
	if(current == 'neighborhood'){
		$("#neighborhoodFilterView").attr("checked",true);
		hide($("#locationFilter"));
		show($("#neighborhoodFilter"));		
	}else{
		$("#locationFilterView").attr("checked",true);
		show($("#locationFilter"));
		hide($("#neighborhoodFilter"));
	}
}

function showEmptyResultHint(){
	var emptyMessage;
	var reasons = populateReasons();
	if(reasons["Total"] > 0){
		emptyMessage = 'Sorry, no leagues or events matched all of your criteria.<br /><br />You can use the controls above to adjust your search, or try one of these options:<br /><ul>';
	}else{
		emptyMessage = 'Sorry, there are no leagues or events to display. Please check back later.<ul>';
	}
	
	if(sport != '' && reasons["Sport"] > 0)
		emptyMessage = emptyMessage + '<li><a href="#" onclick="sport=\'\';updateDisplay();return false;">' + getEmptyOption("Sport") + ': ' + reasons["Sport"] + ' results</a></li>';

	if(locationID != 0 && reasons["Location"] > 0)
		emptyMessage = emptyMessage + '<li><a href="#" onclick="locationID=0;updateDisplay();return false;">' + getEmptyOption('LocationID') +  ': ' + reasons["Location"] + ' results</a></li>';

	if(neighborhoodID != 0 && reasons["Location"] > 0)
		emptyMessage = emptyMessage + '<li><a href="#" onclick="neighborhoodID=0;updateDisplay();return false;">' + getEmptyOption('NeighborhoodID') + ': ' + reasons["Location"] + ' results</a></li>';

	if(skillLevelID != 0 && reasons["SkillLevel"] > 0)
		emptyMessage = emptyMessage + '<li><a href="#" onclick="skillLevelID=0;updateDisplay();return false;">' + getEmptyOption('SkillLevelID') +  ': ' + reasons['SkillLevel'] + ' results</a></li>';
		
	if(days.length > 0 && reasons["Day"] > 0)
		emptyMessage = emptyMessage + '<li><a href="#" onclick="days=new Array();updateDisplay();return false;">' + getEmptyOption('Days') +  ': ' + reasons['Day'] + ' results</a></li>';

	emptyMessage = emptyMessage + '</ul>';
	$("#emptyResultHint").html(emptyMessage);
	show($("#emptyResultHint"),300);
}

function populateReasons(){
	var reasons = {"Sport":0,"Location":0,"SkillLevel":0,"Day":0,"Total":0};
	for(leagueID in leagues){
		if(leagues[leagueID]["BadField"] != "" && leagues[leagueID]["BadField"] != "Multiple"){
			reasons[leagues[leagueID]["BadField"]]++;
		}
		reasons["Total"]++;
	}
	return reasons;
}

function getEmptyOption(optionToRemove){
	var nhID = neighborhoodID;
	var locID = locationID;
	var spt = sport;
	var dy = days;
	var sl = skillLevelID;
	var changeDescription = '';
	switch(optionToRemove){
		case 'NeighborhoodID':
			nhid = 0;
			break;
		case 'LocationID':
			locID = 0;
			break;
		case 'Sport':
			spt = '';
			break;
		case 'SkillLevelID':
			sl = 0;
			break;
		case 'Days':
			dy = new Array();
			break;
	}
	if(spt != ''){
		changeDescription = spt + ' ';
	}
	if(nhID != 0){
		changeDescription += "in " + getSelectText("neighborhoodFilter",nhID) + " ";
	}
	if(locID != 0){
		changeDescription += "at " + getSelectText("locationFilter",locID) + " ";
	}
	if(dy.length != 0){
		changeDescription += "on " + getDayNames(dy) + " ";
	}
	if(changeDescription == '')
	{
		changeDescription = 'All Offerings';
	}
	
	return changeDescription;
}

function getSelectText(selectBoxID,selectValue){
	var selectBox = document.getElementById(selectBoxID);
	for(var i = 0; i < selectBox.options.length; i++){
		if(selectBox.options[i].value == selectValue){
			return $(selectBox.options[i]).html();
		}
	}
}

function getDayNames(dayArray){
	var dayString = "";
	for(var i = 0; i < dayArray.length; i++){
		if(i == dayArray.length - 1 && dayArray.length > 1){
			dayString += " or ";
		}else{
			if(dayString != ""){
				dayString += ", "
			}
		}
		dayString += dayArray[i];
	}
	return dayString;
}

function hideEmptyResultHint(){
	hide($("#emptyResultHint"));
}

function updateSelect(selectBox,selectedValue){
	if(selectBox == undefined)
		return;
	for(var i = 0; i < selectBox.length; i++){
		if(selectBox.options[i].value == selectedValue){
			selectBox.selectedIndex = i;
			return;
		}
	}
	selectBox.selectedIndex = 0;
}

function applyFilters(){
	var resultCount = 0;
	
	hide($("div.leagueDetail"));
	
	if(leagueIDQuery != 0)
	{
		show($("#league_" + leagueIDQuery));
		return 1;
	}
	
	$("div.leagueDetail").each(
		function(){
			var leagueID = extractID($(this).attr("id"));
			var found = false;
			
			leagues[leagueID]["BadField"] = "";
			
			//filter by sport, if required
			if(sport != "" && sport != leagues[leagueID]["Sport"]){
				if(leagues[leagueID]["BadField"] == ""){
					leagues[leagueID]["BadField"] = "Sport";
				}else{
					leagues[leagueID]["BadField"] = "Multiple";
				}
			}
			
			//filter by location and/or neighborhood, if required
			if(locationID != 0 || neighborhoodID != 0){
				found = false;
				for(locID in leagues[leagueID]["Locations"]){
					if(
						(locID == locationID || locationID == 0) && 
						(leagues[leagueID]["Locations"][locID]["NeighborhoodID"] == neighborhoodID || neighborhoodID == 0)
					){
						found = true;
						break;
					}
				}
				if(!found){
					if(leagues[leagueID]["BadField"] == ""){
						leagues[leagueID]["BadField"] = "Location";
					}else{
						leagues[leagueID]["BadField"] = "Multiple";
					}
				}
			}
				
			//filter by skill level, if required
			if(skillLevelID != 0){
				found = false;
				for(skillIndex in leagues[leagueID]["SkillLevels"]){
					if(leagues[leagueID]["SkillLevels"][skillIndex]["SkillLevelID"] == skillLevelID){
						found = true;
						break;
					}
				}
				if(!found){
					if(leagues[leagueID]["BadField"] == ""){
						leagues[leagueID]["BadField"] = "SkillLevel";
					}else{
						leagues[leagueID]["BadField"] = "Multiple";
					}
				}				
			}
			
			//filter by day, if required
			if(days.length > 0){
				for(dayIndex in leagues[leagueID]["Day_Array"]){
					if(indexOf(leagues[leagueID]["Day_Array"][dayIndex],days) == -1){
						if(leagues[leagueID]["BadField"] == ""){
							leagues[leagueID]["BadField"] = "Day";
						}else{
							leagues[leagueID]["BadField"] = "Multiple";
						}
					}
				}
			}
			
			
			if(leagues[leagueID]["BadField"] == ""){
				show($(this),300);
				resultCount++;
			}
		}
	);
	return resultCount;
}

//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");
	}
}

