$(document).ready(function(){
var margin =$("#image1").width()/2;
var width=$("#image1").width();
var height=$("#image1").height();
var ubercounter=0;

jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

$.preloadImages("img/0.jpg","img/0c.jpg","img/1.jpg","img/1c.jpg","img/1-preview.jpg","img/0-preview.jpg");

$("#image2").stop().css({width:'0px',height:''+height+'px',marginLeft:''+margin+'px',opacity:'0.5'});
	$("#container").mouseenter(function(){
		//cambia image2 in versione bw
		var image2_next = (ubercounter+1)%2;
		$("#image2").attr("src","img/"+image2_next+".jpg");
		//riduci
		$("#image1").stop().animate({width:'0px',height:''+height+'px',marginLeft:''+margin+'px',opacity:'0.5'},{duration:300});
		//aspetta 500ms e poi allarga img2
		window.setTimeout(function() {
		$("#image2").stop().animate({width:''+width+'px',height:''+height+'px',marginLeft:'0px',opacity:'1'},{duration:500});
		},500);
	});
	
	$("#container").mouseleave(function(){
		$("#image2").stop().animate({width:'0px',height:''+height+'px',marginLeft:''+margin+'px',opacity:'0.5'},{duration:300});
		window.setTimeout(function() {
		$("#image1").stop().animate({width:''+width+'px',height:''+height+'px',marginLeft:'0px',opacity:'1'},{duration:500});
		},500);				   
	});
	
	$("#image1").click(function(){
		//nascondi questo testo
		$("#text"+ubercounter%2).fadeOut();
		$("#preview").fadeOut(500,function(){$("#preview").attr("src","img/"+ubercounter%2+"-preview.jpg");});
		ubercounter++;
		$(this).stop().animate({width:'0px',height:''+height+'px',marginLeft:''+margin+'px',opacity:'0.5'},{duration:300});
		//cambia image1 nell'altro, colorato
		var image1_next = ubercounter%2;
		window.setTimeout(function() { $("#image1").attr("src","img/"+image1_next+"c.jpg");},500);
		//aspetta 500ms e poi allarga img1
		window.setTimeout(function() {
		$("#image1").stop().animate({width:''+width+'px',height:''+height+'px',marginLeft:'0px',opacity:'1'},{duration:700});
		},500);
		$("#preview").fadeIn();
		$("#text"+ubercounter%2).fadeIn();
	});
	
	$("#image2").click(function(){
		$("#text"+ubercounter%2).fadeOut();
		$("#preview").fadeOut(500,function(){$("#preview").attr("src","img/"+ubercounter%2+"-preview.jpg");});
		ubercounter++;
		//stringi img2
		$(this).stop().animate({width:'0px',height:''+height+'px',marginLeft:''+margin+'px',opacity:'0.5'},{duration:300});
		//cambia img1 nello stesso, colorato
		var image1_next = ubercounter%2;
		window.setTimeout(function() {$("#image1").attr("src","img/"+image1_next+"c.jpg");},500);
		//aspetta 500ms e poi allarga img1
		window.setTimeout(function() {
		$("#image1").stop().animate({width:''+width+'px',height:''+height+'px',marginLeft:'0px',opacity:'1'},{duration:500});
		},500);
		$("#preview").fadeIn();
		$("#text"+ubercounter%2).fadeIn();

	});
});

