﻿$.log = function() {//Funzione per la scrittura sulla console di FF  
    if ($.browser.mozilla) {//su ie6 pianta tutto - metto controllo
        var consoleExists = (typeof(console) == "object") && (typeof(console.log) == "function");
        if (consoleExists) { 
            if (navigator.userAgent.toLowerCase().indexOf("applewebkit") != -1) { 
                console.log(arguments); 
            } 
            else 
            { 
               console.log.apply(this,arguments); 
            } 
        } 
    }
}

var containerCenter, cites;
var imgLuca;
var container;
var mappa;
var layerOver;
var windowMusic;

function resize()
{
    var height;
    if ($(window).height()>550) height=$(window).height();
    else height=550;
    containerCenter.height(height);

    imgLuca.width(parseInt((imgLuca.height()*451)/618));
    imgLuca.css({"margin-left":-(parseInt(imgLuca.width()/2))+"px"});
}

$(window).resize(
    function()
    {
        resize();
    }
);

var gallery={
    step:1,
    lengthStep:0,
    lengthGal:0,
    maxShift:0,
    arrowLeft:null,
    arrowRight:null,
    bufferAnimation:[],
    onAnimation:false,
    slide:null,
    slideSpeed:600,
    init:function(gal,objs,obj,numObjPerPage,slideVelocity)
    {
        gallery.arrowLeft=gal.find("a#arrow-left");
        gallery.arrowRight=gal.find("a#arrow-right");
        gallery.manageArrows();
        gallery.slide=gal.find(objs);
        gallery.lengthStep=parseInt(gallery.slide.find(obj+":first").width());
        if (gallery.slide.find(obj+":first").css("margin-right")!=0)
            gallery.lengthStep+=parseInt(gallery.slide.find(obj+":first").css("margin-right"));
        gallery.lengthStep=gallery.lengthStep*numObjPerPage;
        
        gallery.lengthGal=parseInt(gallery.lengthStep*gallery.slide.find(obj).length);
        gallery.maxShift=(gallery.lengthGal-gallery.lengthStep*3)/numObjPerPage;
        if (slideVelocity!=undefined) gallery.slideSpeed=slideVelocity;
    },
    shiftSlide:function(step) /* semaphore for multiple click*/
    {
        var canShift=false;
        if (step==1)
        {
            if (parseInt(gallery.slide.css("margin-left"))<0) canShift=true;
            else 
            {
                gallery.onAnimation=false;
                gallery.arrowLeft.addClass("off");
            }
        }
        else
        {
            if (parseInt(gallery.slide.css("margin-left"))>-(gallery.maxShift)) canShift=true;
            else 
            {
                gallery.onAnimation=false;
                gallery.arrowRight.addClass("off");
            }
        }    
        if (canShift)
            gallery.slide.animate(
                {
                    "margin-left":parseInt(gallery.slide.css("margin-left"))+step*gallery.step*gallery.lengthStep
                },
                gallery.slideSpeed,
                function()
                {
                    if (parseInt(gallery.slide.css("margin-left"))==0) gallery.arrowLeft.addClass("off");
                    else gallery.arrowLeft.removeClass("off");
                    if (parseInt(gallery.slide.css("margin-left"))==-(gallery.maxShift)) gallery.arrowRight.addClass("off");
                    else gallery.arrowRight.removeClass("off");
                    if (step==1)
                    {
                    }
                    else
                    {
                    }
                    
                    if (gallery.bufferAnimation.length>0)
                    {
                        gallery.shiftSlide(gallery.bufferAnimation.shift());
                    }
                    else gallery.onAnimation=false;
                }
            );        
      
    },
    manageArrows:function()
    {
        gallery.arrowLeft.click(
            function()
            {
                if (!gallery.onAnimation)
                {
                   gallery.onAnimation=true;
                    gallery.shiftSlide(1);
                }
                else gallery.bufferAnimation.push(1);
                return false;
            }
        );
        gallery.arrowRight.click(
            function()
            {
                if (!gallery.onAnimation)
                {
                    gallery.onAnimation=true;
                    gallery.shiftSlide(-1);
               }
                else gallery.bufferAnimation.push(-1);
                return false;
            }
        );
    }
}
    
    var mex;
    var detBrowsAnimate;
    function hideMex()
    {
         mex.animate({"top":-500},2500,
            function()
            {
                mex.remove();
                window.clearInterval(detBrowsAnimate);
            }
        );
    }

