/*
* Created : 3/17/2011
* Author  : pscott
* Purpose : a custom horizontal scroll bar class that can be attached to any element,
* 			it scrolls between the _target's child elements' left edge
*/

function HorizontalScroll(_left, _target, _right){
	_left.observe('mousedown', LeftPress);
	_right.observe('mousedown', RightPress);
  
  //observe target for mouseover & mouseout events to invoke mousewheel & left/right arrow key movement
  _target.observe('mouseover', StartListening);
  _target.observe('mouseout', StopListening);
  
  // Start on a random page
  jumpRandomPage(_target);
  
  
  /**
   * Jumps to a random page in the horizontal scroller
   * @param _target DOM element hosting the scoll elements
   */
  function jumpRandomPage(_target) {
	  var wrapper = _target.down();
	  var children = wrapper.childElements();
	  
	  // Get a random number
	  var randomPage = Math.ceil(Math.random()*(children.length/3));

	  //Scroll to that page
	  for (var i=0; i<randomPage; i++) {
		  Scroll(i);  		  
	  }	  	  
  }  
  
  function Scroll(move){
	  var wrapper = _target.down();
	  var children = wrapper.childElements();
	  
	  if(children.length > 1){
		  if(move < 0)
		  {
			  //remove last element and put it at the beginning 3 times
			  wrapper.insertBefore(children[children.length - 1].remove(), wrapper.firstDescendant());
			  wrapper.insertBefore(children[children.length - 2].remove(), wrapper.firstDescendant());
			  wrapper.insertBefore(children[children.length - 3].remove(), wrapper.firstDescendant());
		  }
		  else if(move > 0)
		  {
			  //remove beginning element and put it at the end 3 times
			  wrapper.appendChild(children[0].remove());
			  wrapper.appendChild(children[1].remove());
			  wrapper.appendChild(children[2].remove());
		  }
	  }
  }
  
  function LeftPress(e){
    Scroll(-1);
    
    return e.stop();
  }
  
  function RightPress(e){
    Scroll(1);
    
    return e.stop();
  }
  
  function MouseWheel(e){
    e = e ? e : window.event;
    var movement = e.detail ? e.detail / -3 : e.wheelDelta/120;
    
    Scroll(-1 * movement);
    
    return e.stop();
  }

  function KeyPress(e){
      e = e ? e : window.event;
      var keyCode = e.which ? e.which : e.keyCode;

      //left arrow
      if(keyCode == 37)
          return LeftPress(e);

      //right arrow
      else if(keyCode == 39)
          return RightPress(e);
      
      return 0;
  }
  
  function StartListening(){
	  Event.observe(window, 'DOMMouseScroll', MouseWheel);
	  Event.observe(document, 'mousewheel', MouseWheel);

	  Event.observe(window, 'keydown', KeyPress);
  }
   
  function StopListening(){
	  Event.stopObserving(window, 'DOMMouseScroll', MouseWheel);
	  Event.stopObserving(document, 'mousewheel', MouseWheel);
	
	  Event.stopObserving(window, 'keydown', KeyPress);
  }
}
