DY=window.DY||{};
DY.gallerie=[];
DY.activateGallerifyc=function (n) {
    //    console.log('attivo-'+'-cosa-'+n);
    // We only want these styles applied when javascript is enabled
    $('div.content_'+n).css('display', 'block');


    // Initially set opacity on thumbs and add
    // additional styling for hover effect on thumbs
    var onMouseOutOpacity = 0.67;
    $('#thumbs_'+n+' ul.thumbs_'+n+' li, div.navigation_'+n+' a.pageLink_'+n).opacityrollover({
        mouseOutOpacity:   onMouseOutOpacity,
        mouseOverOpacity:  1.0,
        fadeSpeed:         'fast',
        exemptionSelector: '.selected_'+n
    });

    var gallery = $('#thumbs_'+n).galleriffic({
        delay:                  3000,
        preloadAhead:           10,
        numThumbs:              8,
        enableTopPager:         false,
        enableBottomPager:      false,
        imageContainerSel:      '#slideshow_'+n,
        controlsContainerSel:   '#controls_'+n,
        captionContainerSel:    '#caption_'+n,
        loadingContainerSel:    '#loading_'+n,
        renderSSControls:       false,
        playLinkText:           'Play',
        pauseLinkText:          'Pause',
        prevLinkText:           'Previous',
        nextLinkText:           'Next',
        nextPageLinkText:       'Next &rsaquo;',
        prevPageLinkText:       '&lsaquo; Prev',
        enableHistory:          true,
        autoStart:              false,
        cycleThumbs:            true,
        syncTransitions:           true,
        defaultTransitionDuration: 900,
        onSlideChange:               function(prevIndex, nextIndex) {
            this.find('ul.thumbs_'+n).children()
            .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
            .eq(nextIndex).fadeTo('fast', 1.0);

        //            this.$captionContainer.find('div.photo-index').html('Photo '+ (nextIndex+1) +' of '+ this.data.length);
        },
        onPageTransitionOut:       function(callback) {
            this.fadeTo('fast', 0.0, callback);
        },
        onPageTransitionIn:        function() {


            var prevPageLink = this.find('a.prev_'+n).css('visibility', 'visible');
            var nextPageLink = this.find('a.next_'+n).css('visibility', 'visible');
            
//            var firstPageLink = this.find('a.firstPage_'+n).css('visibility', 'hidden');
//            var lastPageLink = this.find('a.lastPage_'+n).css('visibility', 'hidden');

            // Show appropriate next / prev page links
//            if (this.displayedPage > 0)
//            {
//                prevPageLink.css('visibility', 'visible');
//                firstPageLink.css('visibility', 'visible');
//            }
//
//            var lastPage = this.getNumPages() - 1;
//            if (this.displayedPage < lastPage)
//            {
//                nextPageLink.css('visibility', 'visible');
//                lastPageLink.css('visibility', 'visible');
//            }


            this.fadeTo('fast', 1.0);
        }
    });
    //    console.log( '#controls_'+n+' a.prev',gallery.find('#controls_'+n+' a.prev'));
    $('#controls_'+n+' a.prev').html('<img src="/stile/images/gl_prev.png" alt="Prev Image">').hide();
    $('#controls_'+n+' a.next').html('<img src="/stile/images/gl_next.png" alt="Next Image">').hide();
    
    $('.photogallery').hover(function(){
        $('#controls_'+n+' a.prev,#controls_'+n+' a.next').fadeIn("fast");
    },function(){
        $('#controls_'+n+' a.prev,#controls_'+n+' a.next').fadeOut("fast");
    });


    /**************** Event handlers for custom next / prev page links **********************/

    gallery.find('a.prev_'+n).click(function(e) {
        gallery.previousPage();
        e.preventDefault();
    });
    gallery.find('a.firstPage_'+n).click(function(e) {
        gallery.firstPage();
        e.preventDefault();
    });
    gallery.find('a.lastPage_'+n).click(function(e) {
        gallery.lastPage();
        e.preventDefault();
    });
    
    gallery.find('a.next_'+n).click(function(e) {
        gallery.nextPage();
        e.preventDefault();
    });
    
    window.galleria=gallery;

    /****************************************************************************************/


    /**** Functions to support integration of galleriffic with the jquery.history plugin ****/

    // PageLoad function
    // This function is called when:
    // 1. after calling $.historyInit();
    // 2. after calling $.historyLoad();
    // 3. after pushing "Go Back" button of a browser
    //    function pageload(hash) {
    //        // alert("pageload: " + hash);
    //        // hash doesn't contain the first # character.
    //        if(hash) {
    //          $.galleriffic.gotoImage(hash);
    //        } else {
    //            gallery.gotoIndex(0);
    //        }
    //    }
    gallery.gotoIndex(0);


// Initialize history plugin.
// The callback is called at once by present location.hash.
//    $.historyInit(pageload);
//
//    // set onlick event for buttons using the jQuery 1.3 live method
//    $("a[rel='history']").live('click', function(e) {
//        if (e.button != 0) return true;
//
//        var hash = this.href;
//        hash = hash.replace(/^.*#/, '');
//
//        // moves to a new page.
//        // pageload is called at once.
//        // hash don't contain "#", "?"
//        $.historyLoad(hash);
//
//        return false;
//    });

/****************************************************************************************/
};

