

var SlideScrollers = {};
function CreateSlideScroller (containerId,options) {
  if (!options) options = {};
  // Set up 
  SlideScrollers[containerId] = new SlideScroller(containerId,options);
  Event.observe(window, 'load', function(event) {
    SlideScrollers[containerId].Setup();
  });
  return SlideScrollers[containerId];
}

function SlideScroller (containerId,options) {
  this.id = containerId; // Can always reference SlideScrollers[this.id] to get this
  this.started = false;
  this.spd = (options.speed || 1);
  this.variable_speed = (options.variable_speed || false);
  this.continue_on_hover = (options.continue_on_hover || false);
  this.mode = options.mode;
  this.pause = (options.pause || (this.mode == 'fade' ? 3 : 0)); // Default pause: 3 secs with fade, 0 with scroll
  //this.px = (options.pxdistance || 1);
  this.timer_interval = (options.timer_interval || 20);//200;
  this.direction = (options.direction || 'left');
  this.offsetLeft = options.offsetLeft;
  this.items = [];
  this.currentItem = [];
  this.previousFade = false;
  this.widths = [];
  this.debug = false;
  this.Setup = SlideScroller_Setup;
  this.Speed = SlideScroller_Speed;
  this.Stop = SlideScroller_Stop;
  this.Start = SlideScroller_Start;
  this.Back = SlideScroller_Back;
  this.Forward = SlideScroller_Forward;
  this.NextStep = SlideScroller_NextStep;
  return this;
}

function SlideScroller_Setup () {

  // Container:
  $(this.id).setStyle({'position':'relative','overflow':'hidden'});
  // Elements
  this.items = $(this.id).childElements();
  
  if (!this.continue_on_hover) {
    $(this.id).observe('mouseover', function(event) { 
      SlideScrollers[this.id].Stop(true);
      });
    $(this.id).observe('mouseout', function(event) { 
      SlideScrollers[this.id].Start();
      });
    }
  if (this.mode == "fade") {
    // Fix elements:
    var z = this.items.length+1;
    this.currentItem = 0;
    for (var i = 0; i < this.items.length; i++) {
      this.items[i].setStyle({
        //'display':'inline-block',
        //'float':'left',
        'position':'absolute',
        'top':'0px',
        'left':'0px'
        }).hide();
        //'zIndex': z
      z--;
      }
    }
  else {
    // Fix container:
    this.containerWidth = parseInt($(this.id).getWidth());
    //alert("w="+this.containerWidth);
    
    var xx;
    if (this.variable_speed) {
      $(this.id).observe('mousemove', function(event) { 
      	if (!SlideScrollers[this.id].userStopped) {
          var x = Event.pointerX(event);
        	//var mouseY = Event.pointerY(event);
        	//$('debug').innerHTML = 'mouseX:' + mouseX + '-- mouseY:' + mouseY;
          // Keep in mind that the scroller may have an alternate x coord itself:
          var l = (this.offsetLeft || $(this.id).offsetLeft);
          if (this.debug) $('debug').innerHTML = 'X: ' + parseInt(x);
          //if (!xx) { alert(l); xx=true }
          x -= l; // 0 = 0, so x can not be arger than the width of the container
          var w = SlideScrollers[this.id].containerWidth / 2; // half the width of the container
          x -= w; // subtract half that width of the coordinate, so exactly the middle of the slider gets coord 0
          x *= (100 / w); // max 100, so absolutely left its -100, middle = 0 and right its 100. NO matter what the width of the container is.
          if (this.debug) $('debug').innerHTML += ' wordt X: ' + parseInt(x);
          SlideScrollers[this.id].Speed(parseInt(x/10));
          }
        });
      }
   
    // Fix elements:
    var x = 0;
    for (var i = 0; i < this.items.length; i++) {
      this.items[i].setStyle({
        //'display':'inline-block',
        //'float':'left',
        'position':'absolute',
        'top':'0px',
        'left':x+'px'
        });
      this.widths[i] = SlideScroller_TotalWidth(this.items[i]);
      if (this.debug) $('debug').innerHTML += "<br/>item " + i + " width = " + this.widths[i] + " totalwidth = " + x;
      x += this.widths[i];
      //x += this.items[i].getWidth();
      } 
    this.totalwidth = x;
    if (this.debug) $('debug').innerHTML += "<br/>totalwidth = " + x;
    }
  this.Start();
}

