$(document).ready(function() {
	adjustMetaNavSelection($("#MetaItems"));
	adjustMetaNavSelection($("#Languages"));
});

$(window).load(function() {
	startCrossFadeSideBar()
	fitMainToChildren();
	positionFooter();
});

$(window).resize(function() { positionFooter(); });

/*** metanav selection ***/
function adjustMetaNavSelection(container) {
	var sel = $(container).find("div.selected");
	if(sel.length == 0)
		return;
	
	var prv = $(sel).prev();
	var nxt = $(sel).next().next();
	
	var width =  $(nxt).position().left - $(prv).position().left  + 2;
	$(sel).css({
		"left": $(prv).position().left,
		"width" : width,
		"visibility" : "visible"
	});
}

/*** side bar cross fading ***/
var sleep = 4000;
var fade = 2000;

function startCrossFadeSideBar() {
	$("#Picture img").css("opacity", 0);
	$("#Picture img:first").css("opacity", 1).addClass("curVisible");
	setTimeout(crossFadeSideBar, sleep);
}

function crossFadeSideBar() {
	var cur = $(".curVisible");
	var next = cur.next();
	if(next.length == 0)
		next = $("#Picture img:first");
	
	cur.removeClass("curVisible").animate({opacity: 0}, fade);
	next.animate({opacity: 1}, fade, function() {
		next.addClass("curVisible");
		setTimeout(crossFadeSideBar, sleep);
	});
}

/*** footer ***/
var footer;
var footerTopStart;
 
function positionFooter() {
	if(!footer) {
		footer = $("#Footer");
		footerTopStart = $(footer).offset().top;
	}

	var footerOffset = $(footer).offset();
	var footerHeight = $(footer).height();
	var winHeight = $(window).height();

	var newTop = Math.max(
		footerTopStart,
		winHeight - footerHeight - parseInt($(footer).css("margin-top"))
	);

	if(!newTop || newTop == Number.NaN)
		return;

	$(footer).css({  
		position : "absolute",
		top : newTop,
		width: $(footer).width()
	});
}

/*** fitParentToChlildren ***/
function fitMainToChildren() {
	var main = $("#Main");
	var maxHeight = 0;
	$(main).children().each(function(i) {
		maxHeight = Math.max(maxHeight, $(this).position().top + $(this).outerHeight(true));
	});

	// hack to take side bar pictures (position: absolute) into account	
	if($("#Main #Picture img").length > 0)
		maxHeight = Math.max(maxHeight, 392 + 58);

	$(main).css({"height" : maxHeight});
}

function getMaxHeight(container) {
	var maxHeight = 0;
	$(container).children().each(function(i) { maxHeight = Math.max(maxHeight, $(this).height()); });
	return maxHeight;
}