function getMex(message,type)
{
    if (type==undefined) type="";
    mex=jQuery("<div id='mex' class='"+type+"'>"+message+"</div>");
    $("body").append(mex);

    mex.animate({"top":20},2500,
        function()
        {
            detBrowsAnimate=setInterval(hideMex,6000);
        }
    );
}

function detBrowser()
{
    if (($.browser.msie && ($.browser.version=="6.0"||$.browser.version=="7.0"))) 
        getMex("The Magic World of Luca Bono<br/> <br/>Il tuo browser è obsoleto: ti consigliamo di aggiornarlo "+
                "alla versione più recente per poter visualizzare meglio il sito","error");
}

var startAnimation;
var objsToShow;
var objsPages=
{
    obj:["#left-side", "#menu", "#footer","#paragraph"],
    interval:[1000,600,600,600]
}
var objsHome=
{
    obj:["img#imgLuca","#left-side", "#menu", "#footer","#tour-container", "#cites"],
    interval:[1500,1000,600,600,600,600]
}

var rotatePics;
var countRotate=0;
function changeGal()
{
    countRotate++;
    if (countRotate>=5) countRotate=1;
    
    var imgFog=container.find("img.fog");
    var imgShadow=container.find("img.shadow");
    imgShadow.attr({"src":"img/sfondi/"+container.attr("class")+"/step"+countRotate+".png"})
    imgFog.fadeOut(3000);
    imgShadow.fadeIn(3000,
        function()
        {
            imgFog.removeClass("fog").addClass("shadow");
            imgShadow.removeClass("shadow").addClass("fog");
        }
    );
   
}

function animationOnOpen()
{
    var i=0;
    function showObj()
    {
        if (i<objsToShow.obj.length)
        {
            if ($(objsToShow.obj[i]).length>0) $(objsToShow.obj[i]).fadeIn(objsToShow.interval[i]);
            i++;
        }
        else 
        {
            window.clearInterval(startAnimation);
            if ($("body").hasClass("home")) gallery.init($("#tour-date"),"ul","li",1);
            else if ($("#article-layout").length>0) gallery.init($("#article-layout"),"#article","p",2,1500);

        }
    }
    
    if ($("body").hasClass("home")) objsToShow=objsHome;
    else objsToShow=objsPages;
    window.clearInterval(startAnimation);
    startAnimation=setInterval(showObj,1000);    
    rotatePics=setInterval(changeGal,3000);
}

function animationOnClose(href)
{
    var i;
    function hideObj()
    {
        if (i>=0)
        {
            if ($(objsToShow.obj[i]).length>0) $(objsToShow.obj[i]).fadeOut(objsToShow.interval[i]);
            i--;
        }
        else 
        {
            window.clearInterval(startAnimation);
            container.fadeOut("slow",function(){location.href=href;});
        }
    }
    if ($("body").hasClass("home")) 
    {
        objsToShow=objsHome;
        objsToShow.obj.splice(1,0,"img.sfondo:first");
        objsToShow.interval.splice(1,0,600);
    }
    else objsToShow=objsPages;
    i=objsToShow.obj.length-1;
    window.clearInterval(startAnimation);
    startAnimation=setInterval(hideObj,600);    
}



