var load_next = true;
var x_target = 0;
var animation_interval = null;
var animation_clicked = false;

function click_image()
{
	if (!$(this).hasClass("invisible")) return false;
	
	window.clearInterval(animation_interval);
	
	var testo = $(this).attr("title");
	$("#subtitle").html("/ "+testo);
	Cufon.replace('#subtitle');
	
	$("#scroll-images div div a:not(.invisible)")
		.click(click_image)
		.hover(rollover_image, rollout_image)
		.mousemove(rollover_image)
		.toggleClass("invisible");

	$(".scroll-image a").addClass("opacity50");

	$(this)
		.click(function() { return false; })
		.unbind("mouseenter")
		.unbind("mouseleave")
		.unbind("mousemove")
		.toggleClass("invisible")
		.removeClass("opacity50");

	
	var id = $(this).attr("id").split("-");
	if (location.hash != id[1]) location.hash = id[1];
	
	var x = parseInt($(this).parent().css("left").replace("px","")) + Math.round($(this).width()/2);
	x_target = -x;
	
	animation_clicked = true;
	animation_interval = window.setInterval("animate()",25);
	
	return false;
}

function animate()
{
	var e = document.getElementById("scroll-images");
	var x = parseInt(e.style.left.replace("px",""));
	var x_diff = x_target - x;
	e.style.left = (x + x_diff/4) + "px";

	//if (Math.round(x_diff) == 0) {
	if (Math.ceil(x_diff/4) == 0) {
		window.clearInterval(animation_interval);
		animation_clicked = false;
	}
}

function load_next_image()
{
	if (load_next) {
		if ($("#scroll-images div div:has(a.loaded):last").next().length > 0) {
			$("#scroll-images div div:has(a.loaded):last")
				.next()
				.children("a")
				.each(
					function(i)
					{
						var image_url = $(this).attr("href");
						$(this).children("img").attr("src", image_url).load(load_next_image);
						$(this).addClass("loaded");
					}
				);
				
			if ($("#scroll-images div div:has(a.loaded):first").prevAll().length > 0) load_next = false;
		} else {
			load_next = false;
			load_next_image();
		}
	} else {
		$("#scroll-images div div:has(a.loaded):first")
			.prev()
			.children("a")
			.each(
				function(i)
				{
					var image_url = $(this).attr("href");
					$(this).children("img").attr("src", image_url).load(load_next_image);
					$(this).addClass("loaded");
				}
			);
		
		if ($("#scroll-images div div:has(a.loaded):last").nextAll().length > 0) load_next = true;
	}
}

function rollover_image()
{
	$(this).removeClass("opacity50");
//	$(this).addClass("opacity50");
}

function rollout_image()
{
	$(this).addClass("opacity50");
//	$(this).removeClass("opacity50");
}

function splash_image_resize()
{
	var splash_image = $("#splash img:last");
	
	//splash_image.css("width", "").css("height", "");

	//var w = splash_image.attr("width");
	//var h = splash_image.attr("height");
	
	if (!splash_image.data('original_width')) {
		splash_image.data('original_width', splash_image.width());
		splash_image.data('original_height', splash_image.height());
	}
	
	var w = splash_image.data('original_width');
	var h = splash_image.data('original_height');
	
	var r = w/h;
	
	//var window_w = $(window).width();
	var window_w = ($(window).width()>$("body").width())?$(window).width():$("body").width();
	//var window_h = $(window).height();
	var window_h = ($(window).height()>$("body").height())?$(window).height():$("body").height();
	var window_r = window_w/window_h;

	var new_w; var new_h;
	if (window_r >= r){
		new_w = window_w;
		new_h = window_w / r;
	} else {
		new_w = window_h * r;
		new_h = window_h;
	}
	/*
	if(window_h<680) 
		window_h=680;
	new_w = window_h * r;
	new_h = window_h;
	*/
	
	//splash_image.css("width", new_w).css("height", new_h);
	
	splash_image.width(new_w).height(new_h);
	splash_image.css("left", (window_w-new_w)/2);
	
	var altro = $("#home_content");
	altro.width(window_w-57);
	var altro = $("#content_logo");
	altro.width(window_w-57-(329*2)-4);	
	var altro = $("#footer_chiuse");
	altro.width(window_w-57-37);
	
}

