(function($) {

    $.fn.gallery = function() {
        
        var self = this;
        var images = [];

        var viewport = $('.gallery-viewport');
        var stepWidth = viewport.width();

        var currentImage = null;

        function stepNext() {
            var next = images.shift();           

            if(next !== undefined) {
                console.log( next );
//                currentImage = next;
                var s = viewport.scrollLeft() + stepWidth;
                viewport.css({
                    'opacity': 0.3
                }).animate({
                    'scrollLeft': s
                },
                1000,
                'linear',
                function(){
                    viewport.css({
                        'opacity': 1
                    })
                });
            }
        }
        function stepPrev() {
            var next = currentImage.next();
            currentImage = next;
            //viewport.scrollLeft(stepWidth);
            var s = viewport.scrollLeft() - stepWidth;
            viewport.animate({
                'scrollLeft': s
            },1000);
        }

        function init() {                
            var length = 0;

            self.find('.gallery-viewport img').each(function(){
                images.push(this);
                length += $(this).width();
            });

            $('.gallery-viewport .gallery-container').width(length);
            
            currentImage = images.shift();  

            $('.gallery-button-left').bind('click',stepPrev);
            $('.gallery-button-right').bind('click',stepNext);
        }        

        init();
    }
    $(window).load(function(){
        $('#gallery').gallery();
    });

})(jQuery);