$(document).ready(
    function()
    {
        imgLuca=$("img#imgLuca");
        
        layerOver=$("#layer-over");
        
        layerOver.show();
        layerOver.find("#initial-cite").css({"margin-left":-(parseInt(layerOver.find("#initial-cite h2").width())+10)/2});
        detBrowser();
        container=$("#container");
        container.fadeIn("slow");
        
        $("ul#menu a").click(
            function()
            {
                var _this=$(this);
                if (_this.parent().attr("id")!="lbWorld")
                {
                    var parMusic=1;
                    if (musica.find("#musicSwf").length==0) parMusic=0;
                    animationOnClose(_this.attr("href")+"?m="+parMusic);
                }
                else animationOnClose(_this.attr("href"));
                return false;
            }
        );
        
        var animateBg;
        var i=1;

        containerCenter=$("#layout,#container,#left-side,#center,#imgLuca,img.container,.sfondo");
      
        resize();
        
        var arrayImg=["bg.jpg","step1.png","step2.png","step3.png","step4.png"];
        var divBuffer=$("div#imgBuffer");
        var pathImg=$("ul#menu li.current").attr("id");
        function loadingImages()
		{
		    var img=arrayImg.shift();
		    if (divBuffer.find("."+img).length==0)
		    {
		        var classImg=img.split(".")[0];
		        divBuffer.append("<img class='"+classImg+"' src='img/sfondi/"+pathImg+"/"+img+"' alt=''/>");
		        $("."+classImg).load(
		            function()
		            {
		                if (arrayImg.length==0) 
		                {   
		                    layerOver.fadeOut("fast",
		                    function()
		                    {
                               startAnimation=setInterval(animationOnOpen,1500);
                            });
                        }
		                else loadingImages();
		            }
		        );
		    }
		}
		
		loadingImages();

        var numGal=$("#par ul.pic li a").length;
        if (numGal>0)
        {
            for (var j=0; j<numGal; j++)
            $("#par ul li a[rel=gal"+j+"]").fancybox({
                'cyclic'        :   true,
		        'transitionIn'	:	'elastic',
		        'transitionOut'	:	'elastic',
		        'speedIn'		:	600, 
		        'speedOut'		:	200, 
		        'overlayShow'	:	true,
		        'overlayOpacity':   0.8/*,
		        'titlePosition': 'over',
                'titleFormat': function(title, currentArray, currentIndex, currentOpts) {
                    return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + '</span>';
                }*/
	        });
	        
	        var video=$("#par ul li a[rel=video]");
	        video.each(
	            function()
	            {
	                var _this=$(this);
	                var img=$("<img></img>");
	                img.attr({"src":"http://img.youtube.com/vi/"+_this.attr("href").split("v=")[1]+"/2.jpg"});
	                _this.append(img);
	            }
	        );	  
	        video.click(
	            function()
	            {
	                if (musica.html()!="") musica.html("<p></p>");//*** metto il p, così se apre il video youtube e poi
	                //*** richiude, se c'è il p, sa che c'era la musica prima, se non c'è niente, non fa niente :)
	                window.clearInterval(rotatePics);
	            }
	        );  
	        video.jqvideobox();
	    }
	    
	    
	    musica=$("#musica");

	    var musicOnStart=location.href.split("?m=")[1];//.substr(0,1);
	    if(musicOnStart==undefined) musicOnStart=1;
	    else musicOnStart=musicOnStart.substr(0,1);
	    var turnSound=$("#turnSound a");
	    if (musicOnStart==0) {turnSound.prev("label").html("sound on"); turnSound.addClass("off");}
	    else startMusic();
	    turnSound.click(
	        function()
	        {
	           turnSound.toggleClass("off");
	            if (turnSound.hasClass("off")) 
	            {
	                turnSound.prev("label").html("sound on");
	                musica.html("");
	            }
	            else  
	            {
	                turnSound.prev("label").html("sound off");
	                startMusic();
                }
	            return false;
	        }
	    );

        var validEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;	   
	    var nome=$("#nome");
	    var cognome=$("#cognome");
	    var email=$("#email");
	    var messaggio=$("#messaggio");
	    
	    var controls=$("#par .obbl");
	    
	    function setValidOrError(obj)
	    {
            if (obj.attr("id")!="email")
            {
                if (obj.val()!="" && obj.val().indexOf("scrivi il tuo")==-1) obj.parent().removeClass("error");
                else obj.parent().addClass("error");
            }
            else
            {
                if (validEmail.exec(obj.val()) && obj.val().toLowerCase()!="tuaemail@dominio.it") obj.parent().removeClass("error");
                else obj.parent().addClass("error");
            }
	    }
	    
	    function controlForm()
	    {
	        controls.each(
	            function()
	            {
	                setValidOrError($(this));
	            }
	        );
	    }
	    
	    controls.blur(
	        function()
	        {
	            setValidOrError($(this));   
	        }
	    );
	  
	    $("#sendData").click(     
	        function()
	        {   
	            var valid=( nome.val()!="" && nome.val().toLowerCase()!="scrivi il tuo nome" && 
	                        validEmail.exec(email.val()) && email.val().toLowerCase()!="tuaemail@dominio.it" &&
	                        messaggio.val()!="" );
	            if (valid)
	            {
                    $("form .riga").removeClass("error");
                    var nomePers=nome.val();
                    if (cognome.val()!="") nomePers += " " + cognome.val();
	                $.ajax({
                            type: "POST",
		                    url: "send.php?nome="+nomePers+"&email="+email.val()+"&messaggio="+messaggio.val(),
		                    dataType: "text",
		                    success: function(text) 
		                    {
		                        getMex("The Magic World of Luca Bono<br/>Mail inviata con successo<br/>Grazie per averci contattato");
		                    },
		                    error: function(msg)
		                    {
		                    }
		                });
		        }
		        else
		        { 
		            controlForm();
		            getMex("compilare tutti i campi contrassegnati in rosso","error");
		            return false;
		        }
		        return false;
            }
	    );

        var lookGmap=$(".look-gmap");
        mappa =$("#map_canvas");
        if (lookGmap.length>0)
        {
            lookGmap.click(
                function()
                {
                    var father=$(this).parent();
                    layerOver.fadeIn(600, 
                        function()
                        {
                            mappa.parent().show();
                            mappa.fadeIn();
                            initializeGMap(father.find("input.lat").val(),father.find("input.lng").val());
                       }
                    );
                }
            );
        }
        function chiudiMappa()
        {
            mappa.parent().hide();
            mappa.fadeOut(100);
            layerOver.fadeOut(600);
        }
        
        layerOver.click(
            function()
            {
                chiudiMappa();
            }
        );
        
        mappa.parent().find("a.close").click(
            function()
            {
                chiudiMappa();
            }
        );
                
        var animationGal;var current;
        function rotate()
        {
            current.removeClass("current");

            if (current.next().length>0) 
            {
                current=current.next();
            }
            else 
            {
                current=current.siblings().eq(0);
                window.clearInterval(animationGal);
            }
            current.addClass("current");
       }
        
        var curGal=-1;
        var pics=$(".pic a");
  
        pics.hover(
            function()
            {
                current=$(this);
                curGal=$(".pic li").index(current.parent());
                animationGal=setInterval(rotate,300);
            },
            function()
            {
                window.clearInterval(animationGal);
            }
        );
        setInterval(rotateCite,6000);

    }
);
 
function rotateCite()
{
    var current=$("#center div#cites div.current");
    current.fadeOut(1000,
        function()
        {
            current.removeClass("current");
            if (current.next().length>0) current=current.next();
            else current=current.siblings().eq(0);
            
            current.fadeIn(1000,function(){current.addClass("current");})

        }
    );
}
	    
function initializeGMap(lat,lng) {
    var latlng = new google.maps.LatLng(lat, lng);

        var myOptions = {
          zoom: 16,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.HYBRID
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"),
            myOptions);
    
        
    var marker = new google.maps.Marker({
      position: latlng, 
      map: map,
      title:"Google map"
    });
    google.maps.event.addListener(marker, 'click', function() {
        map.setZoom(16);
    });
 
}
