// COSTANTI

// Velocità di scroll delle immagini di sfondo.
// 1  |--> come scroll finestra
// 0  |--> fissa
// <0 |--> più lenta dello scroll finestra
var speedBG = 0.2;		
var speedFG = -0.6;

// Distanza del menu (filetto orizzontale) dall'alto. Valore negativo = distanza dal basso
bottomMenu = new Array (-90, 160, 160, 160, -160, 160);

// Immagini correnti dei vari slideshow
currImg = new Array (0, 1, 1, 1, 1);

// Larghezza fascia sinistra. Deve coincidere col css/left di text-content
var leftWidth = 287;

var currentPos = 1;
var firstAccess = true;

// Tab attiva (aperta)
var activeTab = "";

// Distanza dal basso linea ultima sezione
var lastD = -75;

// Stoppa il video quando arriva, se accedo ad una sezione direttamente
var stopVideo = false;

function flashCallBack() {
    if (stopVideo) {
        document.getElementById("flashContent").stopVideo();
    }
    else {
        document.getElementById("flashContent").playVideo();
    }
}


// Resize immagini - plugin
(function($) {
	$.fn.fullBg = function(){
		var bgImg = $(this);		

		function resizeImg() {
			var imgwidth = bgImg.width();
			var imgheight = bgImg.height();
		
			var divWidth = $(window).width();
			var divHeight = $(window).height();

			var widthratio = divWidth / imgwidth;
			var heightratio = divHeight / imgheight;

			var widthdiff = heightratio * imgwidth;
			var heightdiff = widthratio * imgheight;

			if(heightdiff>divHeight) {
				bgImg.css({
				  width: divWidth+'px',
				  height: heightdiff+'px'
				});
			} else {
				bgImg.css({
				  width: widthdiff+'px',
				  height: divHeight+'px'
				});		
			}
			bgImg.css("clip", "rect(0px," + divWidth + "px," + divHeight + "px,0px)");
		} 

		resizeImg();	
		
		//Chrome lancia troppo presto il resize iniziale
		if ($.browser.webkit) {
			var timeoutID1 = window.setTimeout(resizeImg, 10);
			var timeoutID2 = window.setTimeout(callScroll, 20);
		}
		function callScroll(){
			$(window).scroll();
		}
		
		$(window).resize(function() {
			resizeImg();
			$(window).scroll();
		}); 
	};
})(jQuery);

// Parallax - plugin
// Muove l'immagine ad una velocità relativa (opts.speed) rispetto allo scroll del browser
// Le immagini hanno proprietà position:fixed per evitare che lo scroll del browser le muova e successivamente il codice ne calcoli la posizione 'rallentata' (o velocizzata)
// Questo complica notevolmente il calcolo delle posizioni, che sono tutte assolute. Inoltre le immagini 'fixed' non sono mascherate dai div che le contengono, anche se questi hanno overflow:hidden
// Per questo uso la proprietà "clip" (css), che croppa l'immagine in base a 4 valori che seguono le regole del margin/padding (sopra destra sotto sinistra), relativamente all'immagine stessa
// L'immagine viene clippata e centrata in verticale
(function($){
    $.fn.parallax = function(options){
        var $$ = $(this);
		// Non sono necessari i default ma dà errore se non si estende options...
        var defaults = {};
        var opts = $.extend(defaults, options);
        return this.each(function(){
            $(window).bind('scroll', function() {
                windowTop = $(window).scrollTop();
				var H = $(window).height();
				var offset = (opts.position - 1) * H * (1 - opts.speed) + ($$.height() - H) / 2;
				
				newY = H * (opts.position - 1) - windowTop * opts.speed - offset;
				$$.css({
					"top": newY + "px"
				});
				
				var deltaSpeed = windowTop - windowTop * opts.speed;
				var cropY = H - deltaSpeed + offset;
				$$.css("clip", "rect(0px," + $(window).width() + "px," + cropY + "px,0px)");
            });
        });
    };
})(jQuery);

