﻿var PuffRotator;

if (PuffRotator == undefined)
{
	PuffRotator = function(settings) {
		this.initialize(settings);
	};
}

PuffRotator.prototype.initialize = function(settings) {
	this.settings = settings;
	this.initSettings();

	// Default values;
	this.currentIndex = 0;
	this.maxItems = 0;
	this.items = {};
	this.timer = null;
	
	this.items = $(this.settings.puffContainer);
	this.maxItems = this.items.length;

	var maxHeight = 0;

	if (this.maxItems > 1)
	{
		var self = this;

		// Hide all but the first item
		for (var i = 0; i < this.maxItems; i++)
		{
			var item = $(this.items[i]);
			var itemHeight = item.height();
			if (itemHeight > maxHeight)
			{
				maxHeight = itemHeight;
			}
		
			if (i > 0)
			{
				item.css('display', 'none');
			}
			
			var navLink = $('<a href="#" style="color: #fff; font-family: \'Gill Sans\', \'Gill Sans MT\', Arial, Sans-Serif; font-size: 16px;">' + (i + 1) + '<' + '/a>');
			navLink.click(function() { self.goToItem($(this).text() - 1); return false; });
			navLink.appendTo(this.settings.navigationContainer);
			if (i < (this.maxItems - 1))
			{
				$(this.settings.navigationContainer).append('&nbsp;-&nbsp;');
			}
		}
	}
	else
	{
		$(this.settings.navigationContainer).css('display', 'none');
	}
		
	$(this.settings.puffContainer).parent().css('visibility', 'visible').parent().parent().parent().css('height', '' + maxHeight + 'px');
};

PuffRotator.prototype.initSettings = function() {
	this.ensureDefault = function(settingName, defaultValue) {
		this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
	};

	this.ensureDefault('interval', '10000');
	this.ensureDefault('puffContainer', '');
	this.ensureDefault('navigationContainer', '');

	delete this.ensureDefault;
};

PuffRotator.prototype.nextItem = function() {
	this.goToItem(this.currentIndex + 1);
};

PuffRotator.prototype.goToItem = function(index) {
	if (index >= this.maxItems)
	{
		index = 0;
	}
	this.showItem(index);
};

PuffRotator.prototype.showItem = function(showIndex) {
	var self = this;
	this.stop();
	$(this.items[this.currentIndex]).animate({ opacity: 0 }, 500, null, function() {
		$(this).css('display', 'none');
		$(self.items[showIndex]).css('opacity', '0').css('display', 'inline').animate({ opacity: 1 }, 500, null);
		self.currentIndex = showIndex;
	});	
	this.start();
};

PuffRotator.prototype.start = function() {
	if (this.maxItems > 1)
	{
		var self = this;
		this.timer = setInterval(function() { self.nextItem(); }, this.settings.interval);
	}
};

PuffRotator.prototype.stop = function() {
	clearInterval(this.timer);
};
