var Showcase = Class.create({
  initialize: function(width){
    this.debug = false;         // stops the timer
    this.current = 0;           // current tab
    this.showcase_timeout = []; // slide timer
    this.open_tab_timer = [];   // open tab timer
    this.timeout = 8;           // seconds for tabswitch
    this.article_showcase = $('showcase');
    this.x_width = width;
    
    this.tabs = this.article_showcase.select('.showcase-tab');
    this.contents = this.article_showcase.select('.showcase-content');

    this.current_tab = this.tabs.first();

    this.bind_mouse_events();
    this.start_auto_timeout();
  },

  bind_mouse_events: function(){
    var my_self = this;

    this.tabs.each( function(tab, x){
      tab.index_x = x;

      tab.observe('mouseover', function(event){
        my_self.stop_auto_timeout();
        my_self.close_tab_timeout();
		my_self.open_tab_timeout(tab);
      });

      tab.observe('mouseout', function(event){
        my_self.close_tab_timeout();
        my_self.start_auto_timeout();
      });

      tab.observe('click', function(event){
        document.location = my_self.contents[tab.index_x].select('.read-on').first().href;
      });
    });

    this.contents.each( function(content) {
      content.observe('mouseover', function(event) {
        my_self.stop_auto_timeout();
      });

      content.observe('mouseout', function(event) {
        my_self.start_auto_timeout();
      });

      content.observe('click', function(event) {
        document.location = this.select('.read-on').first().href;
      });
    });
  },

  open: function(tab){
	  	tab_coord = this.x_width*tab.index_x;
 		if( this.current_tab == tab ) { return; }
		new Effect.Parallel([
			new Effect.Morph('showcase-large', 		{ sync: true, style: 'left: ' + (0 - this.x_width*tab.index_x) + 'px;' })
		], { 
		  duration: 0.8
		});

		this.current = tab.index_x;
		this.current_tab = tab;
  },

 	next: function(){
		this.current = (this.current + 1) % this.tabs.length;
		this.open(this.tabs[this.current]);
	},
	
	start_auto_timeout: function(){
		if( this.debug ) return;
		
		this.showcase_timeout.push(setInterval(function(){
			this.next();
		}.bind(this), this.timeout * 1000));
	},
	
	stop_auto_timeout: function(){
		if( this.debug ) return;
		
    this.showcase_timeout.each(function(timeout){
      clearInterval(timeout);
    });
    this.showcase_timeout.clear();
	},

  open_tab_timeout: function(tab){
    this.open_tab_timer.push( setTimeout( function(){
      this.open(tab);
    }.bind(this), 200));
  },

  close_tab_timeout: function(){
    this.open_tab_timer.each(function( timer ){
      clearTimeout(timer);
    });
  }
});
