var $content, $pages, $pageLinks, pageLinkHtml, pageIndex;
$(document).ready(function()
{
	$content = $("#content");
	$pages = $("#pages").children("div");
	$pageLinks = $("#rightpanel h2:first span");
	setContentHeight();
	initPageLinks();
	changePage(1);
	$("#loaderBack").fadeOut(300);
});
$(window).scroll(function()
{
	scrollBackground();
});
$(window).resize(function()
{
	setContentHeight();		
	scrollBackground();
	changePage(pageIndex); //Update pages that do not automatically resize
});

function scrollBackground() {
	$("#back").offset({ top: 0 });		
}
function setContentHeight() {
	winH = $(window).height();
	winW = $(window).width();
	minH = Math.max(winW * 2 / 5, maxChildHeight($content) + 20/*margin*/);
	maxH = winW * 10 / 16;		
	h = Math.max(minH, Math.min(winH, maxH)); //Height between max and min
	$content.height(h);
}
function maxChildHeight($el)
{
	var h = 0;
	$el.children().each(function(i, el)
	{
		h = Math.max(h, $(el).outerHeight());
	});
	return h;		
}
function initPageLinks()
{
	$pageLinks.each(function(i, el)
	{
		$(el).click(function() {
			changePage(i);
			setContentHeight(); //Pages can vary in size
		});
	});
}
function changePage(index)
{
	if (index != pageIndex)
	{
		//Update links
		if (!isNaN(pageIndex))
			$($pageLinks.get(pageIndex)).html(pageLinkHtml);		
		pageIndex = index;
		$pageLink = $($pageLinks.get(index));
		pageLinkHtml = $pageLink.html();
		$pageLink.html($pageLink.text());
		
		//Show correct page
		$pages.each(function(i, el)
		{
			if (i == index)
				$(el).show();
			else
				$(el).hide();			
		});
	}
	
	if (index == 1) //Facebook stream (does not support liquid layout)
	{
		w = Math.floor($("#rightpanel").width());
		h = 395; //Max height is 395 due to Facebook bug
		$($pages.get(index)).html('<iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2FDescendOfficial&amp;width=' + w + '&amp;colorscheme=dark&amp;show_faces=false&amp;stream=true&amp;header=false&amp;height=' + h + '" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:' + w + 'px; height:' + h + 'px;" allowTransparency="true"></iframe>');
	}
}
