// 
//  jquery.jsslide.js
//  
//  Created by Matthias Link on 2011-12-17.
//  Copyright 2011 Interactive Systems. All rights reserved.
// 

$(function(){
  $.widget("ui.jsslide", {
    options: {
      delay: 2000,
      speed: "slow",
      autoStart: true,
      height: "200px",
      width: "100%",
      images: []
    },
    _init: function(){
      var $element = $(this.element);
      
      
      this.options.active_image = 0;
      this.options.images = $element.find("img");
          
      this.options.images.css({"position": "absolute", top:"0px"});

      
      $element.css({width: this.options.width, height: this.options.height, position: "relative", overflow: "hidden"});
      
      if (this.options.images.length > 1) {
        this.options.images.hide().first().show();
        
        if (this.options.autoStart) {
          this.start();
        }
      }
    },
    _animate: function() {
      var self = this, $element = $(this.element), next_image, $active_image, $next_image, speed = this._duration(this.options.speed);
      

      
      if ((this.options.active_image+1) == this.options.images.length) {
        next_image = 0;
      } else {
        next_image = this.options.active_image+1;
      }
      
      $active_image = $(this.options.images[this.options.active_image]);
      $next_image = $(this.options.images[next_image])

      
      // another approach: putting active image into a container and the next into another one.
      // the active-image container has z-index: 0, the next-image container. On animation start the next-image container
      // is hidden and faded in. On animation finish the next-image container gets emptyed and the next image is put into
      // the active container.
      
      $next_image.css("zIndex", 1000).fadeIn(speed, function(){
        var $this = $(this);
        
        $active_image.hide();
        $next_image.css("zIndex", 0);
      });
      
      this.options.active_image = next_image;
    },
    stop: function() {
      if (this.options.timer){
        clearInterval(this.options.timer);
        this.options.timer = undefined;
      }
    },
    start: function() {
      var self = this;
      if (!this.options.timer){
        this.options.timer = setInterval(function() {
          self._animate();
        }, this._duration(this.options.delay) + this._duration(this.options.speed));
      }
    },
    _duration: function(duration) {
      return jQuery.fx.off ? 0 : typeof duration === "number" ? duration : duration in jQuery.fx.speeds ? jQuery.fx.speeds[ duration ] : jQuery.fx.speeds._default;;
    }
  });
});