// Scrolla la finestra fino alla sezione 
function gotoSection(position) {

   
    $(".section").css("visibility", "visible");

	if ($.browser.webkit)
	{
		$('body').stop().animate({scrollTop : $(window).height() * (position - 1)}, 2000, "easeOutQuart", function()
			{
				//alert($(window).height() * (position-1) - $(window).scrollTop() * speedBG - ((position - 1) * $(window).height() * (1 - speedBG)));
				//$("#section-" + position).children(".parallax").stop().animate({top:0}, 1000);
				//$('html,body').scrollTop($(window).height() * (position - 1))
				removeAllSlideShow();
				loadSlideShow(position);
			});
	}
	else
	{
		if (firstAccess && $.browser.mozilla)	// Firefox inspiegabilmente non esegue lo scroll al primo ingresso !!
		{
			
			$('html').scrollTop($(window).height() * (position - 1));
			$("#section-" + position).children(".parallax").stop().animate({top:0}, 1000);
		}
		$('html').stop().animate({scrollTop : $(window).height() * (position - 1)}, 2000, "easeOutQuart", function()
		{
			//alert($(window).height() * (position-1) - $(window).scrollTop() * speedBG - ((position - 1) * $(window).height() * (1 - speedBG)));
			//$("#section-" + position).children(".parallax").stop().animate({top:0}, 1000);
			//$('html,body').scrollTop($(window).height() * (position - 1))
			
			//alert($("#imgBG-5").css("top"));
			
			removeAllSlideShow();
			loadSlideShow(position);
		});
	}
	
	currentPos = position;
	
	$('.img-link').removeClass('img-link-current');
	$('#link-' + position).addClass('img-link-current');

	if (position != 1) stopVideo = true;
}

function removeAllSlideShow()
{
	$(".slide-img").each (function(index)
	{
		if (Right ($(this).attr("id"), 2) != "-1")
		{
			$(this).remove();
		}
	});
	$(".arrow-left").fadeOut(100);
	currImg[1] = 1;
	currImg[2] = 1;
	currImg[3] = 1;
	currImg[4] = 1;

	$("#m-text-1-1").css("display", "block");
	$("#m-text-1-1").css("opacity", 1);
	$("#m-text-2-1").css("display", "block");
	$("#m-text-2-1").css("opacity", 1);
	$("#m-text-3-1").css("display", "block");
	$("#m-text-3-1").css("opacity", 1);
	$("#m-text-4-1").css("display", "block");
	$("#m-text-4-1").css("opacity", 1);
}
	
// Gestione degli slide-show:
// All'ingresso nella sezione inserisce un preloader per ogni immagine e carica le immagini usando elementi come cache.
// Next e Prev agiscono sui preloader, fino alla loro sostituzione con i tag definitivi, comprensifi vi immagini già caricate
// Ogni immagine a caricamento avvenuto si sostituisce al preloader
function loadSlideShow(position)
{
	var slideCont = $("#section-" + position).children(".slide-cont");
	if(slideCont.length > 0)
	{
		var slideShowId = Right(slideCont.attr("id"), 1);
		for (i=2; i<=slideCont.attr("data-slides") ; i++)
		{
			var str="<img src='img/loader.gif' class='preloader' id='imgBG-" + slideShowId + "-" + i + "' />";
			slideCont.append(str);
			
			str="<img src='img/" + slideCont.attr("data-folder") + "/" + i + ".jpg' class='slide-img' id='cacheBG-" + slideShowId + "-" + i + "' />";
			slideCont.append(str);
			
			$("#cacheBG-" + slideShowId+ "-" + i).imagesLoaded( function( $images ) {
				$images.fullBg();					// Le immagini nuove vanno adattate
				//console.log($images.attr("id"));
				idToRemove = "imgBG-" + $images.attr("id").split("-")[1] + "-" + $images.attr("id").split("-")[2];		// E' l'ID del preloader
				//console.log(idToRemove);
				var visibile = false;
				if ($("#" + idToRemove).css("display") != "none")
				{
					visibile = true;
				}
				$("#" + idToRemove).remove();		// Rimuovo il preloader
				//$("#" + idToRemove).attr("id", "ppp")
				
				$images.attr("id", idToRemove);		// Cambio l'ID dell'immagine in modo che coincida con quello del preloader appena rimosso (per Next e Prev)
				if (visibile)
				{
					$images.fadeIn(1200);
				}
			});
		}
	}
}

