(function($){
    $.fn.smileCarousel = function(options){
        var defaults = {
            visibleItems: 4,
            shiftItems: 4,
            itemClass: ".thumb"
        };

        var options = $.extend(defaults, options);
        return this.each(function() {
            var container = $(this);
            container.wrap($("<div></div>").addClass("smile-carousel")).wrap($("<div></div>").addClass("smile-carousel-wrapper"));
            var carousel = container.closest(".smile-carousel");
            var wrapper = container.closest(".smile-carousel-wrapper");
            var item = container.find(options.itemClass);
            var shift = item.outerWidth(true) * options.shiftItems;

            var height = 0;
            item.each(function(){
                if (height < $(this).height())
                    height =  $(this).height();
            });
            container.addClass("smile-carousel-inner");
            item.addClass("smile-carousel-item");

            wrapper
            .height(height)
            .width(item.outerWidth(true) * options.visibleItems );
            
            container
            .height(height)
            .width(item.outerWidth(true) * item.length);
            
            carousel.append( "<a href=\"\" class=\"arrow-left\"></a>" 
                            + "<a href=\"\" class=\"arrow-right\"></a>" );

            arrowLeft  = carousel.find(".arrow-left");
            arrowRight = carousel.find(".arrow-right");
            arrowLeft. hide();
            arrowRight.hide();

            if ( item.length > options.visibleItems){
                $(arrowLeft, carousel).fadeIn();
                $(arrowRight, carousel).fadeIn();
            }

            arrowRight.click(function() {
//                $(arrowLeft).fadeIn();
                var pos = container.position().left - shift;
                if ((container.width() + pos) <= wrapper.width()) {
                    pos = wrapper.width() - container.width();
//                    $(this).fadeOut();
                }
                container.animate({ left:pos+"px"}, 1000, "linear");
                return false;
            });
            
            arrowLeft.click(function() {
//                arrowRight.fadeIn();
                var pos = container.position().left + shift;
                if (pos >= 0) {
                    pos = 0;
//                    arrowLeft.fadeOut();
                }
                container.animate({ left:pos+"px"}, 1000, "swing");
                return false;
            });
            
        });
        
        
    };
})(jQuery);