// SLIDING MENU FUNCTIONS
// Note: This code relies on the mootools javascript library. (http://mootools.net)

window.addEvent( 'load', startSliders ) ;

function setSource(img, src) {
  img.src = src;
}

function startSliders() 
{
  var sliders = $S( '.slider' ) ;
  sliders.each( function( e, i ) 
  {
    initSlider( e ) ;
    if ( e.getProperty("slideable") != 'no' ) e.slide.periodical( e.interval, e ) ;
  }) ;
}

function initSlider( e ) 
{
  // set properties
  var spans = e.getElements( 'span' ) ;
  e.a = spans[0] ;            /* span of scrolling images */
  e.b = spans[1] ;            /* 2nd span of scrolling images */
  e.xd = -1 ;                  /* x-delta for each movement cycle */
  e.interval = 20 ;           /* default cycle interval in milliseconds */
  e.w = e.a.offsetWidth ;     /* width of each image span */
  e.a.x = 0 ;
  e.b.x = e.a.x + e.a.offsetWidth ;
  e.a.setStyle( 'left', e.a.x + 'px' ) ;
  e.b.setStyle( 'left', e.b.x + 'px' ) ;
  //set methods
  e.slide = function() 
  {
    // move if the x-delta is non-zero, otherwise cancel the periodic event
    if ( this.xd == 0 ) this.eh = $clear( this.eh ) ;
    else 
    {
      this.a.x -= this.xd ;
      this.b.x -= this.xd ;
      // if a span drops off the end then send it back to the other side
      if ( this.xd > 0 ) 
      {
        if ( this.a.x + e.w <= 0 ) this.a.x = e.b.x + e.w ;
        if ( this.b.x + e.w <= 0 ) this.b.x = e.a.x + e.w ;
      }
      else if ( this.xd < 0 ) 
      {
        if ( this.a.x >= this.offsetWidth ) this.a.x = e.b.x - e.w ;
        if ( this.b.x >= this.offsetWidth ) this.b.x = e.a.x - e.w ;
      }
      this.a.setStyle( 'left', this.a.x + 'px' ) ;
      this.b.setStyle( 'left', this.b.x + 'px' ) ;
    }
  } ;
  e.handleMouseOver = function( event ) 
  {
    if ( e.getProperty("slideable") != 'no' ) 
    {
      // change the scroll direction depending on the location of the mouse
      event = event || window.event ;
      var ratio = Math.floor( (event.clientX - e.offsetLeft) / this.w * 100 )
      if (ratio < 43 ) this.xd = -2 ;
      else if (ratio > 57 ) this.xd = 2 ;
      else this.xd = -1 ;
      // only try and move it if it needs to be moved
      //if ( this.xd != 0 && !this.eh ) this.eh = this.slide.periodical( this.interval, this ) ;
    }
  } ;
  e.handleMouseOut = function( event )
  {
    // set the x-delta to zero (this will also cancel the periodical)
    this.xd = -1 ;
  }
  //set event handlers
  e.onmouseover = e.handleMouseOver.bindAsEventListener( e ) ;
  e.onmouseout = e.handleMouseOut.bindAsEventListener( e ) ;
}