// Sistema la linea del menu attivo
function setupMenuLines()
{
    $(".m-active").each(function (index) {
        var distance = bottomMenu[Right($(this).parent().attr("id"), 1) - 1];
        if ($(this).hasClass("m-0")) {
            distance = lastD;
        }
        if (distance > 0) {
            $(this).height(distance);
        }
        else {
            $(this).height($(window).height() + distance);
        }
    });
	
	$(".m-hline").each(function(index)
	{
		$(this).width($(window).width() - parseInt($(this).css("right")) - leftWidth);
	});
}

// Ridimensiona i box di sinistra (solo altezza)
function resizeBox()
{
	$(".box").height($(window).height());
	$(".box img").height($(window).height());
	
	$(".title").height($(window).height());
	$(".title img").css("top", $(window).height() / 2 + 12);
	
	$("#box-border img").height($(window).height());
	
	$(".submenu").height($(window).height());
	$(".submenu ul").css("top", $(window).height() / 2 + 66);
}

function resizeSections()
{
    $(".section").height($(window).height());
    $("#n_cont").height($(window).height() - 275);
    $("#n_cont").width($(window).width() - 630);
    $("#scroller").height($(window).height() - 275);
    $("#scroller").width($(window).width() - 515);

    if ($("#n_cont").height() > $("#n_scroll").height() - 32) {
        $(".news-arrow").hide();
    }
    else {
        $(".news-arrow").show();
    }
    $("#n_scroll").animate({ "top": 0 }, 500);

}

function resizeGalleries()
{
	$(".slide-cont").height($(window).height());
}

function resizeTabs()
{
	$(".close-tab").height($(window).height());
	if (activeTab != "")
	{
		$(".paragraph").each (function (){
			var offset = $(this).position();
			$(this).height($(window).height() - offset.top - 55);
		});
		$('.paragraph').jScrollPane({showArrows: true});
	}
}

function outTab(tab)
{
	$("#tab-cont").css("display", "block");
	activePar = tab.find(".paragraph");
	if (activePar.length > 0)
	{
		activePar.height($(window).height() - activePar.position().top - 55);
		activePar.jScrollPane({showArrows: true});
	}
	tab.animate ({"left":0}, 1500, "easeOutQuint");
	activeTab = tab;
	
	$("#shadow").fadeIn(1000);
}

function openRef(idRef, link)
{
	activePar = $("#ref-" + idRef);
	activePar.parent().find(".paragraph").fadeOut();	// Tutti i paragrafi fratelli scompaiono
	activePar.fadeIn();
	activePar.height($(window).height() - activePar.position().top - 55);
	activePar.jScrollPane({showArrows: true});

	$(".referenze a").removeClass("ref-menu-current");
	link.addClass("ref-menu-current");
}

