function callbackFunction(obj){
	jQuery('#rotator .current').html(obj.getCurrent());
}

function Rotator(obj){
	var index;
	var r_timer;
	var maxElements;
	var first;
	var fadeType="dualFade";
	var deltaAnimation=500;
	var rotatorObject=jQuery(obj);
	var rotatorPaused=true;
	var deltaRotatorChange=8000;
	var callback='';

	var self=this;

	this.init=function(){
		rotatorPaused=false;
		index=1;
		maxElements=rotatorObject.find(".rotatorSubstories .substory").length;
		rotatorObject.find('.mainImage .mainStory').each(function(){
			if(jQuery(this).hasClass('initial'))
			{
				jQuery(this).show().addClass('on');
			}
			else
			{
				jQuery(this).hide().addClass('off');
			}
		});
		jQuery(obj+" .mainImage").children(".mainStory").css("position", "absolute");
		self.play();

		rotatorObject.find('.rotatorSubstories .substory').click(function(){
			self.trigger(jQuery(this).attr('counter'));
			self.stop();
		});
	}

	this.setCallback=function(cf){
		callback=cf;
	}

	this.clean=function(val){
		var mod=val%maxElements;
		if(mod==0)
		{
			mod=maxElements;
		}
		return mod;
	}

	this.getCurrent=function(){
		return index;
	}

	this.getMax=function(){
		return maxElements;
	}

	this.getRotator=function(){
		return rotatorObject;
	}

	this.isCurrent=function(i){
		if(i==index){
			return true;
		}
		return false;
	}

	this.trigger=function(i){
		i=parseInt(i);
		rotatorObject.find('.rotatorSubstories .substoryOn').removeClass('substoryOn');
		var nextSubstory=rotatorObject.find('.rotatorSubstories .substory_'+i);
		nextSubstory.addClass('substoryOn');
		self.showStory(i);
		callbackFunction(self);
		index=i;
	}

	this.showStory=function(i)
	{
		self.animateFade(i);
	}

	this.animateFade=function(i){
		if(!self.isCurrent(i)){

			rotatorObject.find(".mainImage .on")
				.fadeOut(deltaAnimation)
				.removeClass("on")
				.addClass('off');

			rotatorObject.find(".mainImage .mainStory_"+i)
				.fadeIn(deltaAnimation)
				.addClass('on')
				.removeClass('off');

			index=parseInt(i);
		}
	}

	this.play=function(){
//		alert('play!!!');
			r_timer=setInterval(
				function(e){
					self.next();
			}, deltaRotatorChange);
			rotatorPaused=false;
	}

	this.stop=function(){
		clearInterval(r_timer	);
		rotatorPaused=true;
	}

	this.pause=function(){
		if(rotatorPaused==true){
			self.play();
		}
		else{
			self.stop();
		}
	}

	this.next=function(){
		self.trigger(self.clean(index+1));
	}

	this.prev=function(){
		self.trigger(self.clean(index-1));
	}

	this.sleep=function(){
		rotatorObject.find('.rotatorSubstories .substory').unbind('click');
		self.stop();
	}

	this.wake=function(){
		rotatorObject.find('.rotatorSubstories .substory').click(function(){
			self.trigger(jQuery(this).attr('counter'));
			self.play();
		});
	}
	self.init();
}

