;(function($) {
    
    var elem, titleBar, old, opts, settings, timer, current, started = false, waitingOn;
    
    $.fn.gallery = function(options) {
        opts = $.extend({}, $.fn.gallery.defaults, options);
        
        function _init() {
            elem = $(this);
            titleBar = elem.find('.gallery_titlebar').eq(0);
            
            settings = opts;
            current = -1;
            
            items = elem.children('.gallery_item').css('opacity', 0);
            waitingOn = items.find('img').bind('load', _loaded).bind('error', _error).length;
            
            _start();
            
            return false; 
        };
        
        function _loaded() {
            $(this).attr('loaded', 'true');
        };
        
        function _error() {
            $(this).attr('loaded', 'failed');
        };
        
        function _start() {
            started = true;
            _roll();
            timer = setInterval(_roll, settings.timeout);
        };
        
        function _hideTitleBar() { titleBar.animate({bottom: '-' + titleBar.height()+'px'}, settings.slideDownTime); }
        function _showTitleBar() { titleBar.animate({bottom:  0}, settings.slideUpTime); }
        
        function _roll() {
            var img, el, next, nextel;
            next = (current + 1) % items.length;
            nextel = $(items[next]);
            
            if(!nextel.find('img')[0].complete){
                setTimeout(_roll, 200);
                return;
            }
            
            _hideTitleBar();
            
            old = $(items[current]);
            current = next;
                
            nextel.css('opacity', 0).addClass('next_item').fadeTo(settings.fadeInTime, 1.0, _fadeDone);
            //elem.css('height', nextel.height()+'px');
        }
        
        function _fadeDone() {
            var el = $(items[current]);
            old.removeClass('active_item');
            el.removeClass('next_item').addClass('active_item');
            titleBar.find('.gallery_titlebar_content').text(el.attr('title'));
            _showTitleBar();
        }
        
        return this.each(_init);
    };
    
    $.fn.gallery.defaults = {
        timeout: 5000,   //ms
        fadeInTime: 500, //ms
        fadeOutTime: 500, //ms
        slideDownTime: 100,
        slideUpTime: 100
    };
})(jQuery);
