﻿// Create our UOE namespace object to keep the global namespace clean.
if (!uoe) var uoe = {};

uoe.rotator = function() { }

uoe.rotator.prototype = {
	initialize: function (container, options) {
		// Set default values
		this.viewTime = 5000;
		this.transitionTime = 1000;
		this.initialDelay = 0;
		this.loop = true;
		this.pauseOnMouseover = false;
		this.paused = false;
		this.random = false;

		// Merge supplied options
		$.extend(this, options || {});

		// Find my rotatables
		this.items = $(container).children("ul").children("li");
		if (this.items.length == 0)
			return;

		// Determine starting item
		var startIndex;
		if (this.random) {
			startIndex = Math.floor(Math.random() * this.items.length);
		} else {
			startIndex = this.items.length - 1;
		}
		this.nextIndex = this.currentIndex = startIndex;

		// Hide all but the starting item
		$(this.items).hide();
		this.items.eq(startIndex).show();


		var scope = this;

		// Bind hover handler
		if (this.pauseOnMouseover) {
			$(container).hover(function () { scope.paused = true; }, function () { scope.paused = false; });
		}

		// Start the timer after the initial delay.	
		setTimeout(function () { scope.startTimer(); }, this.initialDelay);
	},

	startTimer: function () {
		// If there was an initial delay, transition now.
		if (this.initialDelay > 0)
			this.transition();

		// Start the repeating timer.
		var scope = this;
		this.timer = setInterval(function () { scope.transition(); }, this.viewTime);
	},

	transition: function () {
		// If not looping and no more items, we're finished.
		if (!this.loop && this.currentIndex == 0) {
			// Cancel timer
			clearInterval(this.timer);
			return;
		}

		// Advance nextIndex, even while paused.
		if (this.nextIndex == 0)
			this.nextIndex = this.items.length - 1;
		else
			this.nextIndex = this.nextIndex - 1;

		// Perform transition if not paused
		if (!this.paused) {
			// Fade out the current and fade in the next simultaneously.
			this.items.eq(this.currentIndex).fadeOut(this.transitionTime);
			this.items.eq(this.nextIndex).fadeIn(this.transitionTime);

			this.currentIndex = this.nextIndex;
		}
	}
};

