function initOpen() {
	$("a[rel='materials']")
		.unbind("click")
		.html("+ <span>alle anzeigen</span>")
		.click(function() {
			$("table.materials tbody tr.closed th p a").click();
			return false;
		});
}

function initClose() {
	$("a[rel='materials']")
		.unbind("click")
		.html("- <span>alle verbergen</span>")
		.click(function() {
			$("table.materials tbody tr:not(.closed) th p a").click();
			return false;
		});
}

function updateTableToggle() {
	if ($("table.materials tbody tr.closed th p a").size() == 0) {
		initClose();
	}
	if ($("table.materials tbody tr:not(.closed) th p a").size() == 0) {
		initOpen();
	}
}

$(document).ready(function(){
	$("table.materials tbody tr th p a").click(function(){
		var headerRow = this.parentNode.parentNode.parentNode;
		var start = false;
		var end = false;
		$("table.materials tbody tr > *").filter(function(index){
			if (!end && start) {
				if (this.tagName != "TH") {
					return true
				}
				else {
					end = true;
				}
			}
			if (!start && this.parentNode == headerRow) {
				start = true;
			}
			return false;
		}).parent().toggle();
		$(headerRow).toggleClass("closed");
		updateTableToggle();
		return false;
	})
	
	$("table.materials tbody tr:not(:first-child) th p a").click();
	
	initOpen();
	
});
