$(document).ready(function(){
	
	$('#tree li:has(ul)').prepend('<span class=\'tree-expand\'>+ </span>').children('ul').hide();
	
	$('#tree li > span').toggle(
		function() { $(this).text('–').removeClass('tree-expand').addClass('tree-collapse').parent('li').children('ul').show();	},
		function() { $(this).text('+').removeClass('tree-collapse').addClass('tree-expand').parent('li').children('ul').hide();	}
	);
	
	$('#tree li:has(ul input:checkbox:checked) > span').click();
	
	$('#tree li input:checkbox').change(function() {

		if($(this).attr('checked')) {
			var parent = $(this).parent('li');
			parent.find('ul input:checkbox').attr('checked', true);
			parent.find('span.tree-expand').click();

			// check parent if all siblings are checked
			var uncheckedSiblings = parent.parent('ul').find('>li>input:checkbox:not(:checked)').length;
			if(uncheckedSiblings === 0)
				parent.parent('ul').parent('li').children('input:checkbox').attr('checked', true);

		} else {
			
			$(this)
				.parents('#tree li')
				.children('input:checkbox')
				.not(this)
				.attr('checked', false);
				
			$(this)
				.parent('li')
				.find('input:checkbox')
				.not(this)
				.attr('checked', false);
		}
	
	});

});
