//*****************************
// Funzioni Jquery            *
//*****************************

    //Inizializzazione
    function init() {
        //Variabili globali e Detach immagini
        fadeVelocity='slow';
        infoBoxVelocity='normal';
        current=0;
        isAnimating=false;
        isBoxOpen=false;
        isBoxAnimating=false;
        total=$('#bg img').length;
        detachMe=$('#bg img').detach();

        //Rimuove icona preloader
        $('#preloader').remove();

        //Mostra prima immagine
        mostraPrimaImmagine();
    }

    //Mostra prima immagine
    function mostraPrimaImmagine() {
        //Controllo numero foto
        if(total==0) { return false; }

        //Flag animazione
        isAnimating=true;

        //Inserimento prima immagine attiva
        var $imgAttuale=detachMe.eq(current).css({'position': 'absolute', 'top': 0, 'left': 0, 'display': 'none'}).appendTo('#bg');

        //Calcolo dimensione e posizione immagine, poi animazione
        var dim=getImageDim($imgAttuale);
    	$imgAttuale.css({
	        width: dim.width,
    		height: dim.height,
		    left: dim.left,
	    	top: dim.top
    	}).fadeIn(fadeVelocity, function() {
            isAnimating=false;

            //Prev/Next controls
            prevNextControls();

            //Check key buttons
            checkKeyButtons();

            //Visualizza info button
            checkInfoButton();
	    });
    }

    //Prev/Next controls
    function prevNextControls() {
        //Controllo numero foto
        if(total<1) {
            return false;
        } else {
            //Box info slide down/up
            $('#boxinfoBtn').click(function() {
                //Controllo animazione
                if(isBoxAnimating) { return false; }
                isBoxAnimating=true;
                //Animazione slide
                $('#boxinfo-container').slideToggle(infoBoxVelocity, function() {
                    //Cambio icona plus minus
                    isBoxOpen=!isBoxOpen;
                    if(isBoxOpen) {
                        $('#boxinfoBtn').attr('title', 'Chiudi box informazioni').css('backgroundPosition','center bottom');
                    } else {
                        $('#boxinfoBtn').attr('title', 'Apri box informazioni').css('backgroundPosition','center top');
                    }
                    isBoxAnimating=false;
                });
            });
            if(total==1) { return false; }            
        }

        //Calcolo altezza div buttons wrapper
        var viewportHeight=$(document).height()-150; //150 = altezza menu' principale

        //Prev/Next click buttons
        $('#buttons_wrapper_sx').css('height', viewportHeight).show().click(function() {
            //Controllo animazione
            if(isAnimating) { return false; }
            showImage('prev');
        });
        $('#buttons_wrapper_dx').css('height', viewportHeight).show().click(function() {
            //Controllo animazione
            if(isAnimating) { return false; }
            showImage('next');
        });

        //Prev/Next hover buttons
        $('#buttons_wrapper_sx').hover(
            function() {
                $('#prevBtn').show();
            },
            function() {
                $('#prevBtn').hide();
            }
        );
        $('#buttons_wrapper_dx').hover(
            function() {
                $('#nextBtn').show();
            },
            function() {
                $('#nextBtn').hide();
            }
        );
    }

    //Check key buttons
    function checkKeyButtons() {
        if(total<1) {
            return false;
        }
        //Prev/Next keydown
        $(document).keydown(function(event) {
            //Tasti frecce
            var tasto=event.which;

            //Controlli tasti premuti dx, sx
		    if(tasto==37 || tasto==39) {
                //Controllo animazione
		        if(isAnimating) { return false; }
                if(total==1) { return false; }                
		        if(tasto==37) { showImage('prev'); }
    			if(tasto==39) { showImage('next'); }
            }

            //Controlli tasti premuti up, down
		    if(tasto==38 || tasto==40) {
                //Controllo animazione
                if(isBoxAnimating) { return false; }
                //Controllo stato box
                if(tasto==38 && isBoxOpen==false) { return false; }
                if(tasto==40 && isBoxOpen==true) { return false; }
                isBoxAnimating=true;
                //Animazione slide
                $('#boxinfo-container').slideToggle(infoBoxVelocity, function() {
                    //Cambio icona plus minus
                    isBoxOpen=!isBoxOpen;
                    if(isBoxOpen) {
                        $('#boxinfoBtn').attr('title', 'Chiudi box informazioni').css('backgroundPosition','center bottom');
                    } else {
                        $('#boxinfoBtn').attr('title', 'Apri box informazioni').css('backgroundPosition','center top');
                    }
                    isBoxAnimating=false;
                });
            }
    	});
    }

    //Check info button
    function checkInfoButton() {
        var tempBox=$("#boxinfo-"+(current+1));
        if(tempBox.length) {
            $('#boxinfoBtn').attr('title', 'Apri box informazioni').css('backgroundPosition','center top').show();
            tempBox.show();
            isBoxAnimating=false;
            isBoxOpen=false;
        }
    }

    function showImage(dir) {
        //Nasconde info box attuale
        $('#boxinfoBtn').hide();
        $("#boxinfo-"+(current+1)).hide();
        $('#boxinfo-container').hide();

        //Calcolo nuovo indice corrente
        current=(dir=='next') ? current+1 : current-1;
		if(current>=total) current=0;
		else if(current<0) current=total-1;

        //Flag animazione
        isAnimating=true;

        //Inserimento immagine successiva
        var $imgSuccessiva=detachMe.eq(current).css({'position': 'absolute', 'top': 0, 'left': 0, 'display': 'none'}).appendTo('#bg');
        //Calcolo dimensione e posizione immagine, poi animazione
        var dim=getImageDim($imgSuccessiva);
		$imgSuccessiva.css({
		    width: dim.width,
			height: dim.height,
			left: dim.left,
			top: dim.top
		}).fadeIn(fadeVelocity,function() {
    	    //Rimozione immagine precedente
	    	$("#bg img:not(:last)").remove();
            isAnimating=false;

            //Visualizza info button corrente
            checkInfoButton();
		});
    }

    //Resize window
    function resizeWindow() {
        //Controllo numero foto
        if(total==0) { return false; }
        //Immagine attiva
        var $imgAttuale=$('#bg img:last');
        //Calcolo dimensione e posizione immagine attuale
    	var dim	= getImageDim($imgAttuale);
        $imgAttuale.css({
    	    width: dim.width,
	    	height: dim.height,
    		left: dim.left,
	    	top: dim.top
    	});

        //Controllo numero foto
        if(total<=1) { return false; }
        //Calcolo altezza div buttons wrapper
        var viewportHeight=$(document).height()-150; //150 = altezza menu' principale
        $('#buttons_wrapper_sx, #buttons_wrapper_dx').css('height', viewportHeight);
    }

    //Calcolo dimensione e posizione immagine fullscreen centrata
    function getImageDim($img) {
        var window_width=$(window).width(),
	    window_height=$(window).height(),
		ratio_window=window_height/window_width,
		image_width=$img.width(),
		image_height=$img.height(),
		ratio_image=image_height/image_width,
		new_width, new_height;

    	if(ratio_window>ratio_image) {
	        new_height=window_height;
	    	new_width=Math.round(window_height/ratio_image);
        } else {
	        new_height=Math.round(window_width*ratio_image);
	    	new_width=window_width;
    	}

        return {
	        width: new_width+'px',
	    	height: new_height+'px',
    		left: (window_width-new_width)/2+'px',
		    top: (window_height-new_height)/2+'px'
	    };
    }


