/*******************************************************************
 ** Frontend Slideshows
 ******************************************************************/
(function ($) { // protect the lemmings

// Globals
var activeClass = 'frontend-slideshow-slide-active';

$.widget( "ui.frontendSlideshow", {

    options: {
        nyro_params : {
	    resizable: false,
	    autoSizable: false,
	    windowResize: false,
	    closeButton: false
        },
        jscroll_pane_params : {
            showArrows : false
        }
    },

    _create: function () {
	var self = this;
        self._setOption( 'lightbox_initialized', false );

        var gallery = self.element;
        var autoIsOn = true;
        
        // Get element surrounding current page # and get total page count
	var active;
	var span = $('div.switcher > ul > li > strong', gallery ).find('span:eq(0)');
	var count = $('div.gallery > ul.slide > li', gallery ).length;

        var thumbCarousel = null;
    if( count > 6 ) { 
        // Setup jCarouselLite and update page # after each slide
        $( '.gallery-holder .slide', gallery ).jcarousel({
            buttonNextHTML : null,
            buttonPrevHTML : null,
            wrap : 'circular',
            scroll : 5,
            initCallback : function (jc) {
                gallery.find( '.btn-prev' ).click( function () {
                    if( autoIsOn )
                        stopAutoOn();
                    
                    jc.prev();

                    return false;
                });
                gallery.find( '.btn-next' ).click( function () {
                    if( autoIsOn )
                        stopAutoOn();
                    
                    jc.next();

                    return false;
                });
            },
            itemFirstInCallback : {
                onAfterAnimation : function (jc, item, idx) {
                    // If user initiated the scroll
                    if( autoIsOn )
                        return false;

                    // Then highlight the new first item
                    item = $(item);
                    item.siblings().removeClass( activeClass );
                    item.addClass( activeClass );
                    
                    // Get the large image and caption for the first item
                    var link = item.find( 'a' );
                    var parent = link.parent();
                    var title = parent.find( '.frontend-slideshow-slide-title' );

                    // Get the current visible large item
                    var lgJC = $( '.gallery-preview .slide', gallery ).data( 'jcarousel' );
                    var lgItem = lgJC.get( lgJC.first );
                    
                    // Update large item with image/caption
                    lgItem.find( '.gallery-image img' ).attr( 'src', link.attr( 'href' ) );
                    lgItem.find( '.gallery-caption' ).html( title.html() );

                    return false;
                }
            }
	});
        
        thumbCarousel = $( '.gallery-holder .slide', gallery ).data( 'jcarousel' );
    } // if more than 6 thumbnails
        else {
            // Disable thumbnail slideshow control if < 6 images
            gallery
                .find( '.btn-prev, .btn-next' )
                .hide()
            ;
        }

        // Put gray box around first thumbnail

        gallery
            .find( 'div.gallery ul.slide > li:first' )
            .addClass( activeClass )
        ;


        // If there is a preview
        var preview = gallery.find( '.gallery-preview' );
        var previewSlides = preview.find( 'li' );
        var previewCap = gallery.find( '.gallery-preview .gallery-caption' );
        if( preview.length > 0 && previewSlides.length > 1 ) {

            // Update the preview image when small image is clicked
            $( '.gallery-holder .gallery-preview-link', gallery ).bind(
                'click.frontendSlideshow',
                function () {
                    // If large images are still automatically scrolling
                    if( autoIsOn ) {
                        // Then stop them 
                        stopAutoOn();
                    }
                    
                    // Get image caption
                    var link = $(this);
                    var parent = link.parent();
                    var title = parent.find( '.frontend-slideshow-slide-title' );

                    // Highlight clicked item
                    parent.siblings().removeClass( activeClass );
                    parent.addClass( activeClass );
                    
                    // Get large image carousel and currently visible item
                    var jc = $( '.gallery-preview .slide', gallery ).data( 'jcarousel' );
                    var item = jc.get( jc.first );
                    
                    // Update large image and caption
                    item.find( '.gallery-image img' ).attr( 'src', link.attr( 'href' ) );
                    item.find( '.gallery-caption' ).html( title.html() );

                    return false;
                }
            );

            // Get preview images to scroll
            $( '.gallery-preview .slide', gallery ).jcarousel({
                animation: 'slow',
                scroll: 1,
                auto: 4,
                wrap: 'circular',
                itemFallbackDimension: 557,
                itemVisibleInCallback: { 
                    onAfterAnimation: function (jc, item, idx, state) {
                        if( state == 'init' )
                            return;

                        // Determine active thumbnail, even if no carousel
                        var thumb;
                        if( thumbCarousel == null ) {
                            var thumbs = gallery.find(
                                'div.gallery > ul.slide > li'
                            );

                            var thumbIdx = (idx%thumbs.length) - 1;
                            thumb = thumbs.eq( thumbIdx );
                        }
                        else {
                            thumb = thumbCarousel.get( idx );
                        }
                        
                        // Highlight thumbnail 
                        thumb.siblings().removeClass( activeClass );
                        thumb.addClass( activeClass );
                    },
                    onBeforeAnimation: function(jc, item, idx, state) {
                        if( state == 'init' || thumbCarousel ==  null )
                            return;

                        // Scroll to next thumbnail if necessary
                        if( idx < thumbCarousel.first || idx > thumbCarousel.last ) {
                            thumbCarousel.scroll( $.jcarousel.intval( thumbCarousel.first + 1 ) );
                        }
                        
                        return;
                    } 
                }
	    });

        } // if preview
        else {
            // Disable clicking on thumbnails
            gallery.find( '.gallery-holder .gallery-preview-link, '
                          + '.gallery-holder .gallery-preview-link img ' )
                .addClass( 'disabled' )
                .click( function () { return false } )
            ;
        }

        var stopAutoOn = function () {
            var jc = $( '.gallery-preview .slide', gallery ).data( 'jcarousel' );
            if( jc != null ) jc.stopAuto();
            autoIsOn = false;
        }
            
        // Setup full screen button to trigger lightbox
        var nyroParams = {
            endFillContent : function (elts) { self._initLightbox(elts) }
        };
        $.extend( nyroParams, self.options.nyro_params );

        // Seems like there is no other way to transform an existing div into a LB
        $( 'a.btn-full', gallery ).bind( 
            'click.fronendSlideshow',
            function (e) {
                e.preventDefault();

                if( $.browser.msie && $.browser.version.substr( 0, 1 ) == "6" ) {
                    return false;
                }

                if( autoIsOn ) {
                    stopAutoOn();
                }

                // Except for doing it this way
                var fullscreenGallery = gallery.next( '.gal-full-wrapper' );

                nyroParams.forceType = fullscreenGallery;
                fullscreenGallery.nyroModalManual( nyroParams );
            }
        );

        return;
    }, // _create

    _initLightbox : function (elts) {
        var self = this;

        // Retrieve lightbox wrapper and the gallery within
        var wrapper = elts.contentWrapper;
        
        // Wrapper is hidden at this point, lets position it offscreen
        // and show it, so that we can initialize the carousel.  We need
        // to do this because starting index might not be the first image
        // and if we don't do things this way, we'll see a "jump" from the
        // first image to the starting index image
        var wrapperCSSLeft = wrapper.css( 'left' );
        wrapper.css( 'left', '-99999px' );
        wrapper.show();
        
        if( !self.options.lightbox_initialized ) {
            self._initFullGallery(elts);

            self._setOption( 'lightbox_initialized', true );
        }
        else {
            self._updateFullGallery(elts);
        }
        
        // Reposition lightbox wrapper and hide
        wrapper.css( 'left', wrapperCSSLeft );
        wrapper.hide();

        return;
    }, // _initLightbox

    _initFullGallery : function(elts) {
        var self = this;

        // Retrieve lightbox wrapper and the gallery within
        var wrapper = elts.contentWrapper;
        var fullGallery = wrapper.find( '.gal-holder' );
        
        // Get hold of the "1 of 8" text
        var curspan = $('#num-info', fullGallery).find('span:eq(0)');
        var count = $('div.gallery > ul.slide > li', fullGallery).length;
        
        var startingIdx = self._getActiveIndex();

        fullGallery.find( '.gallery-holder-full .slide' ).jcarousel({
            buttonNextHTML : null,
            buttonPrevHTML : null,
            scroll: 1,
            wrap: 'circular',
            start: startingIdx,
            initCallback : function (jc) {
                fullGallery.find( '.btn-prev' ).click( function () {
                    jc.prev();
                    return false;
                });
                fullGallery.find( '.btn-next' ).click( function () {
                    jc.next();
                    return false;
                });
            },
            itemVisibleInCallback : {
                onAfterAnimation : function (jc, item, idx, state) {
                    // Update "1 of 8" after each animation
		    curspan.text( jc.index( idx ) );
                }
            }
        });

        return;
    }, // _initFullGallery

    _updateFullGallery : function(elts) {
        var self = this;
        
        // Retrieve lightbox wrapper and the gallery within
        var wrapper = elts.contentWrapper;
        var fullGallery = wrapper.find( '.gal-holder' );

        // Get the current active image
        var startingIdx = self._getActiveIndex();

        // Get the lightbox carousel
        var jc = fullGallery.find( '.gallery-holder-full .slide' ).data( 'jcarousel' );
        
        // Do not animate this scroll
        var jcSpeed = jc.options.animation;
        jc.options.animation = 0;

        // Scroll to the active image
        jc.scroll( $.jcarousel.intval( startingIdx ) );

        // Restore animation settings
        jc.options.animation = jcSpeed;

        return;
    }, // _updateFullGallery

    _getActiveIndex : function () {
        var self = this;
        var gallery = self.element;

        var thumbCarousel 
            = gallery.find( '.gallery-holder .slide' ).data( 'jcarousel' );

        var slides = gallery.find( '.gallery-holder .slide li' );

        var activeThumb;
        var itemIdx;
        for( var i = 0; i < slides.length; i++ ) {
            var slide = slides.eq( i );
            if( slide.hasClass( activeClass ) ) {
                activeThumb = slide;
                itemIdx = i + 1;
            }
        }

        if( thumbCarousel != null ) {
            var jcIdx = activeThumb.attr( 'jcarouselindex' );
            itemIdx = thumbCarousel.index( jcIdx  );
        }

        return itemIdx;
    },

    destroy: function () {
	var self = this;
        var gallery = self.element;

        $( 'a.btn-full', gallery ).unbind( '.frontendSlideshow' );

        // jCarousellite does not have a destroy that unbind and removes added stuff, etc

	$.Widget.prototype.destroy.apply( this, arguments );
    } // destroy

}); // $.widget

})(jQuery); // function($)



