var menuItems;
var topMargin = 0;

$(document).ready(function() {
	
	menuItems = [];
	
	$('.menu a[href*=#]').each(function(index) {
		if($(this.hash).offset()) {
	    	menuItems.push([this.hash, ($(this.hash).offset().top-30)]);
	    }
	});
	
	/* OPEN ALL EXTERNAL LINKS IN A NEW WINDOW */
	
	
//	$("a[href^='http:']").not("[href*='"+document.domain+"']").attr('target','_blank');
	
	      
    $('a[href*=#]').click(function(e) {
        var duration=1500;
        var target=$(this.hash).offset().top-topMargin+1;
        $('html, body').animate({scrollTop: target}, duration, "swing", updateMenu);
        deselectAllMenuItems();
        $(this).addClass('selected');
        pageTracker._trackEvent('Navigation', 'Goto', this.hash);
        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-topMargin);
		if(i==0) {
			currentItemTop = 0;
		}
		var nextItemTop = 1;
		if(i<(menuItems.length-1)) {
			nextItemTop = ($(menuItems[i+1][0]).offset().top-topMargin);
		}
		
		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');
		}
		
	}
}