$(document).ready(function () {
    $("h1").textShadow();

    $(".open-tab").click(function () {
        $(".open-tab").removeClass("submenu-current");
        $(".close-link").removeClass("submenu-current");
        $(this).addClass("submenu-current");
        relTab = $("#" + $(this).attr("data-reltab"));

        // Fa uscire il tab corrente, se è fuori e non è quello cliccato
        if (activeTab != "" && relTab.attr("id") != activeTab.attr("id")) {
            activeTab.animate({ "left": -(activeTab.parent().width()) }, 600, "easeInQuad", function () { outTab(relTab); });
        }
        else {
            outTab(relTab);
        }
    });
    $(".tab").click(function (event) {
        event.stopPropagation();        // Non propago il click al container (#tab-cont), che chiuderebbe il tab
    });

    $(".close-tab, #tab-cont, .close-link").click(function (event) {
        $(".open-tab").removeClass("submenu-current");
        $(".close-link").addClass("submenu-current");
        larg = activeTab.outerWidth(true);
        activeTab.animate({ "left": -larg }, 600, "easeOutQuint", function () {
            $("#tab-cont").css("display", "none");
            $("#shadow").fadeOut(1000);
        });
        activeTab = "";
    });

    $(".close-tab").hover(function () {
        $(".close-arrow").css("background-image", "url('Styles/img/close-arrow-h.png')");
    }, function () {
        $(".close-arrow").css("background-image", "url('Styles/img/close-arrow.png')");
    });

    $(".m-hline").each(function (index) {
        var distance = bottomMenu[Right($(this).parent().attr("id"), 1) - 1];
        if ($(this).hasClass("m-0")) {
            distance = lastD;
        }
        if (distance > 0) {
            $(this).css("top", distance - 1);
        }
        else {
            $(this).css("bottom", -distance - 1);
        }
        $(this).width($(window).width() - parseInt($(this).css("right")) - leftWidth);
        $(this).css("right", parseInt($(this).css("right")) + 2);
    });

    $(".m-text").each(function (index) {
        var distance = bottomMenu[Right($(this).parent().attr("id"), 1) - 1];
        if (distance > 0) {
            $(this).css("top", distance);
        }
        else {
            $(this).css("bottom", -distance);
        }
    });

    // Imposta il resize di tutte le immagini
    // NB: il ridimensionamento avviene 'in blocco' perché il plugin è applicato alla classe .imgBG, quindi TUTTE le immagini vengono ridimensionate secondo gli stessi parametri.
    // Questo implica che tutte le immagini devono avere la stessa dimensione di partenza.
    // Quelle con oggetti piccoli che si muovono veloci dovranno essere grandi, cono molto fondo trasparente (in PNG-24 risultano file solo leggermente più grandi: ~5KB)
    // Volendo usare immagini con rapporto h/w diverso fra loro (ma non dovrebbe servire) si dovrebbe applicare il plugin agli ID, eventualmente con un jquery.each()

    window.onload = function () {
        

        $(".imgBG").fullBg();
        $(".slide-img").fullBg();
        $('#imgBG-1').parallax({ "speed": speedBG, "position": 1 });
        $('#imgBG-6').parallax({ "speed": speedBG, "position": 6 });
        $('#slideshow-1').parallax({ "speed": speedBG, "position": 2 });
        $('#slideshow-2').parallax({ "speed": speedBG, "position": 3 });
        $('#slideshow-3').parallax({ "speed": speedBG, "position": 4 });
        $('#slideshow-4').parallax({ "speed": speedBG, "position": 5 });

        $("div.slide-cont img:first-child").fadeIn(500);
        $("img.imgBG").fadeIn(500);
    };

    /*
    $("#wrapper").imagesLoaded(function ($images) {
    alert("ok");
    $images.fullBg();
    $('#imgBG-1').parallax({ "speed": speedBG, "position": 1 });
    $('#imgBG-6').parallax({ "speed": speedBG, "position": 6 });
    });
    $(".slide-img").imagesLoaded(function ($images) {
    $images.fullBg();
    $('#slideshow-1').parallax({ "speed": speedBG, "position": 2 });
    $('#slideshow-2').parallax({ "speed": speedBG, "position": 3 });
    $('#slideshow-3').parallax({ "speed": speedBG, "position": 4 });
    $('#slideshow-4').parallax({ "speed": speedBG, "position": 5 });
    });
    */


    // Applica il parallasse alle immagini di sfondo




    // Applica il parallasse alle immagini in sovraimpressione
    /*
    $('#imgFG-1').parallax({ "speed":-speedFG, "position":1 });
    $('#imgFG-2').parallax({ "speed":speedFG, "position":2 });
    $('#imgFG-3').parallax({ "speed":0, "position":3 });
    //$('#imgFG-4').parallax({ "speed":1, "position":4 });
    $('#imgFG-5').parallax({ "speed":1, "position":5 });
    $('#imgFG-6').parallax({ "speed":1, "position":6 });
    */

    // Adatta le linee di menu alle dimensioni del browser
    setupMenuLines();
    // Sistema i box di sinistra
    resizeBox();
    // Setup Welcome (flash)
    resizeSections();
    // Resize gallerie foto
    resizeGalleries();
    // Resize tabs interni
    resizeTabs();

    // IE7 no hashChange event support...
    $(".img-link").click(function () {
        if ($.browser.msie && Left($.browser.version, 1) == 7) {
            window.location = $(this).attr("href");
            $(window).trigger("hashchange");
        }
    });
    $(window).bind('hashchange', function () {
        var hash = window.location.hash;
        if (hash != "") gotoSection(Right(hash, 1));
    });
    $(window).trigger('hashchange');

    // Lancia un evento scroll per sistemare inizialmente tutte le immagini
    $(window).scroll();

    $("a.img-link").click(function () {
        firstAccess = false;
        if ($(this).attr("id") == "link-1") {
            document.getElementById("flashContent").playVideo();
        }
        else {
            document.getElementById("flashContent").stopVideo();
        }
    });

    $(window).resize(function () {
        setupMenuLines();
        resizeBox();
        resizeSections();
        resizeGalleries();
        gotoSection(currentPos);
        resizeTabs();
    });

    $(".arrow-left").click(function () {
        var id = Right($(this).attr("id"), 1);
        if (currImg[id] > 1) {
            $("#imgBG-" + id + "-" + currImg[id]).fadeOut(1200);
            currImg[id]--;
        }

        if (currImg[id] == 1) {
            $(this).fadeOut(200);
        }

        $("#arrow-right-" + id).fadeIn(200);

        showHideTxt(id);
    });
    $(".arrow-right").click(function () {
        var id = Right($(this).attr("id"), 1);
        var slides = $("#slideshow-" + id).attr("data-slides");
        currImg[id]++;
        if (currImg[id] <= slides) {
            $("#imgBG-" + id + "-" + currImg[id]).fadeIn(1200);
        }

        if (currImg[id] >= slides) {
            $(this).fadeOut(300);
            currImg[id] = slides;
        }
        $("#arrow-left-" + id).fadeIn(300);

        showHideTxt(id);
    });

    function showHideTxt(id) {
        $("#m-text-" + id + "-1").stop().animate({ opacity: 0 }, 1200, function () { $(this).css("display", "none") });
        $("#m-text-" + id + "-2").stop().animate({ opacity: 0 }, 1200, function () { $(this).css("display", "none") });
        $("#m-text-" + id + "-3").stop().animate({ opacity: 0 }, 1200, function () { $(this).css("display", "none") });
        $("#m-text-" + id + "-4").stop().animate({ opacity: 0 }, 1200, function () { $(this).css("display", "none") });
        if (id != 4) {
            if (currImg[id] == 1) {
                $("#m-text-" + id + "-1").css("display", "block");
                $("#m-text-" + id + "-1").stop().animate({ opacity: 1 }, 1200);
            }
            if (currImg[id] == 5) {
                $("#m-text-" + id + "-2").css("display", "block");
                $("#m-text-" + id + "-2").stop().animate({ opacity: 1 }, 1200);
            }
            if (currImg[id] == 10) {
                $("#m-text-" + id + "-3").css("display", "block");
                $("#m-text-" + id + "-3").stop().animate({ opacity: 1 }, 1200);
            }
        }
        else {
            if (currImg[id] == 1) {
                $("#m-text-" + id + "-1").css("display", "block");
                $("#m-text-" + id + "-1").stop().animate({ opacity: 1 }, 1200);
            }
            if (currImg[id] == 10) {
                $("#m-text-" + id + "-2").css("display", "block");
                $("#m-text-" + id + "-2").stop().animate({ opacity: 1 }, 1200);
            }
            if (currImg[id] == 14) {
                $("#m-text-" + id + "-3").css("display", "block");
                $("#m-text-" + id + "-3").stop().animate({ opacity: 1 }, 1200);
            }
            if (currImg[id] == 16) {
                $("#m-text-" + id + "-4").css("display", "block");
                $("#m-text-" + id + "-4").stop().animate({ opacity: 1 }, 1200);
            }
        }
    }

    // SPERIMENTALE, GESTISCE IL DRAG DELLO SCHERMO
    /*
    jQuery(function($){
    $('#wrapper').drag(function( ev, dd ){
    $(window).scrollTop($(window).scrollTop()-dd.offsetY);
    });
    });
    */

    // SPERIMENTALE, PRELEVA UN ATTRIBUTO DEL DIV #test
    //alert(document.getElementById("test").getAttribute("data-file"));


});








