
window.heroshot = new (function($j) {

    // init
    $j(function() {
        $j('.heroshot').each(function() {
            var el = $j(this);
            make_heroshot(el);
        });
    });

    // selectors
    shot_selector = '.shot';
    
    // heroshots
    function make_heroshot(els) {
        var fade = els.find('input[name=fadetime]').val();
        var pause = els.find('input[name=showtime]').val();
        if(fade && pause) {
            var first = els.children(shot_selector).filter(':first');
            
            els.children(shot_selector)
                .not(':first')
                .css('display', 'none');
            first.show();
            begin(first, fade, pause);
        }
    }

    function begin(shot, fade, pause) {
        fade_ms = fade * 1000;
        pause_ms = pause * 1000;
        
        setTimeout(function() {
            var next = next_shot(shot);
            shot.fadeOut(fade_ms);
            next.fadeIn(fade_ms, function() {
                begin(next, fade, pause);
            });
        }, pause_ms);
    }

    function next_shot(shot) {
        var maybe = shot.next(shot_selector);
        if(maybe.length)
            return maybe
        else {
            return shot.parent()
                .children(shot_selector)
                .filter(':first');
        }
        
    }
    
})(jQuery);

