$(function() {
	$("body").append("<div id='Window-Bottom' style='position:fixed;bottom:0px;height:0;width:1;'></div>");
	var archiveTop = getOffsetTop($("#archives")[0]);
	var breadCrumbsTop = getOffsetTop($("#breadcrumbs")[0])-5;
	var $windowsBottom = $("#Window-Bottom")[0];
	var minArchiveSize = 100, maxArchiveSize = getOffsetTop($("#pied_page")[0]) - archiveTop - 30;
	if (maxArchiveSize < 300) maxArchiveSize = 300;

	function loadItem(nid) {
		if (!nid) nid = $("#firstItem a")[0].href.replace(/^[^#]+#/, '');
		if ($.historyCurrentHash.length > 0) $("#selected-item-content").slideUp('fast');
		
		$(".selected-item").removeClass("selected-item");
		var $selectedItem = $("#item-"+nid);
		$selectedItem.addClass("selected-item");

		if (getScrollTop() > breadCrumbsTop) {
			var $archives = $("#archives .block-content-top");
			var visHeight = $windowsBottom.offsetTop + breadCrumbsTop - archiveTop;
			var itemHeight = $selectedItem[0].clientHeight;
			var y = $selectedItem[0].parentNode.offsetTop - (visHeight > itemHeight ? visHeight-itemHeight : 0)/2;
			if (y > $archives[0].scrollHeight - $archives[0].clientHeight) {
				$.scrollTo(breadCrumbsTop,800, { 'onAfter':function(){
					adjustArchivesHeight();
					$archives.scrollTo(y, 500);
					}});
			} else {
				$.scrollTo(breadCrumbsTop,800);
				$archives.scrollTo(y, 800);
			}
		}

		$("#selected-item-content").load(
				$.GBN.articleSource + "?nid=" + nid,
				function() {
					$("#selected-item-content").slideDown('fast');
				});
	}
	$.historyInit(loadItem);
	loadItem();

	$(".archive-item > .title").click(function(){
		$.historyLoad(this.href.replace(/^.*#/, ''));
		return false;
	});

	// function to adjust height of the archives div
	function adjustArchivesHeight() {
		var windowHeight = $windowsBottom.offsetTop;
		var h = windowHeight + getScrollTop() - archiveTop - 20;
		h = h < minArchiveSize ? minArchiveSize : (h > maxArchiveSize ? maxArchiveSize : h);
		$("#archives .block-content-top").css('max-height', h);
	}

	// adjust height of archives div when resizing the window
	var resizeTimer = null;
	function adjust_archive_height(e) {
		if (resizeTimer) clearTimeout(resizeTimer);
		resizeTimer = setTimeout(adjustArchivesHeight, 200);
	}
	$(window).resize(adjust_archive_height);
	$(window).scroll(adjust_archive_height);

	// adjust height of archives div right after loading the document
	adjustArchivesHeight();
});
