$(document).ready(function() {
	$("#calendar-filters-top").each(function() {
		var element_filterContainer = this,
			element_filterToggle = $(this).find(".filter-toggle");

		$(element_filterToggle).click(function(clickEvent) {
			if ($(element_filterContainer).hasClass("filters-closed")) {
				$(element_filterContainer).removeClass("filters-closed").addClass("filters-open");
				setCookie("calendarfilters.open", true);
			} else if ($(element_filterContainer).hasClass("filters-open")) {
				$(element_filterContainer).removeClass("filters-open").addClass("filters-closed");
				setCookie("calendarfilters.open", false);
			}

			return stopEvent(clickEvent);
		});
	});

	$("#calendar-filters-bottom").each(function() {
		var element_filterContainer = this,
			elements_filterGroupToggles = $(this).find(".filter-group-toggle");

		$(elements_filterGroupToggles).each(function() {
			var element_filterGroup = $(this).closest(".filter-group");
			$(this).click(function(clickEvent) {
				if (!$(element_filterGroup).hasClass("active")) {
					$(element_filterContainer).find(".filter-group.active").removeClass("active");
					$(element_filterGroup).addClass("active");
				} else {
					$(element_filterGroup).removeClass("active");
				}

				return stopEvent(clickEvent);
			});
		});
	});

	$(".clear-target-filter").on("click", function(clickEvent) {
		$($(this).data("target-selector")).each(function() {
			if ($(this).attr("type").toLowerCase() == "checkbox")
				$(this).attr("checked", false);
			else if ($(this).attr("type").toLowerCase() == "radio")
				$(this).closest(".filter-group").find("input[type='radio']").first().attr("checked", true);
			else if ($(this).attr("type").toLowerCase() == "text")
				$(this).val("");
		});
		$("#form_calendar-filters").submit();
	});

	// Setup a click handler on the DOM that can run special handling for any click event that was not stopped
	$("html").mousedown(function(clickEvent) {
		// Close open filter groups that were not just clicked in
		if ($(".filter-group.active").length > 0) {
			var clickedFilterGroup = $(clickEvent.target).closest(".filter-group")[0];
			$(".filter-group.active").each(function() {
				if (clickedFilterGroup == null || this != clickedFilterGroup)
					$(this).removeClass("active");
			});
		}
	});
});