var sectionTopOffset = -92;
var fixedPositionOffset = 10;
var bottomMarginOffset = -49;

$(document).ready(function ( ) {
	
	var sections = $("section");
	
	$(window).scroll(function( ) {
		
		updateNavPosition( );
		
		var scrollTop = $(this).scrollTop( );
		
		var update = false;
		for(var i = 0; i < sections.length; i++) {
			
			if(i < (sections.length - 1)) {
				
				var topSection = $(sections[i]);
				var bottomSection = $(sections[i + 1]);
				
				scrollTop += fixedPositionOffset; 
				
				if(scrollTop > (topSection.offset( ).top + bottomMarginOffset) && scrollTop < bottomSection.offset( ).top + bottomMarginOffset) {
					update = true;
					break;
				}
				
			} else {
				
				var topSection = $(sections[i]);
				if(scrollTop > (topSection.offset( ).top + bottomMarginOffset)) {
					update = true;
					break;
				}
				
			}
			
		}
		
		if(update) {
			
			var id = topSection.attr("id");
			$("nav .active").removeClass("active");
			$("nav ." + id).addClass("active");
			
		}
		
		/* DEBUG NAV
		$("section").each(function( ) {
			var top = $(this).offset( ).top;
			var id = $(this).attr("id");
			$("#" + id + "Line").css("top", (top + bottomMarginOffset) + "px");
		});
		*/
		
	});
	
	$(".scoller").click(function( ) {
		var href = $(this).attr("data-href");
		scrollToSection(href);
	});
	
	$("nav p").click(function( ) {
		$.scrollTo(0, {duration: 400, offset: { top: 0, left:0 } });
	});
	
	$(window).resize(function( ) {
		updateNavPosition( );
	});
	
});

function updateNavPosition( ) {
	
	var navStartPositionTop = 182;
	var scrollTop = $(this).scrollTop( );
	
	if($.browser.msie && (parseInt($.browser.version, 10) >= 8)) {
	
		$("nav").css("position", "fixed");
	
		var top = $("div.main").offset( ).top;
	
		if(scrollTop > $("#introduction").offset( ).top) {
			$("nav").css("top", "10px");
		} else {
			var t = navStartPositionTop - scrollTop;
			$("nav").css("top", t + "px");
		}
	
		var left = $("div.main").offset( ).left;
		$("nav").css("left", left + "px");
	
	} else {
		
		if(scrollTop > $("#introduction").offset( ).top) {
			$("nav").css("position", "fixed");
			$("nav").css("top", "10px");
		} else {
			$("nav").css("position", "absolute");
			$("nav").css("top", "auto");
		}
	
	}
	
}

function scrollToSection(id) {
	$.scrollTo(id + " .box", {duration: 400, offset: { top: sectionTopOffset, left: -150 } });
}
