﻿$(function() {
	var inAnimatedScroll = false;

	// which sections are on the page?
	var sections = []
	$("body div div>section,body>section").each(function() {
		sections.push({ id: $(this).attr('id'), top: this.offsetTop, el: $(this) })
	})

	$("header nav ul ul").each(function() {
		$(this).css("background-position", "0px " + ($(this).height() + 8) + "px")
	})

	var ixxx = 0;
	// update menu when user scrolls
	var updateMenu = function() {
		var cur = $(window).scrollTop();
		var active = sections[0];
		for (var i = 0; i != sections.length; i++) {
			if (sections[i].top <= (cur + 20)) {
				active = sections[i];
			}
		}

		var elem = $(document.body);
		var diff = elem[0].scrollHeight - cur - $(window).height();
		if (Math.abs(diff) < 100) {
			active = sections[sections.length - 1]
		}

		$("header nav .selected").removeClass('selected');
		var a = $("header nav a[rel='" + active.id + "']").addClass('selected');
		if (!inAnimatedScroll) {
			a.parents('li').addClass('selected')
		}
		$("header nav ul ul").each(function() {
			var isSelected = $(this).parent().hasClass("selected");
			if (isSelected) {
				$(this).parent().find(">a").addClass('hidebar')
			} else {
				$(this).parent().find(">a").removeClass('hidebar')
			}
		})
	}
	$(window).scroll(updateMenu)
	updateMenu();

	// scroll down when user clicks
	$("header nav a").click(function() {
		var id = $(this).attr('rel');
		for (var i = 0; i != sections.length; i++) {
			if (sections[i].id == id) {
				inAnimatedScroll = true;
				$('html, body').stop().animate({ scrollTop: sections[i].top }, {
					duration: 1800,
					easing: 'easeOutQuart',
					complete: function() {
						inAnimatedScroll = false;
						updateMenu()
					}
				});
				return false;
			}
		}
		return true;
	});

	// process each mini gallery
	$(".minigallery").each(function() {
		var gallery = $(this)
		// align each content part (pictures)
		var i = 0;
		gallery.find(".minigallerycontents>*").each(function() {
			var content = $(this)
			var l = content.parent().width() * i++
			content.css({ position: 'absolute', left: l + 'px' })
			$('<div class="gallerycontrol' + (i == 1 ? " active" : "") + '"></div>').appendTo(gallery.find(".minigallerycontrols")).click(function() {
				gallery.find(".gallerycontrol.active").removeClass("active")
				$(this).addClass("active")
				gallery.find(".minigallerycontents").animate({ scrollLeft: l })
			})
		})
	})
})