DY.activeVideo='';
DY.videoPlayer=null;
DY.activateGallerifycVideo=function (n) {
    //    console.log('attivo-'+'-cosa-'+n);
    // We only want these styles applied when javascript is enabled
    $('div.content_'+n).css('display', 'block');

    //metto i titoli sotto le immagini icona
    $('#thumbs_6 li').each(function(){
        $(this).append('<span class="titleGalleryVideo">'+$(this).children('a').attr('title')+"</span>");
    });


    // Initially set opacity on thumbs and add
    // additional styling for hover effect on thumbs
    var onMouseOutOpacity = 0.67;
    $('#thumbs_'+n+' ul.thumbs_'+n+' li, div.navigation_'+n+' a.pageLink_'+n).opacityrollover({
        mouseOutOpacity:   onMouseOutOpacity,
        mouseOverOpacity:  1.0,
        fadeSpeed:         'fast',
        exemptionSelector: '.selected_'+n
    });

    DY.galleryV = $('#thumbs_'+n).galleriffic({
        delay:                  3000,
        preloadAhead:           10,
        numThumbs:              18,
        enableTopPager:         false,
        enableBottomPager:      false,
        imageContainerSel:      '#slideshow_'+n,
        controlsContainerSel:   '#controls_'+n,
        captionContainerSel:    '#caption_'+n,
        loadingContainerSel:    '#loading_'+n,
        renderSSControls:       true,
        playLinkText:           'Play',
        pauseLinkText:          'Pause',
        prevLinkText:           'Previous',
        nextLinkText:           'Next',
        nextPageLinkText:       'Next &rsaquo;',
        prevPageLinkText:       '&lsaquo; Prev',
        enableHistory:          false,
        autoStart:              false,
        syncTransitions:           true,
        defaultTransitionDuration: 900,
        onImageAdded:function(imageData,li){
        //            console.log('image added',imageData);
        },
        onSlideChange:function(prevIndex, nextIndex) {
            //            this.find('ul.thumbs_'+n).children()
            //            .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
            //            .eq(nextIndex).fadeTo('fast', 1.0);

            //creo il player:
            
            setTimeout(function(){
                
                dati=DY.galleryV.currentImage.caption[0].innerHTML.match(/([a-zA-Z0-9_-]+)(,([0-9]+),([0-9]+))?/);
                
                video=dati[1];
                
                width='100%';
                height='100%';
                if(typeof dati[3]!="undefined"){
                    width=dati[3]+'px';
                }
                if(typeof dati[4]!="undefined"){
                    height=dati[4]+'px';
                }
                
                if(DY.activeVideo!=video && video!=''){
                    DY.activeVideo=video;
                    //cambiamo il video
                    $(".slideshow *").remove();
                    html='<object style="width: '+width+'; height: '+height+';">';//height: 390px; 
                    html+='<param name="movie" value="http://www.youtube.com/v/'+video+'?version=3&autohide=1&autoplay=1&fs=1&cc_load_policy=0&rel=0&modestbranding=1&showinfo=0&feature=player_embedded&iv_load_policy=3">';
                    html+='<param name="allowFullScreen" value="true">';
                    html+='<param name="wmode" value="transparent">';
                    html+='<param name="allowScriptAccess" value="always">';
                    html+='<embed wmode="transparent" src="http://www.youtube.com/v/'+video+'?version=3&autohide=1&autoplay=1&fs=1&cc_load_policy=0&rel=0&modestbranding=1&showinfo=0&feature=player_embedded&iv_load_policy=3" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="'+width+'" height="'+height+'" ></object>';//height="344"

                    $(".slideshow")[0].innerHTML=html;
                
                    
                }
            },800);
                
              
           
        },
        onPageTransitionOut:       function(callback) {
            this.fadeTo('fast', 0.0, callback);
        },
        onPageTransitionIn:        function() {

            var prevPageLink = this.find('a.prev_'+n).css('visibility', 'hidden');
            var nextPageLink = this.find('a.next_'+n).css('visibility', 'hidden');

            // Show appropriate next / prev page links
            if (this.displayedPage > 0)
                prevPageLink.css('visibility', 'visible');

            var lastPage = this.getNumPages() - 1;
            if (this.displayedPage < lastPage)
                nextPageLink.css('visibility', 'visible');


            this.fadeTo('fast', 1.0);
        }
    });


    /**************** Event handlers for custom next / prev page links **********************/

    DY.galleryV.find('a.prev_'+n).click(function(e) {
        DY.galleryV.previousPage();
        e.preventDefault();
    });
    
    DY.galleryV.find('a.next_'+n).click(function(e) {
        DY.galleryV.nextPage();
        e.preventDefault();
    });

   
    DY.galleryV.gotoIndex(0);
    
    //setto le scritte nelle thumbs
    $('.titleGalleryVideo').each(function(){
        testo=$(this).text();
        trovati=testo.match(/^([a-zA-z 0-9]+ )\-(.*)/);
        if(trovati){
            $(this).html('<b>'+trovati[1]+'</b>-'+trovati[2]);
        }
    });

};

