var SpockView = Class.create(
{
  initialize: function() 
  {
	Event.observe(window , "load" , this.run.bind(this));
  },
  
  run: function()
  {
	
	if($("next"))
	{
		Event.observe($("next") , "click" , this.next.bind(this));
		Event.observe($("prev") , "click" , this.prev.bind(this));
		Event.observe($("pause") , "click" , this.pause.bind(this));
		Event.observe($("go") , "click" , this.play.bind(this));
	}
	this.frames = $$(".SpockView");
	
	this.frameCount = this.frames.length;
	if(this.frameCount > 0)
	{
		this.current = 0;
		
		if(this.frameCount > 0)
			this.timeout = setTimeout(this.next.bindAsEventListener(this) , 5000);
		
		this.playing = true;
	}
  },
  
  fadeToFrame: function(id)
  {
	var index = this.frames.indexOf(id);
	  
	clearTimeout(this.timeout);
	if(this.playing = true)
	{
		var frameDuration = 7000;
    	this.timeout = setTimeout(this.next.bindAsEventListener(this) , frameDuration);
	}
	if(this.current%this.frameCount == index)
		return;
	
  	this.crossfade(this.current % this.frameCount , index );
	this.current = index;
  },

  next: function() 
  { 
  	clearTimeout(this.timeout);
	if(this.playing = true)
	{
		var frameDuration = 7000;
    	this.timeout = setTimeout(this.next.bind(this) , frameDuration);
	}
		
  	this.crossfade(this.current%this.frameCount , (++this.current)%this.frameCount );
  },
  
  
  crossfade: function(from , to)
  {
    this.frames[to].setStyle({zIndex: 1});
    this.frames[from].setStyle({zIndex: 2});
	this.frames[to].show();
	
	new Effect.Fade(this.frames[from] , {duration:1});

  },
  prev: function()
  {
  	clearTimeout(this.timeout);
	if(this.playing == true)
	{
		var frameDuration = 7000;
    	this.timeout = setTimeout(this.next.bind(this) , frameDuration);	
	}
  	this.crossfade(this.current%this.frameCount , (--this.current)%this.frameCount );
  },
  pause: function()
  {
    this.playing = false;
  	clearTimeout(this.timeout);
	Element.hide($("pause"));
	Element.show($("go"));
  },
  play: function()
  {
	this.playing = true;
	Element.hide($("go"));
	Element.show($("pause"));
	this.next();
  }


});

var spockView = new SpockView();