jQuery(
	function($) {
		var
			$body = $('body').addClass('js'),

			// retrieve language from body class
			regExpLanguage = /language_([a-z]{2})/,
			matchesLanguage = $body.attr('class').match(regExpLanguage),
			language = matchesLanguage ? matchesLanguage[1] : 'en',
			$sheet = $('#sheet'),
			$subNavigation = $('.navigation.sub', $sheet);

		// activate stretch images
		$('img.stretch').stretch();

		// activate sub-navigation
		(
			function() {
				$subNavigation.add($('.content-container', $sheet))
					.bind(
						'click',
						function(e) {
							var
								$target = $(e.target),
								$content,
								$listItem,
								position;

							if ($target.is('a[href^=#]')) {
								$content = $('.content' + $target.attr('href'), $sheet);
								if ($target.hasClass('print')) {
									window.print();
								} else if ($target.hasClass('close')) {
									$('a[href=' + $target.attr('href') + ']', $subNavigation).trigger('click');
								} else {
									// show clicked item
									$listItem = $target.closest('li');
									if ($listItem.hasClass('active')) {
										$listItem.removeClass('active');
										$content.fadeOut('slow');
									} else {
										// hide other already active items
										$('li.active a', $subNavigation).trigger('click');

										$listItem.addClass('active');
										position = $target.position();
										position.right = $target.offsetParent().width() - position.left;
										position.top -= 35;

										$content
											.css(
												{
													right: position.right,
													top: position.top
												}
											)
											.fadeIn('slow');
									}
								}
								return false;
							}
						}
					);
			}
		)();

		// show relevant content pane if url has an anchor
		(
			function() {
				var matches = /#[a-z_0-9]+$/.exec(window.location.href);
				if (matches && matches.length) {
					$('a[href=' + matches[0] + ']', $subNavigation).trigger('click');
				}
			}
		)();

		// read and set lightbox parameters
		(
			function() {
				var o =
					{
						download_link: false,
						show_helper_text: false,
						show_linkback:	false
					},
					$gallery = $('.gallery');

				if ($gallery.length) {
					o = $.extend(o, $gallery.metadata())
					$.Lightbox.construct(o);
				}
			}
		)();
	}
);
