﻿/*
	+++ VERTICAL NAVIGATOR +++
	Marcello Cosentino - marcello@2mlab.com - 2mlab.com 2011
*/
var $window = $(window);
var $nav = $('nav.vertical');
var selected_id = '';
var i;

/* LOOK FOR SECTIONS and CREATE NAV ELEMENTS */
var $sections = $('[rel=vertical-nav]');
if ($sections.size() > 0) {
	var $ul = $('<ul></ul>');
	var $li;
	var $a;
	i = 0;
	$sections.each(function () {
		var section_id = $(this).attr('id');
		$li = $('<li></li>');
		//label (taken from the header of the section)
		var $h1 = $(this).find('h1');
		if ($h1.size() > 0) {
			$li.append($('<h1><span>' + $h1.html() + '</span></h1>'));
		}
		//the anchor to the section
		$a = $('<a>' + section_id + '</a>');
		$a.attr('id', section_id + '-anchor');
		$a.attr('href', '#' + section_id);
		$li.append($a);
		$ul.append($li);
		i++;
	});
	$nav.append($ul);
}

var $list_li = $nav.find('li');
var $list_a = $list_li.find('a');

/* NAVIGATOR HOVER */
function fadeInFunc() {
	$(this).find('h1').stop().show().animate({
		opacity: 1,
		right: 20
	}, 150);
}

function fadeOutFunc() {
	$(this).find('h1').stop().animate({
		opacity: 0,
		right: 10
	}, 150, function () { $(this).hide(); });
}

$list_li.each(function () {
	$(this).hover(fadeInFunc, fadeOutFunc);
	$(this).find('h1').click(function(){ $(this).siblings('a').click(); });
});

/* SCROLL TO SECTIONS */
$list_a.click(function (event) {
	event.preventDefault();
	var $section = $($(this).attr('href'));
	$('html, body').stop().animate({
		scrollTop: $section.offset().top - ($(window).height() - $section.outerHeight()) / 2
	}, 2100, 'easeInOutExpo');
});

/* DETECT THE ACTIVE SECTION */
//Nota: la sezione attiva è quella su cui cade la metà (in altezza) della finestra (viewport)
$list_a.each(function () {
	var $anchor = $(this);
	var $section = $($anchor.attr('href'));
	var topOffset = $section.offset().top;
	var bottomOffset = topOffset + $section.outerHeight();

	var scrollFunc = function () {
		var halfViewPortTopOffset = $window.scrollTop() + $window.height() / 2;
		if (topOffset < halfViewPortTopOffset && bottomOffset > halfViewPortTopOffset) {
			if ($anchor.attr('id') != selected_id) {
				selected_id = $anchor.attr('id');
				$list_a.not('#' + selected_id).parent().removeClass('selected');
				$anchor.parent().addClass('selected');
			}
		}
	};

	$(window).scroll(scrollFunc);

	//init
	scrollFunc();
});

/* ANIMAZIONE INIZIALE (mostra navigator e label attiva) */
if ($sections.size() > 0) {
	//show the navigator
	$nav.delay(500).fadeIn(2000, function () {
		var $label = $('.vertical .selected h1');
		
		//show the selected element for a while
		$label.stop().show().animate({
			opacity: 1,
			right: 20
		}, 150);

		$label.delay(2000).animate({
			opacity: 0,
			right: 10
		}, 150, function(){ $(this).hide(); });

	});
}

