// JavaScript Document
var menuItems;

$(document).ready(function() {
	
	menuItems = [];
	
	$('.menu a[href*=#]').each(function(index) {
	    menuItems.push([this.hash, ($(this.hash).offset().top-30)]);
	}); 
	             
    $('a[href*=#]').click(function(e) {
        var duration=1000;
        var target=$(this.hash).offset().top-30;
        $('html, body').animate({scrollTop: target}, duration, "swing", updateMenu);
        deselectAllMenuItems();
        $(this).addClass('selected');
        e.preventDefault();
    });
    
    $(document).scroll(function() {
		var n = $("html, body").queue("fx");
		if(n.length==0) {
    		updateMenu();
		}
	});
	
	updateMenu();
	              
});

function deselectAllMenuItems() {
	$('.menu a[href*=#]').each(function(index) {
		$(this).removeClass('selected');
	}); 
}

function updateMenu() {
	var scrollTopY = $(document).scrollTop();
	var bottomY = $(document).height()-$(window).height();
	for (var i = 0; i<menuItems.length; i++) {
		var currentName = menuItems[i][0];
		var currentItemTop = ($(currentName).offset().top-30);
		var nextItemTop = 1;
		if(i<(menuItems.length-1)) {
			nextItemTop = ($(menuItems[i+1][0]).offset().top-30);
		}
		
		if(scrollTopY==bottomY && menuItems.length==(i+1)) {
			$('.menu a[href='+currentName+']').addClass('selected');
		}else if(scrollTopY>=currentItemTop && scrollTopY<nextItemTop && scrollTopY!=bottomY) {
			$('.menu a[href='+currentName+']').addClass('selected');
		}else{
			$('.menu a[href='+currentName+']').removeClass('selected');
		}
		
	}
}

