var zermatt_heroes = (function($){
    var m = MochiKit.Base,
        itertools = MochiKit.Iter,
        ll = linkedlist;

    var config = {
        cycler: null,
        list_iterator: null,
        started: false,
        
        // These should all be set in the options passed to 'start', but
        // are recorded here for some sense of clarity.
        seconds_to_display: 10,
        transition_speed: 900,    // milliseconds
        container: '#hp-hero',
        image_holder: '#hp-hero-imgholder',
        text_holder: '#hp-hero-text',
        
        promo_records: []
    };
    var c = config;
    
    var fadein_promo = function(promo) {
        var old_image_source = $(c.image_holder).attr('src');
        /* Callback used to restore text */
        var set_hero_text = function() {
            $(c.image_holder).attr({});
            $(c.text_holder).html(promo.description || "");
        };
        
        /* 1. Copy the current image to the background (container)
         * 2. Clear the contents of the text holder.
         * 3. Hide 'image_holder', set source to be promo's image source,
         *    and fade the image in. After fading back in, set the text_holder
         *    text to the new promo's description and display it.
         */
        $(c.container)
            .css({'background-image': 'url('+old_image_source+')'})
            .find(c.text_holder).text('').end()
            .find(c.image_holder)
                .hide()
                .attr({'src': promo.image_source, 'alt': promo.title})
                .animate(
                    {opacity: 'show'},
                    {duration: c.transition_speed,
                     complete: set_hero_text}
                )
            .end();
    };
    
    var start = function(options) {
        if(config.started) {
            return false;
        }
        jQuery.extend(config, options || {});
        
        config.started = true;

        /* Now, build the cycler to rotate and fade this shit in and out */

        var promo_list = ll.Double(config.promo_records, {circular: true});
        config.list_iterator = itertools.iter(promo_list);
        config.list_iterator.next();
        config.cycler = new rlist.PeriodicCycler(
            config.list_iterator,
            config.seconds_to_display,
            fadein_promo
        );
        
        $(c.text_holder).hover(
            function() {config.cycler.pause(); return false;},
            function() {config.cycler.resume(); return false;}
        );
        
        config.cycler.start();
    };
    
    // Exported Names
    return {
        start: start,
        // Additional helpers for debugging
        fadein_promo: fadein_promo,
        get_config: function() {return config;},
        get_cycler: function() {return config.cycler;}
    };
    
})(jQuery);