//*****************************
// Codice Jquery              *
//*****************************

$(document).ready(function() {

    //Cufon text
    Cufon('#main-menu li a', {
        hover: {
            color: '#f0812e'
        }
    });

    //Hack Internet Explorer
    Cufon.now();

    //Cufon menu show;
    $('#main-menu').show();

    //Prettyphoto popup video
    if($("a[rel^='prettyPhoto']").length) {
        $("a[rel^='prettyPhoto']").prettyPhoto({slideshow: false, show_title: false, allow_resize: false, autoplay: true, deeplinking: false, social_tools: false});
    }    

    //Disabilita menu' contestuale tasto destro
    $(document).bind('contextmenu', function() { return false; });

    //Controllo esistenza galleria
    if($("#bg").length) {

        //Resize window
        $(window).bind('resize', resizeWindow);

        //Preload immagini
	    $('#bg img').imagemonitor({
	    	'init': function() {
    			// call when this <b style="color:black;background-color:#a0ffff">plugin</b> start execute
	    	},
    		'onLoad': function(loadedImage, totalImage) {
	    		// call every single image loaded
    			// loadedImage: number of how many image/images are loaded
    			// totalImage: the total number of image/images loaded or not
	    	},
    		'onComplete': function(loadedImage) {
    			// call when all image is loaded
	    		// loadedImage: number of how many image/images are loaded
                init();
	    	}
    	});
    }

});
