var timer;
var active;
$(document).ready(function(){
	active = $("#subnav a.active").index("#subnav a");
	if($("body").hasClass("noindex")){
		if($("#subnav a.active").index("#subnav a") < 4){
			$("#subsubnav section").eq($("#subnav a.active").index("#subnav a") + 1).show();
		}
		else{
			$("#subsubnav section").eq(0).show();
		}
	}
	else{
		$("#subsubnav section").eq(0).show();
	}
	$("#subnav a").click(function(){
		if($(this).index("#subnav a") < 4){
			$("#subsubnav section").hide();
			$("#subnav a.active").removeClass("active");
			$("#subsubnav section").eq($(this).index("#subnav a") + 1).show();
			$("#subnav a").eq($(this).index("#subnav a")).addClass("active");
			return false;
		}
	});
	$("#subnav,#subsubnav").mouseenter(function(){
		clearTimeout(timer);
	});
	$("#subnav,#subsubnav").mouseleave(function(){
		timer = setTimeout("release()", 500);	
	});
	if($("article section").length > 1){
		$("article nav #next").show();
		$("article nav #next").click(function(){
			var activeindex = $("article section").index($("article section.show"));
			if(($("article section").length - 1) != activeindex){
				$("article section.show").next().addClass("show");
				$("article section").eq(activeindex).removeClass("show");
			}
			else{
				$("article section.show").removeClass("show");
				$("article section").eq(0).addClass("show");
			}
		});
		$("article nav #back").click(function(){
			var activeindex = $("article section").index($("article section.show"));
			if(activeindex > 0){
				$("article section.show").prev().addClass("show");
				$("article section").eq(activeindex).removeClass("show");
			}
			else{
				$("article section.show").removeClass("show");
				$("article section").eq($("article section").length - 1).addClass("show");
			}
		});
		$("article nav a").click(function(){
			var activeindex = $("article section").index($("article section.show"));
			var last = $("article section").length - 1;
			console.debug(activeindex + " " + last)
			if(activeindex == last){
				$("article nav #back").show();
				$("article nav #next").hide();
			}
			else if(activeindex == 0){
				console.debug('2')
				$("article nav #back").hide();
				$("article nav #next").show();
			}
			else{
				$("article nav #back").show();
				$("article nav #next").show();
			}
		});
	}
});
function release(){
	clearTimeout(timer);
	if($("body").hasClass("noindex")){
		$("#subsubnav section").hide();
		$("#subnav a.active").removeClass("active");
		if(active > -1){
		$("#subnav a").eq(active).addClass("active");
		}
		if($("#subnav a.active").index("#subnav a") < 4){
			$("#subsubnav section").eq(active + 1).show();
		}
		else{
			$("#subsubnav section").hide();
			$("#subsubnav section").eq(0).show();
		}
	}
	else{
		$("#subsubnav section").hide();
		$("#subnav a.active").removeClass("active");
		$("#subsubnav section").eq(0).show();
	}
}