function ie_png()
{
	if ($.browser.msie) {
		$("img[src$='.png']").each(function() {
			this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + this.src + ")";
			$(this).data('old_src', this.src).attr('src', 'images/empty.gif');
		});
	}
}

function splash_images(items)
{
	var current = 0;
	var images = [];
	var interval;
	
	$('.heading img').each(function()
	{
		var src = $(this).attr('src');
		var current_hex = (src.indexOf('ffffff') > -1) ? 'ffffff' : '000000';
		var hex = (current_hex = 'ffffff') ? '000000' : 'ffffff';
		var image = new Image();
		image.src = src.replace(current_hex, hex);
	});
	
	$('#content_block2 .navigate').click(next);
	$('#content_block2 .navigateprec').click(prec);
	$('#content_block2 .tuttoschermo').click(goFull);
	$('#normalscreen .tuttoschermo').click(goNormal);
	$('#normalscreen').hide();				

	load_image(0);

	findit = $('#stopCiclo');
	if(findit.length>0){
		$('#zoomInFoto').click(next);
		$('#zoomOutFoto').click(prec);		
	}else{
		interval = setInterval(next, 6000);		
	}


	function goFull(){
		$('#home_content').hide();
		$('#footer_chiuse').hide();
		$('#normalscreen').show();	
		clearInterval(interval);
		interval = setInterval(next, 6000);
	}
	
	function goNormal(){
		$('#home_content').show();
		$('#footer_chiuse').show();
		$('#normalscreen').hide();				
	}


	function load_image(n)
	{
		if (n >= items.length) return;
		
		var image = new Image();
		
		$(image).data('n', n).load(image_loaded);
		image.src = (n == 0) ? $('#splash img:first').attr('src') : items[n].filename;
		if (image.complete) $(image).trigger('load').unbind('load'); // Ensure loaded function called in IE
		
		images[n] = image;
		if (images.length > 1) $('#splash-controls .items:not(.open)').addClass('open').delay('slow').slideDown('fast');
	}
	
	function image_loaded()
	{
		var n = $(this).data('n');

		$(this).addClass('loaded');
		
		var classes = (n == current) ? 'active' : '';
		$('#splash-controls .items li:eq(' + n + ')')
			.find('span').replaceWith('<a href="#' + n + '" class="' + classes + '">' + (n + 1) + '</a>')
			.end().find('a').click(navigate);

		load_image(n + 1);
	}
	
	function next(event)
	{
		if (event && event.type == 'click') event.preventDefault();
		
		var n = current + 1;
		if (n > (items.length - 1)) n = 0;
		if (!images[n] === undefined || !$(images[n]).hasClass('loaded')) return;
		
		if (event && event.type == 'click') clearInterval(interval);
		
		show_image(n);
	}
	
	function prec(event)
	{
		if (event && event.type == 'click') event.preventDefault();
		
		var n = current - 1;
		if (n < 0) n = items.length - 1;
		if (!images[n] === undefined || !$(images[n]).hasClass('loaded')) return;
		
		if (event && event.type == 'click') clearInterval(interval);
		
		show_image(n);
	}
	
	function navigate(event)
	{
		event.preventDefault();
		var n = $(this).parent().index();
		if (n == current) return;
		clearInterval(interval);
		show_image(n);
	}
	
	function show_image(n)
	{
		$(images[current]).detach();
		
		var image = images[n];
		
		$('#splash').append(image);
		
		$('#splash .overlay').remove();
		$('#splash').append('<div class="overlay"></div>');
		$('#splash .overlay').fadeOut(700, function() 
		{
			$(this).remove();
		});
		
		if (items[n].url !== '') {
			$('#splash-controls .title').html('<a href="' + items[n].url + '">' + items[n].description + "</a>");
		} else {
			$('#splash-controls .title').html(items[n].description);
		}
		
		$('#splash-controls .active').removeClass('active');
		$('#splash-controls .items li:eq(' + n + ') a').addClass('active');
		
		set_colours(items[n].hex);
		
		splash_image_resize();
		
		current = n;
	}
	
	function set_colours(hex)
	{
		var colour = (hex == '000000') ? 'white' : 'black';
		$('#splash').removeClass('white black').addClass(colour); 
		
		$('.heading img').each(function()
		{
			if (!$.browser.msie) {
				var src = $(this).attr('src');
				var new_src = src.replace(/000000|ffffff/, hex);
				$(this).attr('src', new_src);
			} else {
				var src = $(this).data('old_src');
				var new_src = src.replace(/000000|ffffff/, hex);
				this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + new_src + ")";
			}
		});
		
		ie_png();
	}
}

