﻿function TickerManager(displayPaneID, params) {
	var self = this;

	this.messageIndex = -1;
	this.outSpeed = 400;
	this.inSpeed = 1000;
	this.duration = 6000;
	this.interval = null;
	this.messages = [];
	this.canTicker = true;

	// Get a reference to the display pane and create the two message buckets
	this.displayPane = jQuery(displayPaneID);
	this.prepBucket = jQuery('<div/>');
	this.activeBucket = jQuery('<div/>');
	
	// Style the message buckets and make them children of the pane
	jQuery.each([this.prepBucket, this.activeBucket], function(i, e) {
		e.css({
			position: 'absolute',
			top: 0,
			height: self.displayPane.height(),
			width: self.displayPane.width()
		});
		self.displayPane.append(e);
	});

	// Toggle the 'can ticker' flag on hover to disable animation
	this.displayPane.hover(
		function() { self.canTicker = false; },
		function() { self.canTicker = true; }
	);

	// Adds a message element to the list
	this.addMessage = function(element) {
		var msg = jQuery(element);
		if (1 == msg.length) {
			this.messages.push(msg.html());
		}
	};

	// Shows the next message
	this.changeMessage = function() {
		var self = this;

		// Increment the message indexer (loop back if necessary)
		this.messageIndex++;
		if (this.messageIndex > (this.messages.length - 1)) {
			this.messageIndex = 0;
		}

		// Put the next message in the prep bucket
		this.prepBucket.html(this.messages[this.messageIndex]);

		// Animate the active bucket out
		this.activeBucket.animate({ left: this.displayPane.outerWidth() }, this.outSpeed);

		// Position the prep bucket just to the left of the pane, animate it in,
		// and then swap the bucket references
		this.prepBucket.css('left', -this.prepBucket.outerWidth() + 'px');
		this.prepBucket.animate({ left: 0 }, this.inSpeed, function() {
			var activeBucket = self.activeBucket;
			self.activeBucket = self.prepBucket;
			self.prepBucket = activeBucket;
		});
	};

	// Start the ticker by displaying the first message and setting up an
	// interval to change messages after that
	this.start = function() {
		var self = this;
		this.changeMessage();
		this.interval = setInterval(function() {
			if (self.canTicker) {
				self.changeMessage();
			}
		}, self.duration);
	};
}
