(function($) {
    var config = {
        type: 'rotate'
    };

    $.fn.bannerRotator = function(params) {
        $.extend(config, params);

        if (config.type == 'random') {
            $.bannerRotator.random();
        } else {
            var len = $('.banners a').length
            $('.banners a').each(function(i) {
                $(this).parent().prepend(this);
            });
            $.bannerRotator.doRotation(); //Begin the rotation
        }

        return this;
    };

    function LOG(msg) {
        if (window.console) {
            if (window.console.firebug != '') {
                console.log(msg);
            }
        }
    }

    $.bannerRotator = {

        /*
        * Show a random banner from the list.
        */
        random: function() {
            var numBanners = $('.banners a').length;
            var index = Math.floor(Math.random() * numBanners);
            var elem = $('.banners a').get(index);
            $(elem).show();
        },

        /*
        * Start the rotation, but wait for the duration of
        * the first banner
        */
        doRotation: function() {
            var topBanner = $('.banners a:last');
            topBanner.show();
            setTimeout($.bannerRotator.rotate, parseInt(topBanner.attr('rel')));
        },

        /*
        * Continue the rotation but delay by the duration of
        * the next banner.
        */
        rotate: function() {
            var topBanner = $('.banners a:last');
            topBanner.prev().show();

            topBanner.fadeOut(800, function() {
                $(this).parent().prepend($(this));
                $(this).show();
                setTimeout($.bannerRotator.rotate, parseInt($('.banners a:last').attr('rel')));
            });
        }
    }
})(jQuery);
