$(document).ready(function(){
	
	var siteaccess;
	siteaccess = $('#siteaccess').text();
	
	$('#see_all_months').live("click", function(){
		uncheckOthers( 'filter', '/' + siteaccess + '/tellus/filterevent', 'see_all_months' );
	});
	
	$('input.filter').live("click", function(){
		uncheckSeeAll( 'filter', '/' + siteaccess + '/tellus/filterevent', 'see_all_months' );
	});
	
	$('#see_all_categories').live("click", function(){
		uncheckOthers( 'category', '/' + siteaccess + '/tellus/filterevent', 'see_all_categories' );
	});
	
	$('input.category').live("click", function(){
		uncheckSeeAll( 'category', '/' + siteaccess + '/tellus/filterevent', 'see_all_categories' );
	});
	
	/* uncheckes the specific options if the 'all' checkbox is checked */
	function uncheckOthers(checkboxname, ajax_filter_url, main)
	{
		// if the parent toogle (the 'all' option) is checked

		if ($('#'+main).attr('checked'))
		{
			// for each checkbox with the current name
			$("input." + checkboxname).each(function() {
				// unless it's the first, general item
				if(this.value != main)
				{
					// uncheck all specific options
					this.checked = false;
				}
		    });
		}
		
		// submit form
		submit(ajax_filter_url);
	}
	
	/* checks/unchecks the 'all' checkbox based on whether or not any
	 * of the specific options are checked
	 */
	function uncheckSeeAll(checkboxname, ajax_filter_url, main)
	{
		$('input#'+main).attr('checked', false);
		// submit form
		submit(ajax_filter_url);
	}
	
	/* submit data to filter */
	function submit(ajax_filter_url)
	{
		// for each checkbox
		var formfields = new Object();
		
		$("#filter input.filter, #filter input.category").each(function()
		{
			// if the current check box is checked
			if(this.checked)
			{
				formfields[this.name+'['+ this.value + ']'] = this.value;
			}
		});
		
		$.ajax({
		  type: 'post', 
		  url: ajax_filter_url,
		  data: formfields,
		  success: handleFilterResponse
		});
	}
	
	/* handle filter response */
	function handleFilterResponse(data)
	{
		$('#whats_on_container').html(data);
	}
});