(function(){
    $.fn.carousel = function (content) {

        function repeat(str, num) {
            return new Array( num + 1 ).join( str );
        }

        return this.each(function () {
            var $wrapper = $('> div', this).css('overflow', 'hidden'),
                $slider = $wrapper.find('> ul'),
                $items = $slider.find('> li'),
                $single = $items.filter(':first'),

                singleWidth = $single.outerWidth(), 
                visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
                current_page = 1,
                pages = Math.ceil($items.length / visible);            
            
            // 1. Pad so that 'visible' number will always be seen, otherwise create empty items
            if (($items.length % visible) != 0) {
                $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
                $items = $slider.find('> li');
            }

            // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
            $items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
            $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
            $items = $slider.find('> li'); // reselect

            // 3. Set the left position to the first 'real' item
            $wrapper.scrollLeft(singleWidth * visible);

            // 4. paging function
            var $tagline = $('<div class="tagline"/>')
            var $tabs = $('<ul class="carousel-pages"/>');
            
            function go_to_page(page) {
                var dir = page < current_page ? -1 : 1,
                    n = Math.abs(current_page - page),
                    left = singleWidth * dir * visible * n;
                
                $wrapper.filter(':not(:animated)').animate({
                    scrollLeft : '+=' + left
                }, 500, function () {
                    if (page == 0) {
                        $wrapper.scrollLeft(singleWidth * visible * pages);
                        page = pages;
                    } else if (page > pages) {
                        $wrapper.scrollLeft(singleWidth * visible);
                        // reset back to start position
                        page = 1;
                    } 

                    current_page = page;
                });
                
                if (content) {
                    var $el = $($items[page]),
                        tagline = $el.find('img').attr('alt')
                    $tagline.html(tagline);                    
                };

                return false;
            }
            
            if (content) {
                $items.each(function(i){
                    $item = $($items[i])
                    if (!$item.hasClass('cloned')) {
                        var $a = $('<li><a href="#"><span class="ui-icon ui-icon-bullet"></span></a></li>').clone();
                        $a.bind('click', function(){
                            go_to_page(i);
                            return false;
                            /* TODO update class to show "current" */
                        })
                        $tabs.append($a);
                    };
                });
                $wrapper.after($tabs);
                $wrapper.after($tagline)
            };

            if (! content) {
                $wrapper.after('<a class="arrow back">&lt;</a><a class="arrow forward">&gt;</a>');
            };
            
            // 5. Bind to the forward and back buttons
            $('a.back', this).click(function () {
                return go_to_page(current_page - 1);                
            });
            
            $('a.forward', this).click(function () {
                return go_to_page(current_page + 1);
            });

            // create a public interface to move to a specific page
            $(this).bind('goto', function (event, page) {
                go_to_page(page);
            });
            
            $(this).bind('next', function(event){
                go_to_page(current_page + 1);
            })
            
            go_to_page(1);
        });  
    };
})(jQuery);