function SlideScroller_Speed (spd) {
  if (spd == 0) {
    this.Stop(true);
    }
  else {
    if (spd < 0) {
      this.direction = 'right';
      spd *= -1;
      }
    else {
      this.direction = 'left';
      }
    this.spd = spd;
    if (!this.started) this.Start();
    }
}

function SlideScroller_Stop (internal) {
  this.started = false; 
  this.userStopped = (internal ? false : true); 
  if (this.timer) { self.clearTimeout(this.timer) }
}

function SlideScroller_Start () {
  if (this.started) return false;
  this.started = true;
  this.userStopped = false;
  if (this.spd == 0) this.spd = 1;
  //$('debug').innerHTML += "Started!";
  this.NextStep();
  return true;
}

function SlideScroller_Back () {
  //$('debug').innerHTML += "<br/>Back. ";
  if (this.direction != 'right') {
    //$('debug').innerHTML += "Yes, change dir. Spd="+this.spd;
    }
  this.direction = 'right';
  this.Start();
}

function SlideScroller_Forward () {
  if (this.direction != 'left') {
    }
  this.direction = 'left';
  this.Start();
}

function SlideScroller_NextStep () {
  if (this.started) {
    if (this.timer) { self.clearTimeout(this.timer); this.timer = false; }
    var spd = this.spd; // Calculate with same number entire function
    if (this.mode == "fade") {
      if (this.previousFade) {
        this.previousFade.fade({duration:spd}); // Then show
        }
      var element = this.items[this.currentItem];
      element.appear({duration:spd});
      this.previousFade = element;
      this.currentItem++;
      if (this.currentItem >= this.items.length) this.currentItem = 0;
      // Check for pause
      if (this.pause) {
        this.Stop(true);
        this.timer = self.setTimeout("SlideScrollers['" + this.id + "'].Start()",this.pause * 1000);
        }
      }
    else {
      var px = (this.direction == 'right' ? spd : (spd * -1));
      for (var i = 0; i < this.items.length; i++) {
        var l = parseInt($(this.items[i]).getStyle('left'));
        l += px;
        this.items[i].setStyle({
          'left':(l)+'px'
          });
        var w1 = this.widths[i];//SlideScroller_TotalWidth(this.items[i]);
        
        // Check for pause
        if (this.pause && (l == 0 || (l > 0 && l < spd))) {
          this.items[i].setStyle({ // Todo: this isn't entirely right. Coords changes now. Coords of other items should change as well.
            'left':'0px'
            });
          this.Stop(true);
          this.timer = self.setTimeout("SlideScrollers['" + this.id + "'].Start()",this.pause * 1000);
          }
        
        // Check if the item is completely out of sight, then return it to the other side
        if (this.direction == 'right') {
          var dif = l - (this.totalwidth-w1);
          if (dif > 0) { // Yes! Dissapeared right
            this.items[i].setStyle({
              'left':'-'+(w1-dif)+'px'
              });
            if (this.debug) $('debug').innerHTML += "<br/>'Place item " + i + " at X " + (w1-px) + " (dif="+dif+")'"; 
            }
          }
        else {
          var dif = (w1 + l);
          if (dif < 0) { // Yes! Dissapeared left
            this.items[i].setStyle({
              'left':(this.totalwidth-w1+dif)+'px'
              });
            if (this.debug) $('debug').innerHTML += "<br/>'Place item " + i + " at X " + (this.totalwidth-w1) + " (dif="+dif+")'"; 
            }
          }
        
        //x += SlideScroller_TotalWidth(this.items[i]);
        }
      }
    if (!this.timer) this.timer = self.setTimeout("SlideScrollers['" + this.id + "'].NextStep()",this.timer_interval);
    }
}

function SlideScroller_TotalWidth (el) {
  var w = $(el).getWidth();
  /*var p = parseInt($(el).getStyle('paddingLeft'));
  if (p && p != "NaN") { w += p }
  p = parseInt($(el).getStyle('paddingRight'));
  if (p && p != "NaN") { w += p }*/
  var b = parseInt($(el).getStyle('borderLeft'));
  if (b && b != "NaN") { w += b }
  b = parseInt($(el).getStyle('borderRight'));
  if (b && b != "NaN") { w += b }
  
  var m = parseInt($(el).getStyle('marginLeft'));
  if (m && m != "NaN") { w += m }
  m = parseInt($(el).getStyle('marginRight'));
  if (m && m != "NaN") { w += m }
  return w;
}