$(document).ready(
	function()
	{
		var n = (location.hash) ? parseInt(location.hash.replace("#","")) : 1;
		
		ie_png();
		
		$("#thumbnails a")
			.hover(
				function() 
				{
					$("#subheadings img:not(.hidden)").toggleClass("hidden");
					var id = $(this).attr("class");
					if (id) $("#" + id).toggleClass("hidden");
				},
				function() 
				{
					var id = $(this).attr("class");
					if (id) $("#" + id).toggleClass("hidden");
				}
			)
			.each(
				function()
				{
					if (screen.width >= 1400) {
						var href = $(this).attr("href").replace("/m/", "/l/");
						$(this).attr("href", href);
					}
				}
			)
			
		$("body.projects #thumbnails > a:gt(6)").hide();
		$("body.projects #thumbnails").append('<div id="thumbnails-toggle"><a href="#more">Show more projects »</a></div>');
		$("body.projects #thumbnails-toggle a").click(function()
		{
			if ($("body.projects #thumbnails > a:hidden").length) {
				$("body.projects #thumbnails > a:hidden").show();
				$(this).text('« Show fewer projects');
			} else {
				$("body.projects #thumbnails > a:gt(6)").hide();
				$(this).text('Show more projects »');
			}
			return false;
		});
			
		$("#scroll-images").css("display", "block");
			
		$("#scroll-images div div a")
			.click(click_image)
			.hover(rollover_image, rollout_image)
			.mousemove(rollover_image);
			
		$("#js-"+n).each(
			function(i)
			{
				var image_url = $(this).attr("href");
				$(this).children("img").attr("src",image_url).load(load_next_image);
				var img = new Image();
				$(this).addClass("loaded").trigger("click");
			}
		);
		
		if ($('#scroll-images').length) {
			var current_hash = n;
			setInterval(function()
			{
				var hash = parseInt(location.hash.replace("#", ""));
				if (hash !== current_hash && !animation_clicked) {
					$('#scroll-images div div:eq(' + (hash - 1) + ') a').click();
				}
				current_hash = hash;
			}, 100);
		}

		if ($("body").hasClass("splash")) {
			if (!$(document).attr('compatMode')) {
				// Work around jQuery/Safari 3 bug http://dev.jquery.com/ticket/4638
				$(document).attr('compatMode', 'CSS1Compat');
			}
			splash_image_resize();
			$(window).resize(splash_image_resize);
		}
		
		sfondo = $('.smunta').attr("src");


(function($) {
	var imgList = [];
	$.extend({
		preload: function(imgArr, option) {
			var setting = $.extend({
				init: function(loaded, total) {},
				loaded: function(img, loaded, total) {},
				loaded_all: function(loaded, total) {}
			}, option);
			var total = imgArr.length;
			var loaded = 0;
			
			setting.init(0, total);
			for(var i in imgArr) {
				imgList.push($("<img />")
					.attr("src", imgArr[i])
					.load(function() {
						loaded++;
						setting.loaded(this, loaded, total);
						if(loaded == total) {
							setting.loaded_all(loaded, total);
						}
					})
				);
			}
			
		}
	});
})(jQuery);


$(function() {
	
	$.preload([sfondo], {
		init: function(loaded, total) {
			//$("#indicator").html("Loaded: "+loaded+"/"+total);
		},
		loaded: function(img, loaded, total) {
			//$("#indicator").html("Loaded: "+loaded+"/"+total);
			//$("body").append(img);
		},
		loaded_all: function(loaded, total) {
			$('.smunta').fadeIn(800, function() {
			// Animation complete
			});
		}
	});

});
	
	

		

		splash_image_resize();
	}
);


