// Copyright (c) 2005 Marty Haught, Thomas Fuchs 
//
// See http://script.aculo.us for more info
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

if(!Control) var Control = {};
Control.Slider = Class.create();

// options:
//  axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
//  onChange(value)
//  onSlide(value)
Control.Slider.prototype = {
  initialize: function(handle, track, options) {
    var slider = this;
    
    if(handle instanceof Array) {
      this.handles = handle.collect( function(e) { return $(e) });
    } else {
      this.handles = [$(handle)];
    }
    
    this.track   = $(track);
    this.options = options || {};

    this.axis      = this.options.axis || 'horizontal';
    this.increment = this.options.increment || 1;
    this.step      = parseInt(this.options.step || '1');
    this.range     = this.options.range || $R(0,1);
    
    this.value     = 0; // assure backwards compat
    this.values    = this.handles.map( function() { return 0 });
    this.spans     = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
    this.options.startSpan = $(this.options.startSpan || null);
    this.options.endSpan   = $(this.options.endSpan || null);

    this.restricted = this.options.restricted || false;

    this.maximum   = this.options.maximum || this.range.end;
    this.minimum   = this.options.minimum || this.range.start;

    // Will be used to align the handle onto the track, if necessary
    this.alignX = parseInt(this.options.alignX || '0');
    this.alignY = parseInt(this.options.alignY || '0');
    
    this.trackLength = this.maximumOffset() - this.minimumOffset();

    this.handleLength = this.isVertical() ? 
      (this.handles[0].offsetHeight != 0 ? 
        this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) : 
      (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth : 
        this.handles[0].style.width.replace(/px$/,""));

    this.active   = false;
    this.dragging = false;
    this.disabled = false;

    if(this.options.disabled) this.setDisabled();

    // Allowed values array
    this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
    if(this.allowedValues) {
      this.minimum = this.allowedValues.min();
      this.maximum = this.allowedValues.max();
    }

    this.eventMouseDown = this.startDrag.bindAsEventListener(this);
    this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
    this.eventMouseMove = this.update.bindAsEventListener(this);

    // Initialize handles in reverse (make sure first handle is active)
    this.handles.each( function(h,i) {
      i = slider.handles.length-1-i;
      slider.setValue(parseFloat(
        (slider.options.sliderValue instanceof Array ? 
          slider.options.sliderValue[i] : slider.options.sliderValue) || 
         slider.range.start), i);
      Element.makePositioned(h); // fix IE
      Event.observe(h, "mousedown", slider.eventMouseDown);
    });
    
    Event.observe(this.track, "mousedown", this.eventMouseDown);
    Event.observe(document, "mouseup", this.eventMouseUp);
    Event.observe(document, "mousemove", this.eventMouseMove);
    
    this.initialized = true;
  },
  dispose: function() {
    var slider = this;    
    Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
    Event.stopObserving(document, "mouseup", this.eventMouseUp);
    Event.stopObserving(document, "mousemove", this.eventMouseMove);
    this.handles.each( function(h) {
      Event.stopObserving(h, "mousedown", slider.eventMouseDown);
    });
  },
  setDisabled: function(){
    this.disabled = true;
  },
  setEnabled: function(){
    this.disabled = false;
  },  
  getNearestValue: function(value){
    if(this.allowedValues){
      if(value >= this.allowedValues.max()) return(this.allowedValues.max());
      if(value <= this.allowedValues.min()) return(this.allowedValues.min());
      
      var offset = Math.abs(this.allowedValues[0] - value);
      var newValue = this.allowedValues[0];
      this.allowedValues.each( function(v) {
        var currentOffset = Math.abs(v - value);
        if(currentOffset <= offset){
          newValue = v;
          offset = currentOffset;
        } 
      });
      return newValue;
    }
    if(value > this.range.end) return this.range.end;
    if(value < this.range.start) return this.range.start;
    return value;
  },
  setValue: function(sliderValue, handleIdx){
    if(!this.active) {
      this.activeHandleIdx = handleIdx || 0;
      this.activeHandle    = this.handles[this.activeHandleIdx];
      this.updateStyles();
    }
    handleIdx = handleIdx || this.activeHandleIdx || 0;
    if(this.initialized && this.restricted) {
      if((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
        sliderValue = this.values[handleIdx-1];
      if((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
        sliderValue = this.values[handleIdx+1];
    }
    sliderValue = this.getNearestValue(sliderValue);
    this.values[handleIdx] = sliderValue;
    this.value = this.values[0]; // assure backwards compat
    
    this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] = 
      this.translateToPx(sliderValue);
    
    this.drawSpans();
    if(!this.dragging || !this.event) this.updateFinished();
  },
  setValueBy: function(delta, handleIdx) {
    this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta, 
      handleIdx || this.activeHandleIdx || 0);
  },
  translateToPx: function(value) {
    return Math.round(
      ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) * 
      (value - this.range.start)) + "px";
  },
  translateToValue: function(offset) {
    return ((offset/(this.trackLength-this.handleLength) * 
      (this.range.end-this.range.start)) + this.range.start);
  },
  getRange: function(range) {
    var v = this.values.sortBy(Prototype.K); 
    range = range || 0;
    return $R(v[range],v[range+1]);
  },
  minimumOffset: function(){
    return(this.isVertical() ? this.alignY : this.alignX);
  },
  maximumOffset: function(){
    return(this.isVertical() ? 
      (this.track.offsetHeight != 0 ? this.track.offsetHeight :
        this.track.style.height.replace(/px$/,"")) - this.alignY : 
      (this.track.offsetWidth != 0 ? this.track.offsetWidth : 
        this.track.style.width.replace(/px$/,"")) - this.alignY);
  },  
  isVertical:  function(){
    return (this.axis == 'vertical');
  },
  drawSpans: function() {
    var slider = this;
    if(this.spans)
      $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
    if(this.options.startSpan)
      this.setSpan(this.options.startSpan,
        $R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
    if(this.options.endSpan)
      this.setSpan(this.options.endSpan, 
        $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
  },
  setSpan: function(span, range) {
    if(this.isVertical()) {
      span.style.top = this.translateToPx(range.start);
      span.style.height = this.translateToPx(range.end - range.start + this.range.start);
    } else {
      span.style.left = this.translateToPx(range.start);
      span.style.width = this.translateToPx(range.end - range.start + this.range.start);
    }
  },
  updateStyles: function() {
    this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
    Element.addClassName(this.activeHandle, 'selected');
  },
  startDrag: function(event) {
    if(Event.isLeftClick(event)) {
      if(!this.disabled){
        this.active = true;
        
        var handle = Event.element(event);
        var pointer  = [Event.pointerX(event), Event.pointerY(event)];
        var track = handle;
        if(track==this.track) {
          var offsets  = Position.cumulativeOffset(this.track); 
          this.event = event;
          this.setValue(this.translateToValue( 
           (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
          ));
          var offsets  = Position.cumulativeOffset(this.activeHandle);
          this.offsetX = (pointer[0] - offsets[0]);
          this.offsetY = (pointer[1] - offsets[1]);
        } else {
          // find the handle (prevents issues with Safari)
          while((this.handles.indexOf(handle) == -1) && handle.parentNode) 
            handle = handle.parentNode;
        
          this.activeHandle    = handle;
          this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
          this.updateStyles();
        
          var offsets  = Position.cumulativeOffset(this.activeHandle);
          this.offsetX = (pointer[0] - offsets[0]);
          this.offsetY = (pointer[1] - offsets[1]);
        }
      }
      Event.stop(event);
    }
  },
  update: function(event) {
   if(this.active) {
      if(!this.dragging) this.dragging = true;
      this.draw(event);
      // fix AppleWebKit rendering
      if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
      Event.stop(event);
   }
  },
  draw: function(event) {
    var pointer = [Event.pointerX(event), Event.pointerY(event)];
    var offsets = Position.cumulativeOffset(this.track);
    pointer[0] -= this.offsetX + offsets[0];
    pointer[1] -= this.offsetY + offsets[1];
    this.event = event;
    this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
    if(this.initialized && this.options.onSlide)
      this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
  },
  endDrag: function(event) {
    if(this.active && this.dragging) {
      this.finishDrag(event, true);
      Event.stop(event);
    }
    this.active = false;
    this.dragging = false;
  },  
  finishDrag: function(event, success) {
    this.active = false;
    this.dragging = false;
    this.updateFinished();
  },
  updateFinished: function() {
    if(this.initialized && this.options.onChange) 
      this.options.onChange(this.values.length>1 ? this.values : this.value, this);
    this.event = null;
  }
}



/*
Class: Scroller
	Adds a scrollbar to a specific div. The scrollbar is implemented using a Script.aculo.us slider.
	The class reparents the original div, creates a slider and ties the reparented div to the slider,
	setting any properties necessary on the divs to make it all work. The scrollbar can be styled using
	CSS. The track of the scrollbar has class 'scroll-track', 'scroll-track-top' and 'scroll-track-bot',
	the thumb has class 'scroll-handle', 'scroll-handle-top' and 'scroll-handle-bot'.
	
properties:
	myIndex - an integer used to generate a unique ID for use in, for example, div ids.
	outerBox - the div that holds the scrollpane + scrollbar
	innerBox - the div that holds the scrollpane
	innerHeight - the height of the inner box.
	viewportHeight - the height of the view onto the scrolled div.
	track - a div that holds the script.aculo.us slider (the scrollbar)
	trackHeight - the height of the slider
	handle - the div for the 'thumb' of the scrollbar
	handleHeight - the height of the thumb
	slider - the script.aculo.us slider itself
	ieDecreaseBy - a fudge factor used when calculating the width of innerBox
	
*/
var Scroller = Class.create();

/*
property: Scroller.ids
	A cache of Scrollers indexed by the ID of the original div.
 */
Scroller.ids = new Object();

/*
property: Scroller.i
	A unique ID generator.
 */
Scroller.i = 1;

Scroller.prototype = {
	/*
	constructor: initialize	
		Wrap the passed div in a scrollpane.
	
	parameters:	
		el - the div to add a scrollbar to.
	 */
  initialize: function(el) {
    this.outerBox = el;
    this.decorate();
  },
  
  /*
  function: decorate  
  	create the necessary elements to implement the scrollbar and wire up events.
   */
  decorate: function() {
	$(this.outerBox).makePositioned(); // Fix IE
	
	// Seed a unique ID
	Scroller.i = Scroller.i + 1;
	this.myIndex = Scroller.i;
	
	//wrap the existing content in an intermediate inner box
	this.innerBox = document.createElement("DIV");
	this.innerBox.className="scroll-innerBox";
	$(this.innerBox).makePositioned();	// Fix IE
	this.innerBox.style.cssFloat=this.innerBox.style.styleFloat='left';	// Need the scrollbar to appear next to the scrollpane
	this.innerBox.id="scroll-innerBox-"+Scroller.i;
	this.innerBox.style.top = "0px";
	
	//Transfer the contents of Outer Box to Inner Box
	while (this.outerBox.hasChildNodes()) {
		this.innerBox.appendChild(this.outerBox.firstChild);
	}
	this.innerBox.style.overflow="hidden";
	//turn off scrolling on the outer div
	this.outerBox.style.overflow="hidden";

	// create a track
	this.track=document.createElement('div');
	this.track.className="scroll-track";
	$(this.track).makePositioned();
	this.track.style.cssFloat=this.track.style.styleFloat='left';
	this.track.id="scroll-track-"+Scroller.i;
	// Fix IE line-height bug. Sigh.
	this.track.appendChild(document.createComment(''));

	// Create the top button
	this.tracktop=document.createElement('div');
	this.tracktop.className="scroll-track-top";
	$(this.tracktop).makePositioned();
	this.tracktop.style.cssFloat=this.tracktop.style.styleFloat='left';
	this.tracktop.id="scroll-track-top-"+Scroller.i;
	// Fix IE line-height bug. Sigh.
	this.tracktop.appendChild(document.createComment(''));
	
	// Create the bottom button
	this.trackbot=document.createElement('div');
	this.trackbot.className="scroll-track-bot";
	$(this.trackbot).makePositioned();
	this.trackbot.style.cssFloat=this.trackbot.style.styleFloat='left';
	this.trackbot.id="scroll-track-bot-"+Scroller.i;
	// Fix IE line-height bug. Sigh.
	this.trackbot.appendChild(document.createComment(''));

	// Create the handle
	this.handle=document.createElement('div');
	this.handle.className="scroll-handle-container";
	this.handle.id="scroll-handle-container"+Scroller.i;

	// Create the handle middle
	this.handle_middle=document.createElement('div');
	this.handle_middle.className="scroll-handle";
	$(this.handle_middle).makePositioned();
	this.handle_middle.id="scroll-handle-"+Scroller.i;
	// Fix IE line-height bug. Sigh.
	this.handle_middle.appendChild(document.createComment(''));

	// Create the handle top cap
	this.handletop=document.createElement('div');
	this.handletop.className="scroll-handle-top";
	$(this.handletop).makePositioned();
	this.handletop.id="scroll-handle-top-"+Scroller.i;
	// Fix IE line-height bug. Sigh.
	this.handletop.appendChild(document.createComment(''));

	// Create the handle bottom cap
	this.handlebot=document.createElement('div');
	this.handlebot.className="scroll-handle-bot";
	$(this.handlebot).makePositioned();
	this.handlebot.id="scroll-handle-bot-"+Scroller.i;
	// Fix IE line-height bug. Sigh.
	this.handlebot.appendChild(document.createComment(''));

	this.track.hide();
	this.tracktop.hide();
	this.trackbot.hide();

	this.outerBox.appendChild(this.innerBox);
	this.outerBox.appendChild(this.tracktop);
	this.handle.appendChild(this.handletop);
	this.handle.appendChild(this.handle_middle);
	this.handle.appendChild(this.handlebot);
	this.track.appendChild(this.handle);
	this.outerBox.appendChild(this.track);
	this.outerBox.appendChild(this.trackbot);

	this.slider = new Control.Slider($(this.handle).id, $(this.track).id, {axis:'vertical',
									 minimum: 0,
									 maximum: $(this.outerBox).clientHeight});
	this.slider.options.onSlide = this.slider.options.onChange = this.onChange.bind(this);
	setTimeout(this.resetScrollbar.bind(this, false), 10);

    this.domMouseCB = this.MouseWheelEvent.bindAsEventListener(this, this.slider);
    this.mouseWheelCB = this.MouseWheelEvent.bindAsEventListener(this, this.slider);
    this.trackTopCB = this.tracktopEvent.bindAsEventListener(this, this.slider);
    this.trackBotCB = this.trackbotEvent.bindAsEventListener(this, this.slider);
    
	//Events control
	$(this.outerBox).observe('DOMMouseScroll', this.domMouseCB); // Mozilla
	$(this.outerBox).observe('mousewheel', this.mouseWheelCB);// IE/Opera
	$(this.tracktop).observe('mousedown', this.trackTopCB);
	$(this.trackbot).observe('mousedown', this.trackBotCB);
  },
  
  release: function() {
    $(this.outerBox).stopObserving('DOMMouseScroll', this.domMouseCB);
	$(this.outerBox).stopObserving('mousewheel', this.mouseWheelCB);// IE/Opera
	$(this.tracktop).stopObserving('mousedown', this.trackTopCB);
	$(this.trackbot).stopObserving('mousedown', this.trackBotCB);
  },
  
  /*
  function: resetScrollbar  
  	Re-calculate the geometry of the scrollbar. Typically called from an event handler.
	
	args:	
		repeat - if true, set timer to re-calculate to fix IE bug on resize window.
   */
  resetScrollbar: function(repeat) {
		this.track.hide();
		this.tracktop.hide();
		this.trackbot.hide();
		this.enableScroll = false;
		this.innerHeight = $(this.outerBox).clientHeight;
		this.innerBox.style.height = this.innerHeight + "px";
		var newWidth = $(this.outerBox).clientWidth;

    	var tth = Element.getStyle(this.tracktop,"height");
    	if (tth)
    	   tth = tth.replace("px","");
    	else
    	   tth = 0;
    
        var hth = Element.getStyle(this.handletop,"height");
        if (hth)
    	   hth = hth.replace("px","");
    	else
    	   hth = 0;
    
		if (this.innerHeight < this.innerBox.scrollHeight) {
			this.viewportHeight = this.innerHeight - tth*2;
			this.slider.trackLength = this.viewportHeight;
			this.track.style.height = this.viewportHeight + "px";		
			this.handleHeight = Math.round(this.viewportHeight * this.innerHeight / this.innerBox.scrollHeight);	
			if(this.handleHeight < (hth*2))
				this.handleHeight = (hth*2);
			if (this.handleHeight < 10)
			     this.handleHeight = 10;
			this.handle.style.height = this.handleHeight + "px";
			this.handle_middle.style.height = this.handleHeight - hth*2 + "px";
			this.handletop.style.height = hth + "px";
			this.slider.handleLength = this.handleHeight;
			this.track.style.display = 'inline';
			this.tracktop.style.display = 'inline';
			this.trackbot.style.display = 'inline';
			this.ieDecreaseBy = 1;   // Firefox seems to have an off-by one error, so allow for it.
			if (this.outerBox.currentStyle) {
				var borderWidth = this.outerBox.currentStyle["borderWidth"].replace("px","");
				if(!isNaN(borderWidth)) {
					this.ieDecreaseBy = (borderWidth) * 2;
				}
			}
			newWidth = ($(this.outerBox).clientWidth - $(this.track).clientWidth - this.ieDecreaseBy);
			this.enableScroll = true;
		}
		//Set the width of of the scrollpane (aka innerBox).
		this.innerBox.style.width = newWidth + "px";
		//Fix IE resize event Bug 
		if(repeat) {
			setTimeout(this.resetScrollbar.bind(this, false), 10);
		}
  },
  
	//Mouse wheel code from http://adomas.org/javascript-mouse-wheel/
	MouseWheelEvent: function(event, slider) {
		var delta = 0;
		if (!event) //For IE.
			event = window.event;
		if (event.wheelDelta) { //IE/Opera.
			delta = event.wheelDelta / 120;
			/*if (window.opera) //In Opera 9, delta differs in sign as compared to IE
				delta = -delta;   But it isn't necessary with Opera v9.51*/
		} else if (event.detail) { //Mozilla case
			delta = -event.detail / 3;
		}
		if (delta)
			slider.setValueBy(-delta / 10);
		Event.stop(event);
	},

	trackbotEvent: function(event, slider) {
		if (Event.isLeftClick(event)) {	
			slider.setValueBy(0.2);
			Event.stop(event);
		}
	},

	tracktopEvent: function(event, slider) {
		if (Event.isLeftClick(event)) {
			slider.setValueBy(-0.2);
			Event.stop(event);
		}
	},

  /*
  function: onChange  
  	Called when the script.aculo.us slider has changed (i.e. when it has been dragged). Scroll the inner box.
	
	args:	
		val - not used.
   */
	onChange: function(val) {
		if(this.enableScroll)
			this.innerBox.scrollTop = Math.round (val * (this.innerBox.scrollHeight-this.innerBox.offsetHeight));
	}
}

/*
function: Scroller.setAll
	Search for divs of the class 'makeScroll' and wrap them in a Scroller.
 */
Scroller.setAll = function () {
	$$('.makeScroll').each(function(item) {
		Scroller.ids[item.id] = new Scroller(item);
	});
}

/*
function: Scroller.reset
	If the passed element has class 'makeScroll', wrap it in a Scroller.
 */
Scroller.reset = function (body_id) {
	if ($(body_id).className.match(new RegExp("(^|\\s)makeScroll(\\s|$)"))) {
	   if (Scroller.ids[body_id])
	       Scroller.ids[body_id].release();
	       
		Scroller.ids[body_id] = new Scroller($(body_id));
	}
}

/*
property: Scroller.updateAll
	Reset all of the scrollbars.
 */
Scroller.updateAll = function () {
	$H(Scroller.ids).each(function(pair) {
		Scroller.ids[pair.key].resetScrollbar(true);
	});
}

/*
	Hook up some global event handlers.
 */
Event.observe(window, "load", Scroller.setAll);
Event.observe(window, "resize", Scroller.updateAll);