Imulus.Slideshow = function(){

  var self = this;

  var $slider = $('#slider');
  var $slides = $('#slider-nav li');
  var total = $slides.length;
  var current = 0;
  var speed = 6000; // ms
  
  var shouldLoop = true;
  var $slideTeasers = $('.slides .teaser');
  var factor = 290; // image + screenshot height


  self.initialize = function(){
    self.observe();
    self.loop.start();
  };

  self.observe = function(){
  	$slides.click(function(event){
  		event.preventDefault();
      self.loop.stop();
  		self.slides.goTo($(this).index(), true);
  	});

    $(window).bind({
      blur : function(event) {
        self.loop.stop();
      }
    });
  };


  self.slides = {
    goTo : function(index) {
      var $target = $slides.eq(index);
      $slides.removeClass('active');
      $target.addClass('active');

			$slideTeasers.fadeOut(500);
			$slideTeasers.eq(index).delay(300).fadeIn(500);

      var offset = index * factor;
      $slider.animate({
        top : (offset * -1) + 'px'
      });
      
      current = index;      
    },

    next : function(){
      var target = (current === total - 1) ? 0 : current + 1;
  		self.slides.goTo(target);
    }    
  };


  self.loop = {
    start : function() {
  		$.doTimeout('slideshow', speed, function(){
  			if (!shouldLoop) {
  				return false;
  	    }
        self.slides.next();
  			return true;
  		});
    },

    stop : function() {
  		shouldLoop = false; // kill it once
  		$.doTimeout( 'slideshow' ); // kill it again in case it's a zombie loop
    }
  };

  return self.initialize();
}


