/* Image Rotator */
var ImageRotator = function (options) {

	var defaultOptions = {
		autoRun: true,
		delay: 5000,
		fadeTime: 1000
	};

	this.__options = $.extend({}, defaultOptions, options);

	this._rotator = $("#rotator");
	this._rotatorImages = $("#rotator-images").children();
	this._imageContainer = this._rotator;
	this.currentIndex = 0;
	this.nextIndex = this.__getNextIndex();

	// Initialise images
	this._imageContainer.append($(this._rotatorImages[this.currentIndex]).clone().addClass("main").css(
		{
			top: 0,
			left: 0,
			position: "absolute"
		}));

	if (this.__options.autoRun) {
		this.run();
	}
}

ImageRotator.prototype = {

	__intervalHandle: null,

	__options: null,

	__getNextIndex: function () {

		var next = this.currentIndex + 1;

		if (next > (this._rotatorImages.length - 1))
			next = 0;

		return next;
	},

	__getPreviousIndex: function () {

		var previous = this.currentIndex - 1;

		if (previous < 0)
			previous = this._rotatorImages.length - 1;

		return previous;
	},

	isSwapping: false,

	run: function () {
		var self = this;

		self.setImage(0, null);

		clearTimeout(this.__intervalHandle);
		this.__intervalHandle = setTimeout(function () { self.nextImage(); }, this.__options.delay);
	},

	nextImage: function () {
		this.setImage(this.__getNextIndex());
	},

	previousImage: function () {
		this.setImage(this.__getPreviousIndex());
	},

	setImage: function (index, fadeTime) {

		var self = this;

		if (fadeTime === undefined)
			fadeTime = self.__options.fadeTime;

		if (self.isSwapping)
			return;

		self.isSwapping = true;

		var main = self._rotator.find(".main");
		var next = $(self._rotatorImages[index]).clone().addClass("temp").css(
			{
				position: "absolute",
				opacity: 0,
				top: 0,
				left: 0
			}).animate({
				opacity: 1
			}, fadeTime, function () {

				main.remove();
				$(this).attr("class", "main");

				self.currentIndex = index;
				self.nextIndex = self.__getNextIndex();

				self.isSwapping = false;

				clearTimeout(self.__intervalHandle);
				self.__intervalHandle = setTimeout(function () { self.nextImage(); }, self.__options.delay);

				self._rotator.trigger("imageChange");
			});

		self._imageContainer.append(next);
	},

	count: function () {
		return this._rotatorImages.length;
	}

};

