$(function() {
	$('#headerRotator').cycle({
		fx:      'fade', 
		speed:    3000, 
		timeout:  7500,
		sync: false
	});
	
	$("div.box, div.article").each(function() {
		var link = $(this).find("a").attr("href");
		$(this).click(function(){
			window.location = link;
		});
		$(this).css({cursor: "pointer"});
	});
	
	
	$("a[target='gallery']").each(function() {
		$(this).click(function(event){
			showGallery($(this).attr("href"));
			return false;
		});
	});
	
});

// Fader ut, viser galleri
function showGallery(url) {
	$.dimScreen(1000, 0.9, function() {
		$("#gallery .wrapper").addClass("loading");
		$("#gallery").fadeIn(1000).css({top: ($(window).height() - $("#gallery").height() - 40) / 2 + "px"});
		
		$("#gallery .wrapper").load(url + "?" + (Math.random()*1000), initGallery);		
	});
}	


function initGallery() {

	$("#gallery .wrapper").removeClass("loading");

	$("#gallery p.close a").each(function() {
		$(this).click(function(){
		    hideGallery();
		});
	});	
	
	$("#gallery .thumbnails li a").each(function() {
		$(this).hover(function() {
			changeImage($(this).attr("href"));
		}, function(){});
		$(this).click(function() {
			return false;
		});
	});
	
	displayImageIfLoaded();
}


function hideGallery() {
	$("#gallery").fadeOut(1000, function() {
		$.dimScreenStop({});
	});
}

function changeImage(imageUrl) {
	
	var img = $("#gallery .image img");
	var container = $("#gallery .image");
	var opacity = img.css("opacity");
	var speed = 1000;
	
	var newImage = new Image();
	
	$("#gallery .image img:animated").stop();
	
	if (img.attr("src") == imageUrl) {
		speed = Math.ceil((1 - (opacity / 1)) * 1000);
		img.attr("src", imageUrl).fadeTo(speed, 1);
		return;
	}
	
	speed = Math.ceil((opacity / 1) * 1000); 
	img.fadeTo(speed, 0, function() {
		$(newImage).attr("src", imageUrl).fadeTo(1,0.001);
		container.html($(newImage));
		displayImageIfLoaded();
	});
}

function displayImageIfLoaded() {
	
	var container = $("#gallery .image");
	var img = $("#gallery .image img");
	
	if (img.height() > 100) {
		container.removeClass("loading");
		img.css({
			marginTop: ((408 - img.height()) / 2) + "px"
		});
		img.fadeTo(1000,1);		
	}	
	else { 
		container.addClass("loading");
		setTimeout(displayImageIfLoaded, 50);
	}
	
}