var downspeed = 15000;
var upspeed = 5000;
var newsDirection = 'bottom';
var toggleTop = false;
var startTime, endTime;
var resetScroll = function() {
  toggleTop = false;
  if (newsDirection == 'bottom') {
    // it has just completed the downward scroll,
    // reset it
    startTime = new Date().getTime();
    newsDirection = 'top';
    this.options.duration = upspeed;
    this.options.transition = Fx.Transitions.Sine.easeOut;
    this.toTop();
  } else {
    // it has just completed the reset,
    // start the scroll again
    startTime = new Date().getTime();
    newsDirection = 'bottom';
    this.options.duration = downspeed;
    this.options.transition = Fx.Transitions.linear;
    this.toBottom();
  }
}
/**
 * Calculates the 'duration' option based on the original speed.
 * Essentially just calculates the amount of milliseconds left over in
 * the duration of the transition.
 *
 * @param   int speed the original 'speed' (ms)
 * @return  int       the new speed (ms)
 */
function calculateScrollSpeed(speed) {
  var difference = endTime - startTime;
  var ret = 0;
  if (difference > 0) {
    ret = speed - difference; 
  } else {
    ret = speed;
  }
  return ret;
}
window.addEvent('domready',function() {
  var scroll = new Fx.Scroll('latestNews', {
    duration: downspeed,
    transition: Fx.Transitions.linear,
    onComplete: resetScroll
  });

  // stop the scroll when mouse is over the div
  $('latestNews').addEvent('mouseover', function(e) {
    if (toggleTop) return;
    scroll.stop();
    endTime = new Date().getTime();
  });

  // start the scroll again when mouse is out
  $('latestNews').addEvent('mouseout', function(e) {
    if (toggleTop) return;
    if (newsDirection == 'bottom') {
      scroll.options.duration = calculateScrollSpeed(downspeed);
      //startTime = new Date().getTime();
      scroll.toBottom();
    } else {
      scroll.options.duration = calculateScrollSpeed(upspeed);
      //startTime = new Date().getTime();
      scroll.toTop();
    }
  });

  // back to top button
  $('backToTop').addEvent('click', function(e) {
    if (newsDirection == 'bottom') {
      scroll.stop();
      startTime = new Date().getTime();
      scroll.options.duration = 1000; // just go back up fast!
      scroll.options.transition = Fx.Transitions.Sine.easeOut;
      newsDirection = 'top';
      scroll.toTop();
      toggleTop = true;
    }
  });

  // start the scroll!
  startTime = new Date().getTime();
  scroll.toBottom();
});

