var AutoScroller = new Class({
    initialize: function(parent, layout) {
        this.parent = $(parent);
		this.container = this.parent.getElement('div');
		this.containerWidth = this.container.getSize().x;
		
		this.scrollMax = this.container.getScrollSize().y - this.container.getSize().y;
		if (this.scrollMax <= 0) return;
		
		this.int = null;
		this.inc = 0;
		this.scrolled = 0;
		this.container.scrollTop = 0;
		
		// create navigational arrows
		this.ps = [];
		this.ps[0] = new Element('p');
		this.ps[0].setStyles({ cursor: 'n-resize', opacity: 0, 'padding-left': this.containerWidth - 46 });
		this.ps[0].set('html', '<img src=/images/layout/' + layout + '/pe-nav' + (arguments.length == 3 ? arguments[2] : 1) + '-top.gif alt=down>');
		this.ps[1] = new Element('p');
		this.ps[1].setStyles({ cursor: 'n-resize' });
		this.ps[1].set('html', '<img src=/images/layout/' + layout + '/pe-nav' + (arguments.length == 3 ? arguments[2] : 1) + '-bottom.gif alt=up>');
		this.parent.grab(this.ps[0], 'top');
		this.parent.grab(this.ps[1], 'bottom');

		// adjust container height to fit arrows
		var offset = 34;
		this.container.setStyles({ height: this.container.getSize().y - offset, margin: '10px 0px' });
		this.scrollMax += offset;
		
		this.ps[0].addEvent('mouseenter', this.mouseEnter.bind(this));
		this.ps[0].addEvent('mouseleave', this.mouseLeave.bind(this));
		this.ps[1].addEvent('mouseenter', this.mouseEnter.bind(this));
		this.ps[1].addEvent('mouseleave', this.mouseLeave.bind(this));
    },
	
	mouseEnter: function(event) {
		var elem = event.target;
		if (elem.tagName != 'IMG') elem = elem.getElement('img');
		
		if (elem.alt == 'up') {
			this.inc = 1;
			this.ps[0].setStyle('opacity', 1);
		}
		else {
			this.inc = -1;
			this.ps[1].setStyle('opacity', 1);
		}

		this.int = setInterval(this.scrollDiv.bind(this), 10);
	},
	
	mouseLeave: function(event) {
		if (this.int)
			clearInterval(this.int);
	},
	
	scrollDiv: function() {
		this.scrolled += this.inc;
		
		if (this.scrolled < 0) {
			this.scrolled = 0;
			clearInterval(this.int);
			this.ps[0].setStyle('opacity', 0);
			return;
		}
		else if (this.scrolled > this.scrollMax) {
			this.scrolled = this.scrollMax;
			clearInterval(this.int);
			this.ps[1].setStyle('opacity', 0);
			return;
		}
		
		this.ps[0].setStyle('padding-left', Math.round((this.scrollMax - this.scrolled) * (this.containerWidth - 46) / this.scrollMax));
		this.ps[1].setStyle('padding-left', Math.round(this.scrolled * (this.containerWidth - 46) / this.scrollMax));
		this.container.scrollTop = this.scrolled;
	}
	
});