(function($) {
    
    /**
     * A custom jQuery plugin for the girtonjcr web application.
     *
     * This provides the base functionality and a 'register' method that can
     * be used to add additional functionality.
     */

    (function($) {

        // Namespace for girtonjcr plugins.
        var girtonjcr = {};

        /**
         * The main girtonjcr plugin. Use by passing in the name of the required method.
         */
        $.fn.girtonjcr = function(method) {
            if (girtonjcr[method]) {
                return girtonjcr[method].apply(this, Array.prototype.slice.call(arguments, 1));
            } else {
                $.error("Method " +  method + " does not exist on jQuery.girtonjcr");
            }
        }

        // Namespace for girtonjcr static plugins.
        $.girtonjcr = {};

        /**
         * Creates a slidehow from a list.
         */
        girtonjcr.slideshow = function() {
            return this.each(function() {
                // Set up the list.
                var list = $(this);
                var items = list.find("li");
                items.slice(1).hide();
                list.height(list.height());  // Lock the height of the list.
                items.css({
                    position: "absolute",
                    top: 0,
                    left: 0,
                    zIndex: 100
                })
                // Activate the slideshow.
                var currentSlide = 0;
                var maxSlides = items.length;
                function showSlide(n) {
                    if (n != currentSlide) {
                        items.eq(currentSlide).css("z-index", 100).fadeOut("slow");
                        items.eq(n).css("z-index", 200).fadeIn("slow");
                        currentSlide = n;
                    }
                }
                function nextSlide() {
                    if (currentSlide < maxSlides - 1) {
                        showSlide(currentSlide + 1);
                    } else {
                        showSlide(0);
                    }
                }
                setInterval(nextSlide, 5000);
            });
        }
        
        /**
         * Globally-activated plugins.
         */
        $(function() {
            $(".slideshow").girtonjcr("slideshow");
        });

    }(jQuery));
    
}(jQuery));