DY.attivaGalleryFancy=function(n){
    //    link=this.href.replace('#photogallery_','');
    $.fancybox(
        DY.gallerie[n],
        {
            'autoDimensions'	: false,
            'width'         	: 820,
            'height'        	: 710,
            'autoScale'		: false,
            'overlayOpacity' : 0.95,
            idGallery:n,
            onComplete:function(){
                //                console.log(this);
                //                link=this.href.replace('#photogallery_','');
                //                console.log('stop=>'+link);
                DY.activateGallerifyc(this.idGallery);
            //rimuovo il bottone di chiusura e metto iuna scritta
            //                $('#fancybox-close').css('background','none').html('<span id="bottoneChiusura">Chiudi</span>');
            }
        }
        );
}

DY.attivaGalleryFancyVideo=function(n){
    //    link=this.href.replace('#photogallery_','');
    $.fancybox(
        DY.gallerie[n],
        {
            'autoDimensions'	: false,
            'width'         	: 820,
            'height'        	: 680,
            'autoScale'		: false,
            'overlayOpacity' : 0.95,
            idGallery:n,
            onComplete:function(){
                DY.activateGallerifycVideo(this.idGallery);
            //rimuovo il bottone di chiusura e metto iuna scritta
            //                $('#fancybox-close').css('background','none').html('<span id="bottoneChiusura">Chiudi</span>');
            },
            onClosed:function(){
                DY.activeVideo=null;
            }
        }
        );
}
