(function($){

    $.fn.imageReel = function(){
        var cc = this;
        var next = $(this).parent().find('.next');
        var prev = $(this).parent().find('.prev');
        var items = $(this).find('.items');
        var images = items.find('.item');
        var imageWidth = 0;
        var itemCount = images.length;
        var interval = 600;
        var index = 0;
        var page = $('body');
        var pageWidth = cc.parent().width();

        this.getImageWidth = function(){
            var width = 0;
            // Add up all of the section's widths
            images.each(function(){
                width += $(this).width();
            });
            
            cc.imageWidth = width;
        };


        // When the window gets resized, grab the new width
        $(window).resize(function(){
            pageWidth = cc.parent().width();
        });


        next.click(function(){
            cc.getImageWidth();
            // If sliding the whole interval will still cause the images to be within view...
            if (Math.abs(items.offset().left) + pageWidth + interval < cc.imageWidth) {

                if (index < itemCount -1) {
                    items.stop().animate({
                        'left': '-='+interval+'px'
                    });

                    ++index;
                };
            }
            else{
                // Otherwise slide only as far as is needed
                var currentOffset = Math.abs(items.offset().left) + pageWidth;
                var partialInterval = Math.abs(currentOffset - cc.imageWidth);
                
                items.stop().animate({
                    'left': '-='+ partialInterval +'px'
                });

                ++index;
            }

            return false;
        });


        prev.click(function(){
            cc.getImageWidth();
            if (index > 0 && items.offset().left + interval <= 10) {
                items.stop().animate({
                    'left': '+='+interval+'px'
                });

                --index;
            }
            else {
                items.stop().animate({
                    'left': '0px'
                });
                index = 0;
            }
            return false;                
        });

    };
    

})(jQuery);

