/**************************************************************

  Script		: SlideShow
  Version		: 1.3
  Authors		: Samuel Birch
  Desc		: 
  Licence		: Open Source MIT Licence

**************************************************************/

var SlideShow = Class.create({
  setOptions: function(){
    this.options = Object.extend(Object.extend({ }, arguments[0]), arguments[1] || { });
  },

  getOptions: function(){
    return {
      effect: 'fade', //fade|wipe|slide|random
      duration: 2000,
      transition: Effect.Transitions.linear,
      direction: 'right', //top|right|bottom|left|random
      color: false,
      wait: 5000,
      size: [1024,400],
      loop: false,
      thumbnails: false,
      thumbnailCls: 'outline',
      backgroundSlider: false,
      loadingCls: 'loading',
      onClick: false,
      imageZoom: true
    };
  },

  initialize: function(container, images, options){
    this.setOptions(this.getOptions(), options);

    this.productZoom = null;

    this.container = $(container);
    this.container.setStyle({
      position: 'relative'
    });
    if(this.options.onClick){
      Event.observe(this.container, 'click', function(){
        this.options.onClick(this.imageLoaded);
      }).bind(this);
    }
    
    
    this.imagesHolder = new Element('div').setStyle({
      position: 'absolute',
      top: this.container.getStyle('height'),
      left: 0,
      width: '0px',
      height: '0px',
      display: 'none'
    });
    this.container.appendChild(this.imagesHolder);

    if(typeof(images) == 'string' && !this.options.thumbnails){
      var imageList = [];
      $$('.'+images).each(function(el){
        imageList.push(el.src);
        this.imagesHolder.appendChild(el);
      });
      this.images = imageList;
      
    }else if(typeof(images) == 'string' && this.options.thumbnails){
      var imageList = [];
      var srcList = [];
      this.thumbnails = $$('.'+images);
      this.thumbnails.each(function(el,i){
        srcList.push(el.href);
        imageList.push(el.select('img')[0]);
        el.href = 'javascript:;';
        var self = this;
        Event.observe(el,'click',this.gotoandstop.bind(this, i));
      },this);
      this.images = srcList;
      this.thumbnailImages = imageList;
      
      if(this.options.backgroundSlider){
        this.bgSlider = new BackgroundSlider(this.thumbnailImages,{mouseOver: false, duration: this.options.duration, className: this.options.thumbnailCls, padding:{top:0,right:-2,bottom:-2,left:0}});
        this.bgSlider.set(this.thumbnailImages);
      }
    
    }else{
      this.images = images;
    }

    this.loading = new Element('div').addClassName(this.options.loadingCls).setStyle({
      position: 'absolute',
      top: 0,
      left: 0,
      zIndex: 3,
      display: 'none',
      width: this.container.getStyle('width'),
      height: this.container.getStyle('height')
    });
    this.container.appendChild(this.loading);
    
    this.oldImage = new Element('div').setStyle({
      position: 'absolute',
      top: 0,
      left: 0,
      opacity: 0,
      width: this.container.getStyle('width'),
      height: this.container.getStyle('height')
    }).addClassName('product-image product-image-zoom');
              this.oldImage.setAttribute('id','slideshowContainerOld');
              this.container.appendChild(this.oldImage);
    
    this.newImage = this.oldImage.cloneNode(true);
              this.newImage.setAttribute('id','slideshowContainerNew');
    this.container.appendChild(this.newImage);
    
    
    
    this.timer = 0;
    this.image = -1;
    this.imageLoaded = 0;
    this.stopped = true;
    this.started = false;
    this.animating = false;
  },
  
  load: function(){
    clearTimeout(this.timer);
    this.loading.setStyle('display','block');
    this.image++;
    var img = this.images[this.image];
    delete this.imageObj;
    
    doLoad = true;
    this.imagesHolder.select('img').each(function(el){
      var src = this.images[this.image];
      if(el.src == src){
        this.imageObj = el;
        doLoad = false;
        this.add = false;
        this.show();
      }
    },this);
    
    if(doLoad){
      this.add = true;
      this.imageObj = new Element('img');
      this.imageObj.src = img;
      Event.observe(this.imageObj, 'load', this.show.bind(this));
      //this.imageObj = new Asset.image(img, {onload: this.show.bind(this)});
    }
    
  },

  show: function(add){
    
    if(this.add){
      this.imagesHolder.appendChild(this.imageObj);
    }
    
    this.newImage.setStyle({
      zIndex: 1
    });
    var img = this.newImage.select('img')[0];
    if(img){
      var obj = this.imageObj.cloneNode(true);
      obj.setAttribute('id', 'image');
      img.parentNode.replaceChild(obj, img);
      this.newImage.setStyle({
        opacity: 0
      });
    }else{
      var obj = this.imageObj.cloneNode(true);
      obj.setAttribute('id', 'image');
      this.newImage.appendChild(obj);
    }
    this.imageLoaded = this.image;
    this.loading.setStyle('display','none');
    
    if(this.options.imageZoom && !this.productZoom){
      this.productZoom = new Product.Zoom('image', 'track', 'handle', 'zoom_in', 'zoom_out', 'track_hint', this.options.size);
    } else if (this.productZoom) {
      this.productZoom.setImage(obj);
    }

    if(this.options.thumbnails){
      if(this.options.backgroundSlider){
        var elT = this.thumbnailImages[this.image];
        this.bgSlider.move(elT);
        this.bgSlider.setStart(elT);
      }else{
        this.thumbnails.each(function(el,i){
          el.removeClassName(this.options.thumbnailCls);
          if(i == this.image){
            el.addClassName(this.options.thumbnailCls);
          }
        },this,i);
      }
    }

    this.effect();
  },
  
  wait: function(){
    this.timer = window.setTimeout(this.load.bind(this),this.options.wait);
  },
  
  gotoandstop: function(el){
    if (this.effectObj) this.effectObj.cancel();
    this.stop();
    this.play(el);
    this.stop();				 
  },
  
  play: function(num){
    if(this.stopped){
      if(num > -1){this.image = num-1};
      if(this.image < this.images.length){
        this.stopped = false;
        if(this.started){
          this.next.apply(this);
        }else{
          this.load.apply(this);
        }
        this.started = true;
      }
    }
  },
  
  stop: function(){
    clearTimeout(this.timer);
    this.stopped = true;
  },
  
  next: function(wait){
    var doNext = true;
    if(wait && this.stopped){
      doNext = false;
    }
    if(this.animating){
      doNext = false;
    }
    if(doNext){
      this.cloneImage();
      clearTimeout(this.timer);
      if(this.image < this.images.length-1){
        if(wait){
          this.wait();
        }else{
          this.load();	
        }
      }else{
        if(this.options.loop){
          this.image = -1;
          if(wait){
            this.wait();
          }else{
            this.load();	
          }
        }else{
          this.stopped = true;
        }
      }
    }
  },
  
  previous: function(){
    if(this.imageLoaded == 0){
      this.image = this.images.length-2;	
    }else{
      this.image = this.imageLoaded-2;
    }
    this.next();
  },
  
  cloneImage: function(){
    var img = this.oldImage.select('img')[0];
    if(img){
      img.parentNode.replaceChild(this.imageObj.cloneNode(true), img);
    }else{
      var img = this.imageObj.cloneNode(true);
      this.oldImage.appendChild(img);
    }
    
    this.oldImage.setStyle({
      zIndex: 0,
      top: 0,
      left: 0,
      opacity: 1
    });
    
    //this.newImage.setStyle({opacity:0});
  },
  
  
  effect: function(){
    this.animating = true;
    this.effectObj = {
      duration: this.options.duration,
      transition: this.options.transition
    };
    
    var myFxTypes = ['fade','wipe','slide'];
    var myFxDir = ['top','right','bottom','left'];
    
    if(this.options.effect == 'fade'){
      this.fade();
      
    }else if(this.options.effect == 'wipe'){
      if(this.options.direction == 'random'){
        this.setup(myFxDir[Math.floor(Math.random()*(3+1))]);
      }else{
        this.setup(this.options.direction);
      }
      this.wipe();
      
    }else if(this.options.effect == 'slide'){
      if(this.options.direction == 'random'){
        this.setup(myFxDir[Math.floor(Math.random()*(3+1))]);
      }else{
        this.setup(this.options.direction);
      }
      this.slide();
      
    }else if(this.options.effect == 'random'){
      var type = myFxTypes[Math.floor(Math.random()*(2+1))];
      if(type != 'fade'){
        var dir = myFxDir[Math.floor(Math.random()*(3+1))];
        if(this.options.direction == 'random'){
          this.setup(dir);
        }else{
          this.setup(this.options.direction);
        }
      }else{
        this.setup();
      }
      this[type]();
    }
  },
  
  setup: function(dir){
    if(dir == 'top'){
      this.top = -this.container.getStyle('height').toInt();
      this.left = 0;
      this.topOut = this.container.getStyle('height').toInt();
      this.leftOut = 0;
      
    }else if(dir == 'right'){
      this.top = 0;
      this.left = this.container.getStyle('width').toInt();
      this.topOut = 0;
      this.leftOut = -this.container.getStyle('width').toInt();
      
    }else if(dir == 'bottom'){
      this.top = this.container.getStyle('height').toInt();
      this.left = 0;
      this.topOut = -this.container.getStyle('height').toInt();
      this.leftOut = 0;
      
    }else if(dir == 'left'){
      this.top = 0;
      this.left = -this.container.getStyle('width').toInt();
      this.topOut = 0;
      this.leftOut = this.container.getStyle('width').toInt();
      
    }else{
      this.top = 0;
      this.left = 0;
      this.topOut = 0;
      this.leftOut = 0;
    }
  },
// TODO :  newImage opacity = 0 onload
  fade: function(skip){
    this.effectObj = new Effect.Appear(this.newImage, { duration:this.options.duration/1000, from:0.0, to:1.0 });
    //this.oldImage.hide();

    window.setTimeout(this.resetAnimation.bind(this),this.options.duration+90);
    if(!this.stopped){
      window.setTimeout(this.next.bind(this, true), this.options.duration+100);
    }
  },
  
  wipe: function(){
    this.oldImage.effects({
      duration: this.options.duration,
      transition: this.options.transition
    }).start({
      top: [0,this.topOut],
      left: [0, this.leftOut]
    })
    this.effectObj.start({
      top: [this.top,0],
      left: [this.left,0],
      opacity: [1,1]
    },this);
    window.setTimeout(this.resetAnimation.bind(this),this.options.duration+90);
    if(!this.stopped){
      window.setTimeout(this.next.bind(this),this.options.duration+100);
    }
  },
  
  slide: function(){
    this.effectObj.start({
      top: [this.top,0],
      left: [this.left,0],
      opacity: [1,1]
    },this);
    window.setTimeout(this.resetAnimation.bind(this),this.options.duration+90);
    if(!this.stopped){
      window.setTimeout(this.next.bind(this),this.options.duration+100);
    }
  },
  
  resetAnimation: function(){
    this.animating = false;
  }
  
});

/*************************************************************/
