$(function () {
	var loopTimer = {};
	jQuery.changeFocusUnderside = function(to) {
		//CLEARS EXCISTING TIMEOUTS 
		$.clearTimer(loopTimer);

		//SELECTS THE CURRENT IMAGE (FADE IN) AND FADES OTHERS OUT (TIME IN MILISECONDS)
		var billede = $("#animation-image" + to + "");
		billede.stop().fadeTo(400,1);
		var andrebilleder = $("#undersidekarusel-billeder img");
		andrebilleder.not(billede).stop().fadeTo(1000,0);


		//SELECTS THE CURRENT DOT AND CHANGES ITS SRC, CHANGES ALL OTHERS BACK 
		var dot = $("#underside-selector #knap" + to + "");
		var alldots = $("#underside-selector img");
		valgt="fileadmin/templates/aarhusvalgmenighed_dk/images/underside-dot-valgt.png";
		ikkevalgt="fileadmin/templates/aarhusvalgmenighed_dk/images/underside-dot.png";
		alldots.not(dot).attr("src",ikkevalgt);
		dot.attr("src",valgt);

		//ANIMATES TEXT TO TOP:0 LEFT:0. OTHERS OUT...
		var textbox = $("#undersidekaruseltekst span.tekst" + to + "");
		window.thislink = textbox.find("a").attr("href");
		var alltextboxes = $("#undersidekaruseltekst span");
		alltextboxes.not(textbox).stop().animate({ 
		left: "-200px",
		opacity: 0
		}, 800 );
		textbox.stop().animate({ 
		left: "10px",
		opacity: 1
		}, 800 );
		
		//COUNTS THE DOTS AND DETERMINES NEXT AUTO-SHIFT AND TIMEOUT (5000ms)
		var antal = alldots.length;
		var nyFocus = parseInt(to)+1;
		if(nyFocus > antal) { var nyFocus = 1; }
		loopTimer = $.timer(5000,"$.changeFocusUnderside(" + nyFocus + ")");	
	}	
	$("#indholdWrap #undersidekarusel #overlay").click(function() {
		parent.location=window.thislink;
	});
	
	//MAKES THE DOTS CLICKABLE 
	$("#underside-selector img").click(function() {
		var ny = this.id.replace(/knap/, "");
		$.changeFocusUnderside(ny);
	});
	$(".animation-tekst-box-inner p").click(function() {
		var link = $(this).find("a:first").attr("href");
		parent.location=link;
	});
			
	//RUNS THE changeFocus FUNCTION AND SETS TIMEOUT TO FIRST SHIFT
	$("#undersidekaruseltekst span.tekst1").css({ "left": "10px", "opacity": "1" });
	$.changeFocusUnderside(1);
	loopTimer = $.timer(5000,"$.changeFocusUnderside(2)");	
	
});
