(function($) {
	$(document).ready(function() {
		var getRelatedTagsUri = '/client/index.php?module=client_leidraad&method=getrelatedtag'

		$('div#leidraad-structure a').bind('relate', function() {
			var self = this;
			var tag = $(this).attr('tag');
			var object = $(this).attr('object');

			$.getJSON(getRelatedTagsUri, { tag: tag }, function(relatedTag) {
				if (relatedTag == 'Opdracht') {
					$('div#leidraad-structure a[to!=' + object + '][tag=' + relatedTag + ']').each(function() {
						$(this).parents('li:first').hide();
					});
					$('div#leidraad-structure a[to=' + object + '][tag=' + relatedTag + ']').each(function() {
						$(this).parents('li:first').show();
					});
				}
				else if (relatedTag == 'Rol') {
					$('div#leidraad-structure a[tag=' + relatedTag + '][object=' + $(self).attr('to') + ']').trigger('relate');
				}
			});
		});

		// simulate the click event if a page matches the href of the anchor.
		$('div#leidraad-structure a').each(function() {
			if (window.location.pathname == $(this).attr('href')) {
				$(this).trigger('click');
			}
		});

		// do not bubble up so other elements receive the click.
		$('div#leidraad-structure a').click(function(e) {
			e.stopPropagation();
		});

		// expand and contract the elements.
		$('div#leidraad-structure > ul > li > ul li.has-children').click(
			function(e) {
				var childIndicator = $('span.child-indicator:first', this);
				if (childIndicator.hasClass('contracted')) {
					childIndicator.removeClass('contracted');
					childIndicator.addClass('expanded');
				}
				else if (childIndicator.hasClass('expanded')) {
					childIndicator.removeClass('expanded');
					childIndicator.addClass('contracted');
				}
				$('> ul', this).toggle();
				e.stopPropagation();
			}
		);
	});
})(jQuery);