$(document).ready(function () {
	$('#sendebutton').css('display','none');
	$('#searchfilter ul li ul li ul').map(function () {
		if (!$(this).hasClass('active')) {
			$(this).css('display','none');
		}
	});
	$('#searchfilter input[type=checkbox]').click(function (event) {
		if ( $(this).hasClass('all') ) {
			handleAllClicked( this );
		} else {
			toggleParent( this );
		}
		$('#filterform').submit(); // Activate to enable onclick submit;
		// debug_form_values(); // Debugging to Firebug;
	})
})

function debug_form_values() {
	$('#filterform input').map(function () {
		if (this.checked) {
			console.log(this.name);
		}
	})
}

function toggleParent ( el ) {
	if ( $(el).parents('li').eq(0).hasClass('expandable') ) {
		if ( el.checked == false ) {
			collapse( $(el).parents('li').get(0) );			
		} else {
			expand( $(el).parents('li').get(0) );
		}
	}
	var pAll = $(el).parents('ul').eq(0).find('input.all').get(0);
	var checked = 0;
	$(el).parents('ul').eq(0).find('input').map(
		function () { 
					if (this.checked == true) {
						checked++;
						} 
					}
	);

	if (checked == 0) {
		pAll.checked = true;
	}	else {
		pAll.checked = false;
	}
	

}

function handleAllClicked ( el ) {

	if ( el.checked == true ) {
		$(el).parents('ul').eq(0).find('input').map(
			function () {
				this.checked = false;
			}
		);
		$(el).parents('ul').eq(0).find('li.expandable').map(
			function () {
				$(this).children('ul').eq(0).css('display','none');
			}
		);
		el.checked = true;
	} else  {
		if ( $(el).parents('li.expandable').get(0) ) {
			$(el).parents('li.expandable').eq(0).children('ul').css('display','none'); // collapse the expandable <ul>
			// $(el).parents('li.expandable').eq(0).children('input').get(0).click('foo');
			$(el).parents('li.expandable').eq(0).children('input').get(0).checked = false;
			toggleParent($(el).parents('li.expandable').eq(0).children('input').get(0));
		} else {
			el.checked = true;
		}
		
	}
}

function collapse ( el ) {
	$(el).children('ul').css('display','none');
	$(el).find('ul li input').map(function () { this.checked = false });
}

function expand ( el ) {
	// $(el).children('ul').css('display','block');
	$(el).find('ul input.all').get(0).checked = true;
}


