var StoryRotator = Class.create(  {
	initialize: function(objectid, delaytime) {
	    this.objectid  = objectid;
	    this.delaytime = delaytime;
		this.container = $(this.objectid);
		this.linkscontainer = $(this.objectid+'-links');
		this.current = 0;
		this.paused = true;
		
		this.contents = this.container.select('.object-story-panel');
		this.contents.each(function(a,i) {
			if(i > 0) a.setOpacity(0);
		});
		
		this.links = this.linkscontainer.select('.object-story-dot');
		this.previouslinks = this.linkscontainer.select('.object-story-prev');
		this.nextlinks = this.linkscontainer.select('.object-story-next');
				
		this.attachEvents();
		this.autoPlay();
	}
	
	,attachEvents: function(){
		var c = this;
		c.links.each(function(a,j) {
			a.observe('click',function(e) { Event.stop(e); c.goTo(j); })
		});
		c.previouslinks.each(function(a,j) {
			a.observe('click',function(e) { Event.stop(e); c.previous(); })
		});
		c.nextlinks.each(function(a,j) {
			a.observe('click',function(e) { Event.stop(e); c.next(); })
		});
		return this
	}
	
	,fadeContent:function(j) {
		var c = this.contents;
		var l = this.links;
		c.each(function(a,i) {
			if (i == j) {
				Effect.Appear(a, {
					duration: 1.0
				});
				setTimeout(a.show.bind(a),1100);
			}
			else 
				Effect.Fade(a, {
					duration: 0.8
				});
		});
		l.each(function(a,i) {
			if(i == j) a.addClassName('object-story-dot-on');
			else a.removeClassName('object-story-dot-on');
		});
		this.current = j;
		return this
	}

	,next:function() {
		var l = this.contents;
		var c = this.current;
		var i = l[c+1]?(c+1):0;
		this.paused = true;
		return this.fadeContent(i)
	}

	,previous:function() {
		var l = this.contents;
		var c = this.current;
		var i = l[c-1]?(c-1):(l.length-1);
		this.paused = true;
		return this.fadeContent(i)
	}

	,goTo:function(j) {
		this.paused = true;
		return this.fadeContent(j)
	}
	
	,autoPlay:function() {
		if(!this.paused) { this.next(); }
		this.paused = false;
		setTimeout(this.autoPlay.bind(this),this.delaytime);
	}
});
