// Fader class for the Starfactor frontpage banner

var duration = 45                 // How long it takes to move from one slide to the next
var delay = 90                    // Delay in frames between transitions
var framespeed = 20               // Delay between frames in miliseconds
var root_element = 'banner'       // ID of the element to anchor the viewport in
var viewport_element = 'viewport' // ID of the UL viewport element

var Fader = Class.create();

Fader.prototype = {

  initialize: function( w, h ) {
    log( 'Fader initializing...' );

    // Instance variables
    this.timer = delay
    this.position = duration
    this.total_slides = 0
    this.source_slide = 0
    this.target_slide = 0
    this.width = w
    this.height = h

    // Resize the viewport
    Element.setWidth(viewport_element, this.width)
    Element.setHeight(viewport_element, this.height)
  },

  add_slide: function( image_url, target_url ) {
    var newSlide = document.createElement("li")
    newSlide.setAttribute('id','slide'+this.total_slides)
    newSlide.style.position = 'absolute'
    newSlide.style.left = '0px'
    newSlide.style.top = '0px'
    Element.appendObject( viewport_element, newSlide )

    image_tag = '<img src="' + image_url + '"/ >'
    if( target_url != '' )
      image_tag = '<a href="' + target_url + '">' + image_tag + '</a>'
    newSlide.innerHTML = image_tag

    this.total_slides ++
    this.hide_all()
    log('Added slide: slide'+(this.total_slides-1)+' Total slides: '+this.total_slides)
  },

  next_slide: function() {
    this.position = 0
    this.timer = delay
    this.target_slide = (this.target_slide+1)%this.total_slides
    s = $('slide'+this.source_slide)
    t = $('slide'+this.target_slide)
    log('Next slide requested: Source: slide'+this.source_slide+' Target: slide'+this.target_slide+' Total slides: '+this.total_slides)
    s.setOpacity(100)
    t.setOpacity(0)
    log('Moving from slide ' + this.source_slide + ' to ' + this.target_slide )
    this.hide_all()
  },

  fade_slide: function() {
    s = $('slide'+this.source_slide)
    t = $('slide'+this.target_slide)
    s.setOpacity( sineInOut(this.position, 1, 0, duration) )
    t.setOpacity( sineInOut(this.position, 0, 1, duration) )
    this.position ++
    if( this.position >= duration ) {
      t.setOpacity(100)
      this.source_slide = this.target_slide
      this.hide_all()
    }
  },

  // Check whether we need to start moving the fader
  update: function() {
    if( this.source_slide == this.target_slide ) {
      if( this.timer<0 ) {
        this.next_slide()
      } else {
        this.timer --
      }
    } else {
      this.fade_slide()
    }
    setTimeout(function() { fader.update(); }, framespeed);
  },

  hide_all: function () {
    for( i=0; i<this.total_slides; i++) {
      if( i == this.target_slide || i == this.source_slide ) {
        $('slide'+i).style.display = 'block';
      } else {
        $('slide'+i).style.display = 'none';
      }
    }
  }
}
