/*

itaRotator.js

V. 0.2

Created by Kevin Smith 9/23/11
Copyright Invisions Technical Arts LLC. All rights reserved.

*/

var itaRotator = function (options) {
	var self = this;
	self.images = options.images || ["/images/rotator/1.jpg"];
	self.interval = options.interval || 5000;
	self.selector = options.selector || "div#rotator";
	self.indicator = options.indicator || false;
	self.indicatorTemplate = options.indicatorTemplate || false;
	self.indicatorTemplateSelected = options.indicatorTemplateSelected || false;
	
	$(document).ready(function(e) {
		self.div = $(self.selector);
		self.image = $("<img />");
		self.currentImage = 0;
		
		if (self.indicator) {
			self.indicator = $(self.indicator);
			self.indicatorTemplate = $(self.indicatorTemplate);
			self.indicatorTemplateSelected = $(self.indicatorTemplateSelected).addClass("selected");
		}
		
		self.div.css("position", "relative");
		
		self.image.attr("src", self.images[0]).css("position", "absolute");
		
		self.transitionImage = self.image.clone().appendTo(self.div).addClass("tranImage");
		self.image.appendTo(self.div);
		
		for (var i = 0; i < self.images.length; i++) {
			$("<img />").attr("src", self.images[i]);
			
			if (self.indicator) {
				self.indicator.append(self.indicatorTemplate.clone());
			}
		}
		
		if (self.indicator) {
			self.indicator.children("img:first").replaceWith(self.indicatorTemplateSelected.clone());
		}
		
		setInterval(function () {
			self.image.attr("src", self.images[self.currentImage]).show();
			
			self.currentImage++;
			if (self.currentImage >= self.images.length) self.currentImage = 0;
			
			self.transitionImage.attr("src", self.images[self.currentImage]);
			
			setTimeout(function () { self.image.fadeOut() }, 10);
			
			if (self.indicator) {
				self.indicator.children("img.selected").replaceWith(self.indicatorTemplate.clone());
				self.indicator.children("img:nth(" + self.currentImage + ")").replaceWith(self.indicatorTemplateSelected.clone());
			}
		}, self.interval);
	});
}
