/*
 * scrollable.js (V.1.0.1)
 * Implements vertical scrolling on DIV layers.
 * @author : Jean Semere (Baggage Claim)
 *
 * You have no right to use or redistribute this code unless Baggage Claim SARL
 * authorizes you to do so.
 *
 */

Scrollable = Class.create();
Scrollable.prototype =
{
	initialize: function(name, options)
	{
		this.busy = false;
		this.name = name;
		this.element = $(this.name);
		options = options || {};
		this.upButton = options.up || false;
		this.downButton = options.down || false;
		this.realHeight = parseInt($(this.name).offsetHeight);
		this.visibleHeight = parseInt($(this.name).parentNode.offsetHeight);
		if (this.upButton)
			Event.observe(this.upButton, 'click', this.upAction.bindAsEventListener(this), false);
		if (this.downButton)
			Event.observe(this.downButton, 'click', this.downAction.bindAsEventListener(this), false);
		Event.observe(this.name, 'DOMMouseScroll', this.scrollWheel.bindAsEventListener(this), false);
		Event.observe(this.name, 'mousewheel', this.scrollWheel.bindAsEventListener(this), false);
	},
	
	update: function()
	{
		this.realHeight = parseInt($(this.name).offsetHeight);
		this.visibleHeight = parseInt($(this.name).parentNode.offsetHeight);
	},
	
	upAction: function()
	{
		this.update();
		distance = parseInt($(this.name).offsetTop);
		if (distance < -0.3*this.visibleHeight)
			new Effect.Move(this.name, {x: 0, y: Math.floor(0.3*this.visibleHeight), mode:"relative"});
		else if (distance >= 0)
			return;
		else
			new Effect.Move(this.name, {x: 0, y: -distance, mode: "relative"});
	},
	
	downAction: function()
	{
		this.update();
		distance = this.realHeight - this.visibleHeight + parseInt($(this.name).offsetTop);
		if (distance > 0.3*this.visibleHeight)
			new Effect.Move(this.name, {x: 0, y: -Math.floor(0.3*this.visibleHeight), mode: "relative"});
		else if (distance <= 0)
			return;
		else
			new Effect.Move(this.name, {x: 0, y: -distance, mode: "relative"});
	},
	
	lock: function()
	{
		this.busy = true;
	},
	
	unlock: function()
	{
		this.busy = false;
	},
	
	isLocked: function()
	{
		return this.busy;
	},
	
	handleWheel: function(delta)
	{
		this.newPosition = this.element.offsetTop + delta*5;
		if (this.newPosition < this.visibleHeight - this.realHeight)
			this.newPosition = this.visibleHeight - this.realHeight;
		if (this.newPosition > 0)
			this.newPosition = 0
		this.element.style.top = this.newPosition.toString() + "px";
	},
	
	scrollWheel: function(event)
	{
		var delta = 0;
		if (!event) event = window.event;
		if (event.wheelDelta)
		{
			delta = event.wheelDelta/120; 
			if (window.opera)
				delta = -delta;
		}
		else if (event.detail)
			delta = -event.detail/3;
		if (delta)
			this.handleWheel(delta);
		if (event.preventDefault)
			event.preventDefault();
		event.returnValue = false;
	}
};

