$(document).ready(function(){

	// show nav2
	$('.nav1>li').hover(
		function(){
			$(this).find('.nav2').show();
			$(this).toggleClass('hovered');
			var parentTop = findPos($(this).get(0));
			$(this).find('.nav2 li:first').css('margin-top', parentTop);
		},
		function(){
			$(this).find('.nav2').hide();
			$(this).toggleClass('hovered');
		}
	);
	
	// show nav3
	$('.nav2>li.parent').hover(
		function(){
			$(this).find('.nav3').show();
			$(this).toggleClass('hovered');
			var parentTop = findPos($(this).get(0));
			var childTop = parentTop;
			var childHeight = $(this).find('.nav3>li:first').get(0).offsetHeight;
			var childCount = $(this).find('.nav3>li').length
			while(parentTop + (childHeight * childCount -1) > 456){
				parentTop -= childHeight;
			}
			if(parentTop < 0) parentTop = 0;
			$(this).find('.nav3 li:first').css('margin-top', parentTop);
		},
		function(){
			$(this).find('.nav3').hide();
			$(this).toggleClass('hovered');
		}
	);
	
	// show preview
	$('.nav3>li').hover(
		function(){
			$(this).find('.preview').show();
			$(this).toggleClass('hovered');
			// load preview data dynamically with progress indicator (spinner)
		},
		function(){
			$(this).find('.preview').hide();
			$(this).toggleClass('hovered');
		}
	);

});

// find position
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return curtop;
}