



/* ---------------------------------------------------------------------
* scroller gallery plugin - v0001
* ------------------------------------------------------------------ */


(function ( $ ) {


    $.fn.scrollerGallery = function( options ){

        
        /* ---------------------------------------------------------------------
         * settings
         * ------------------------------------------------------------------ */
        var _this = this;
        
        var settings = $.extend({
            defaultGalleryScale     : true,
            galleryBig              : 600,
            gallerySmall            : 400,
            topBarHeight            : 100  || options.topBarHeight,
            xs                      : 320  || options.xs,
            sm                      : 480  || options.sm,
            md                      : 768  || options.md,
            lrg                     : 992  || options.lrg,
            xlrg                    : 1200 || options.xlrg,
            mode                    : 'xs'
        }, options );

        
        /* ---------------------------------------------------------------------
         * DOM elements
         * ------------------------------------------------------------------ */
        var scroller            = '.scroller' || this.selector,
            scrollerWrap        = scroller  + ' .scroller-wrap',
            container           = scrollerWrap + ' .scroller-container',
            leftBtn             = scrollerWrap + ' .left-arrow',
            rightBtn            = scrollerWrap + ' .right-arrow',
            slide               = container + ' .slide',
            scalebtn            = '.scrollerGalleryNav .scalebtn',
            cover               = slide + ' .cover',
            current             = slide + '.current',
            stopped             = true
        
        
        /* ---------------------------------------------------------------------
        * xlrg mode
        * ------------------------------------------------------------------- */
        xlrgMode = function(){
            var windowWidth = $(window).width();
            console.log('Enable: xlrg ' + windowWidth);
            settings.mode = 'xlrg';
        };
        
        
        /* ---------------------------------------------------------------------
        * lrg mode
        * ------------------------------------------------------------------- */
        lrgMode = function(){
            var windowWidth = $(window).width();
            console.log('Enable: lrg ' + windowWidth);
            settings.mode = 'lrg';
        };
        
        
        /* ---------------------------------------------------------------------
        * md mode
        * ------------------------------------------------------------------- */
        mdMode = function(){
            var windowWidth = $(window).width();
            console.log('Enable: md ' + windowWidth);
            settings.mode = 'md';
        };


        /* ---------------------------------------------------------------------
        * sm mode
        * ------------------------------------------------------------------- */
        smMode = function(){
            var windowWidth = $(window).width();
            console.log('Enable: sm ' + windowWidth);
            settings.mode = 'sm';
        };
        
        
        /* ---------------------------------------------------------------------
        * xs mode
        * ------------------------------------------------------------------- */
        xsMode = function(){
            var windowWidth = $(window).width();
            console.log('Enable: xs ' + windowWidth);
            settings.mode = 'xs';
        };
        
        
        /* ---------------------------------------------------------------------
        * which mode
        * ------------------------------------------------------------------- */
        whichMode = function(){
            
            var windowWidth = $(window).width();
            
            if( windowWidth >= settings.xlrg){
                xlrgMode();
                
            }else if( windowWidth >= settings.lrg){
                lrgMode();
                
            }else if( windowWidth >= settings.md){
                mdMode();
                
            }else if( windowWidth >= settings.sm){
                smMode();
                
            }else if( windowWidth >= settings.xs){
               xsMode();
            }
            
            console.log('Active mode: ' + settings.mode);
        };
        
        
        /* ---------------------------------------------------------------------
        * re calc fades
        * ------------------------------------------------------------------- */ 
        reCalcFades = function( instant ){
            
            var ol = $(current).offset().left,
                or = $(current).offset().left + $(current).width();
            
            //right side calc
            var rt = ($(window).width() - ( $(current).offset().left + $(current).outerWidth()));
            
            if(instant === true){
                $('.fadeBefore, .fadeAfter').css({
                    'display':'none'
                });
            }
            
            $('.fadeBefore') .css({
                'width' : ol,
                'left'  : 0
            });
            
            $('.fadeAfter') .css({
                'width' : rt,
                'left'  : or
            });
            
            if(instant === true){
                $('.fadeBefore, .fadeAfter').css({
                    'display':'block'
                });
            }else{
                $('.fadeBefore, .fadeAfter').fadeIn(200);
            }
                
        };
        
        
        /* ---------------------------------------------------------------------
        * add the side fades
        * ------------------------------------------------------------------- */ 
        this.addFades = function(){

            //fade before
            var fadeBefore = jQuery('<div/>', {
                class: 'fade fadeBefore'
            });

            //fade after
            var fadeAfter = jQuery('<div/>', {
                class: 'fade fadeAfter'
            });
            
            //appends the fade divs
            $(scrollerWrap).append(fadeBefore);
            $(scrollerWrap).append(fadeAfter);
            
            //calculate the fades
            reCalcFades();
        };
       
        /* ---------------------------------------------------------------------
        * add the close button
        * ------------------------------------------------------------------- */ 
        addCloseButton = function( _elem ){
            var closeButton = jQuery('<a/>', {
                class: 'closebtn',
                text: 'x close'
            });
            $(_elem).append( closeButton );
            return $(_elem);
        };

        /* ---------------------------------------------------------------------
        * reset the full screen slides
        * ------------------------------------------------------------------- */   
        resetSlides = function(){
            
            //move up the black div
            $('.black_get_bigger').css({
                width:'100%',
                height:'100%',
                position: 'fixed',
                top: '100%',
                left:0
            });

            //black bigger
            
            $('.black_get_bigger').velocity(
            { 
                top: 0 
            },{
                easing: 'easeInOutSine',
                duration: 500,
                complete: function(elements) { 
                   
                    setTimeout(function(){
                           
                        $('.black_get_bigger').fadeOut( 1500, function(){
                            $('.black_get_bigger').remove();
                        });

                        $('.big_slide .big_image').fadeOut( 300, function(){
                            $('.big_slide .big_image').remove();
                        });

                        $('.big_slide').fadeOut( 500, function(){
                            $('.big_slide').remove();
                        });

                    }, 300);
                }
            });
        };
        
        
        /* ---------------------------------------------------------------------
        * thumbnail to bigger image
        * ------------------------------------------------------------------- */ 
        thumbNailToBig = function(_elem){
            
            $('.mini_nav .slide').removeClass('active');
            $(_elem).parent().addClass('active');
            _img = $(_elem).parent().find('img').attr('src');
            $('.big_image').fadeOut(200, function(){
                 $('.big_image').attr('src', _img);
                 $('.big_image').fadeIn(300);
            });
        };
        
        
        /* ---------------------------------------------------------------------
        * add the cloned carousel
        * ------------------------------------------------------------------- */   
        addClonedContainer = function( _elem, _src ){
            
            _elem = addCloseButton(_elem);
            
            var carousel = $(slide + '.isClone').clone();
            
            $.each( carousel, function(index, value){
                if( $(this).children('img').attr('src') === _src){
                    $(this).addClass('active');
                }
            });
            
            var inside = jQuery('<div/>', {
                class: 'inside'
            });
            
            var mini_nav = jQuery('<div/>', {
                class: 'mini_nav'
            });
            
            $(mini_nav).append( $(inside) );
            $(carousel).appendTo( $(inside) );
            
            var new_img = jQuery('<img/>', {
                class: 'big_image',
                src: _src
            });
            
            $(new_img).css({
                'max-height' : $(window).height() - 400,
            });
            
            $(new_img).appendTo(_elem);
            $(mini_nav).appendTo(_elem);
            
            return _elem;
        };
        
        
        /* ---------------------------------------------------------------------
        * add the big slide
        * ------------------------------------------------------------------- */   
        addBigSlide = function(_elem, _src){
            var big_slide = jQuery('<div/>', {
                class: 'big_slide'
            });
            $(big_slide).css({
                'background': 'rgba(0,0,0,0.9)',
                'display' : 'none'
            });
            var new_elem = addClonedContainer( big_slide, _src );
            $(new_elem).appendTo('body').fadeIn();
        };
        
        
        /* ---------------------------------------------------------------------
        * add the bigger black overlay
        * ------------------------------------------------------------------- */  
        addBlackBigger = function( _from_top, _from_left, _width, _height ){
            
            var black_bigger = jQuery('<div/>', {
                class: 'black_get_bigger',
            });
            
            $(black_bigger).css({
                bottom:  0,
                left: '50%',
                width: 0,
                height: 0
            });  
            
            $(black_bigger).appendTo(container);          
            return black_bigger;
        };
        
        
        /* ---------------------------------------------------------------------
        * make full screen onclick
        * ------------------------------------------------------------------- */   
        makeFullScreen = function( _elem ){
            
   
            //elements
            _parent = $(_elem).parent(),
            _img = _parent.find('img');

            //dimentions
            _from_top   = $(_elem).offset().top ;
            _from_left  = $(_elem).offset().left;
            _new_width  = $(window).outerWidth();
            _new_height = $(window).height();


            //add the black overlay
            var black_bigger = addBlackBigger(_from_top, _from_left, _new_width, _new_height);
            
            $(black_bigger).velocity(
            { 
                width: _new_width,
                height: _new_height,
                left: 0,
            },{
                easing: 'easeInOutSine',
                duration: 500,
                complete: function(elements) { 
                    
                    //add the big slide
                    addBigSlide(_elem, _img.attr('src') );

                    //after a delay make the black slide down
                    setTimeout(function () {

                        $(black_bigger).velocity({
                             height: 0
                        },{
                            easing: 'easeInOutSine',
                            duration: 500,
                        });

                    }, 200 ); 
                }
            });
        };

        /* ---------------------------------------------------------------------
         * total width
         * ------------------------------------------------------------------ */
        totalWidth = function() {
            total = 0;
            $(slide).each(function() {
                total += $(this).width();
            });
            return total;
        };
       
       
        /* ---------------------------------------------------------------------
         * gallery scale
         * ------------------------------------------------------------------ */
        galleryScale = function() {
            
            var windowHeight = parseInt( $(window).height() ) - parseInt(settings.topBarHeight);
            
            switch(settings.mode){
                
                case 'xlrg': 
                    //var windowHeight = parseInt( $(window).height() ) - parseInt(settings.topBarHeight);
                    break;
                    
                case 'lrg':
                    //var windowHeight = parseInt( $(window).height() ) - parseInt(settings.topBarHeight);
                    break;
                
                case 'md': 
                    //var windowHeight = parseInt( $(window).height() ) - parseInt(settings.topBarHeight);
                    break;
                    
                case 'sm': 
                    windowHeight = 400;
                    break;
                    
                case 'xs': 
                    windowHeight = 400;
                    break;
            }
            
            return windowHeight;
        },
          
                
        /* ---------------------------------------------------------------------
         * offset
         * ------------------------------------------------------------------ */      
        offset = function(type) {

            leftOffset = 0;
            centreOffset = 0;

            // Calculate and return the width of all the images that are before the 'current' image
            if (type == "left") {
                $(slide).each(function() {
                    if ($(this).hasClass('current')) { return false; } else { leftOffset += $(this).width(); }
                });
                return leftOffset;
            }

            // Calculate and return the position for where to sit the center/current image
            if (type == "centre") {
                centreOffset = -( offset("left"))+($(scrollerWrap).width()/2)-($('.current').width()/2);
                return centreOffset;
            }
        };
       
       
        /* ---------------------------------------------------------------------
        * resetter
        * ------------------------------------------------------------------- */       
        resetter = function() {
            $(slide).height( galleryScale() );
            $(scroller).height( galleryScale());
            $(container).width( totalWidth());
            $(container).css('left', offset("centre") );
        };
       
       
        /* ---------------------------------------------------------------------
         * next and prev scroll buttons
         * ------------------------------------------------------------------ */
        nextPrevBtn = function(nextPrev) {
            
            var reverseDirection = false;

            if (reverseDirection) { 
                nextPrev === 'prev' ? nextPrev = 'next' : nextPrev = 'prev'; 
            }

            if ( stopped === true) {
                
                stopped = false;
                
                $('.fadeBefore, .fadeAfter').css({'display':'none'});
                
                if (nextPrev === 'prev') {
                    $(slide+':last').insertBefore(slide+':first');
                    $(container).css('left', parseFloat($(container).css('left'))-$(slide+':first').width());
                    //$(container).css('left', parseFloat($(container).css('left'))-$(current).prev().width());
                    $(slide+'.current').removeClass('current').prev().addClass('current');

                    $(container).velocity({ 
                        left:offset("centre")
                    },{
                        easing: 'easeInOutBack',
                        duration: 500,
                        complete: function(e) { 
                            stopped = true;
                            reCalcFades();
                        }
                    });
                };

                if (nextPrev === 'next') {
                    $(slide+':first').insertAfter(slide+':last');
                    $(container).css('left', parseFloat($(container).css('left'))+$(slide+':last').width());
                    //$(container).css('left', parseFloat($(container).css('left'))+$(current).next().width());
                    $(slide+'.current').removeClass('current').next().addClass('current');

                    $(container).velocity({ 
                        left:offset("centre")
                    },{
                        easing: 'easeInOutBack',
                        duration: 500,
                        complete: function(e) { 
                            stopped = true;
                            reCalcFades();
                        }
                    });
                };
            }
        };
        
        /* ---------------------------------------------------------------------
         * init the plugin
         * ------------------------------------------------------------------ */
        this.init = function() {
             
            
            whichMode();
             
             
            setTimeout(function() { 
                resetter(); 
            }, 500);

            // set teh height of the gallery
            $(slide).height( galleryScale() );

            // Dependant of what the default gallery size is, adjust the scale button image/class accordingly
            settings.defaultGalleryScale ? $(scalebtn).addClass('scaledown') : $(scalebtn).removeClass('scaledown');

            $(leftBtn).click(function() {
                nextPrevBtn('next'); 
            });

            $(rightBtn).click(function() { 
                nextPrevBtn('prev'); 
            });

            $("body").keydown(function(e) {
                if(e.keyCode == 37) { 
                    $(leftBtn).click(); 
                }
                if(e.keyCode == 39) { 
                    $(rightBtn).click(); 
                }
                
            });
            
        };
        
        
        /* ---------------------------------------------------------------------
         *  Center the current image, including when the users window is resized
         * ------------------------------------------------------------------ */
        centerCurrentImage = function() { 
            $(container).css('left', - (this.offset("left") ) + ( $(scrollerWrap).width() / 2) -( $('.current').width() / 2)); 
        };
        
        
        /* ---------------------------------------------------------------------
         * bind functions to dom elements
         * ------------------------------------------------------------------ */
        this.bindings = function(){
            
            $(document).on('click', cover, function() {
                makeFullScreen(this);
            });
            
            $(document).on('click', '.mini_nav .slide .cover', function() {
                thumbNailToBig(this);
            });
            
            $(document).on('click', '.big_slide .closebtn', function() {
                resetSlides();
            });
            
            $( window ).resize(function() {
                whichMode();
                centerCurrentImage(); 
                reCalcFades(true);
            });
            
        };
        
        
        /* ---------------------------------------------------------------------
         * scroller
         * ------------------------------------------------------------------ */
        this.scroller = function() {

            // If there are less than 5 slides, clone all the current slides so larger screens won't see any unsusual animations
            if ($(slide).length == 1) { 
                for ( var i = 0; i < 6; i++ ) { 
                    $(container).children('.slide').clone().addClass('isClone').appendTo(container); 
                } 
            }
            else if ($(slide).length == 2 || $(slide).length == 3) {  
                for ( var i = 0; i < 3; i++ ) { 
                    $(container).children('.slide').clone().addClass('isClone').appendTo(container); 
                } 
            }
            else if ($(slide).length >= 4 || $(slide).length <= 6) { 
                $(container).children('.slide').clone().addClass('isClone').appendTo(container);  
            }

            // Make first 'a' set to current
            $(slide).first().addClass('current');

            // Move images from the end to the front until the 'current' image is in the middle
            for ( var i = 0; i < (Math.floor($(slide).length/2)); i++ ) { 
                $(slide+':last').insertBefore(slide+':first'); 
            }

            // Set container width
            $(container).width( totalWidth() );

            //center the current image
            centerCurrentImage();
            
            /* -----------------------------------------------------------------
            * fade in the gallery
            * --------------------------------------------------------------- */
            $(scrollerWrap).fadeIn(1500);

        };

        /* ---------------------------------------------------------------------
        * run the plugin
        * ------------------------------------------------------------------ */
        

        this.init();
        this.bindings();
        this.scroller(); 
        
        setTimeout(function(){
            _this.addFades();
        }, 500);
        
        //force the resize code
        $(window).resize();
        
    };
    
}( jQuery ));






