$(document).ready(function() {
	
	/**
	 * iPhone | iPod Detection
	 *
	 */
	
	function isiPhone(){
	    return (
	        (navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1)
	    );
	}
	
	/**
	 * Automatic height of sections
	 *
	 */
	
	var sectionHeight;
	
	$("section.cat").each(function() {
		sectionHeight = 0;
		$(this).children(".layer").each(function(){
			sectionHeight += $(this).height();
		});
		$(this).height(sectionHeight);
	});
	
	var hash,
		catHash,
		location,
		anchor,
		pageOffset,
		scrollPos;
	
	/**
	 * Hash linking
	 *
	 */
	
	if ( top.location.hash ) {
		hash = top.location.hash.substring(3);
		catHash = hash.split('/')[1];
		
		if ( catHash != undefined )
			scroll($("#"+catHash), false, 0);
		else
			scroll($("#"+hash), false, 0);
			
		if ( hash != "i" && !isiPhone() )
			$('#top').slideDown();	
	}
	
	var currentHash,
		url,
		historyBack,
		sl;
		
	if ( history && history.pushState )
		sl = "/";
	else
		sl = "!/";
	
	$(window).scroll(function() {
		
		hash = $('.layer:in-viewport').attr('id');
		catHash = $("#"+hash).parent('section').attr('id');
		
		if ( currentHash != hash ) {
			
			// Show/Hide navigation bar
			if ( hash != "i" && !isiPhone() ) {
				$('#top').slideDown();
			} else if ( hash == "i" && !isiPhone() ) {
				$('#top').slideUp();
			}
			
			if ( catHash != undefined ) {
				url = sl + catHash + "/" + hash;
				
				// set/remove active state of links
				$('#top ul li').removeClass("active");
				$('li.'+catHash).addClass("active");
				$('#top select option[value="'+catHash+'"]').removeAttr('selected');
				$('#top select option[value="'+catHash+'"]').attr('selected', 'selected');
				
			} else {
				url = sl + hash;
				
				// set/remove active state of links
				$('#top ul li').removeClass("active");
				$('li.'+hash).addClass("active");
				$('#top select option[value="'+catHash+'"]').removeAttr('selected');
				$('#top select option:first-child').attr('selected', 'selected');
			}
			
			// If history API is available
			if ( history && history.pushState ) {
				
				if ( !historyBack ) 
					window.history.pushState(hash, hash, url);
				
			// Fallback	to top.location.hash
			} else {
				
				$(window).off('hashchange', goToHash);
				
				top.location.hash = url;

				setTimeout( function() {
					$(window).on('hashchange', goToHash);
				}, 0);
			}
	
			currentHash = hash;
		}
		
		// Hide/Show images for better performance
		$(".layer:below-the-fold").find('img').hide();
		$(".layer:above-the-top").find('img').hide();
		$(".layer:in-viewport").find('img').show();
		
	});
	
	window.onpopstate = function(event) {
		hash = event.state;
		if ( hash != undefined ) {
			scroll($("#"+hash), true, 0);
			historyBack = true;
		}
	};
	
	function goToHash() {
		hash = top.location.hash.substring(3);
		catHash = hash.split('/')[1];
		
		if ( catHash != undefined )
			scroll($("#"+catHash), true, 0);
		else
			scroll($("#"+hash), true, 0);
	}
	
	/**
	 * Mobile select menu
	 *
	 */
	
	$("#top select").change(function() {
		catHash = $(this).attr('value');
		scroll($("#"+catHash), false, 0);
	});
	
	/**
	 * Scroll behaviour
	 *
	 */
	
	//$("a[href*='#']").live('click', function(e) {
	$("a.animate").live('click', function(e) {
		e.preventDefault();
		anchor = $(this).attr('href').split('#')[1];
		scroll($("#"+anchor), true, 0);
	});
	
	$("a.jump").live('click', function(e) {
		e.preventDefault();
		anchor = $(this).attr('href').split('#')[1];
		scroll($("#"+anchor), false, 0);
	});
	
	$("li.active a").live('click', function(e) {
		e.preventDefault();
	});
	
	function scroll(selector, animate, viewOffset) {
		
		try {
			pageOffset = selector.offset();
			scrollPos = pageOffset.top - viewOffset;
		} catch(e) {
			top.location.hash = "#!/i";
		}
		
		if ( animate ) {
			$('html, body').animate({ scrollTop : scrollPos + 'px' }, {
		        duration: '800',
		        easing: 'easeInQuart',
				complete: function() { historyBack = false; }
			});			
		} else {
			$('html, body').scrollTop( scrollPos );
			$('html, body').animate({ scrollTop : scrollPos + 1 + 'px'}); // tigger lazyload
		}
		
	}
	
	/**
	 * Key Navigation
	 *
	 */
	
	var articles,
		index,
		view,
		next,
		prev;
	
	$(document).keydown(function(e) {
		
		view = $('.layer:in-viewport');
		articles = $('article.layer');
		index = articles.index(view);
		prev = index <= 0 ? $() : articles.eq(index-1);
		next = articles.eq(index+1);
		
		if ( e.keyCode == 37 || e.keyCode == 38 ) {
			
			e.preventDefault();
			
			if ( prev.attr('id') != undefined )
				scroll(prev, true, 0);
		}
			
		if ( e.keyCode == 39 || e.keyCode == 40 ) {
			
			e.preventDefault();
			
			if ( next.attr('id') != undefined )
				scroll(next, true, 0);
		}
	});
	
	/**
	 * Resizing images
	 *
	 */
	
	var sw;
	$(window).resize(function(){
		sw = $(window).width();
		if ( !isiPhone() && sw < 1640 ) {
			$('article.layer img').css({
				maxHeight: $('article.layer').height() * 0.8,
				maxWidth: $('article.layer').width() * 0.8
			});
		}
	});
	
	$(window).resize();
	
	$(".layer img").lazyload({
		effect: "fadeIn"
	});
	
});
