﻿/*
 * content-rotator.js
 *
 * Implements the ContentRotator class.
 */

//
// Class: ContentRotator
//
// Used to implement a content rotator using the Mootools Fx.Scroll class.
//
ContentRotator = new Class({

    //
    // Function: initialize()
    //
    // Constructor for this class
    //
    initialize: function(controlName, containerName, contentItems, nextLink, prevLink) {
        var items = $$(contentItems);
        if (items == null || items.length == 0)
            return; // Items are missing on the page. Just exit?

        var control = $(controlName);
        if (control == null)
            return; // Top-level control (div) is missing. Just exit?

        var first = 1;           // The first item
        var last = items.length; // The last item
        var current = 1;         // The current item
        var width = items[0].getStyle('width').toInt() + items[0].getStyle('padding-right').toInt();

        // Create the Fx.Scroll object.
        var scroll = new Fx.Scroll(containerName, { transition: Fx.Transitions.Quad.easeInOut, wheelStops: false });

        // Add event handler for the "Next" link.
        // Scrolls to the next item.
        var next = $(nextLink);
        next.addEvent("click", function(e) {
            e.stop();
            if (++current > last)
                current = first; // Go to the beginning if we have reached the end.
            scroll.start((current - 1) * width, 0);
        });

        // Add event handler for the "Prev" link.
        // Scrolls to the previous item.
        var prev = $(prevLink);
        prev.addEvent("click", function(e) {
            e.stop();
            if (--current < first)
                current = last; // Go to the end if we have reached the beginning.
            scroll.start((current - 1) * width, 0);
        });

        // Automatically advance the content in the rotator every few seconds.
        var autoAdvance = (function() {
            if (++current > last)
                current = first; // Go to the beginning if we have reached the end.
            scroll.start((current - 1) * width, 0);
        });

        var timer = autoAdvance.periodical(8000); // 8000 milliseconds = 8 seconds.

        // Halt the auto-advance timer whenever a user scrolls over the control.
        control.addEvent("mouseover", function() {
            $clear(timer);
        });

        control.addEvent("mouseleave", function() {
            timer = autoAdvance.periodical(5000);
        });

    }   // initialize

});

