/*
 * Takes an element or element id and an array of clickable elements
 * or element ids and makes the click event of each element scroll
 * to the element passed in as the first parameter.
 * 
 * Example:
 * 	new TP.PageScroller('id_of_element',[$('ele1'), $('el12')]);
 * Array of click elements can also be simply IDs such as
 * 	new TP.PageScroller('id_of_element',['ele1', 'el12']);
 * 
 * Requires Prototype library
 * Author Gareth Hughes
 */

TP.PageScroller = Class.create({
	scrollJump: 40,
	scrollTimer: 10, 
	element: null,
	y: null, 
	maxScroll: null, 
	
	initialize: function(id, clickElements){
		this.element = $(id);

		$A(clickElements).each(function(ele){
			$(ele).observe('click', this.scrollEvent.bindAsEventListener(this));
		}.bind(this));
	},
	
	scrollEvent: function(event, callback){
		// the size has to be recalculated each click as the page might have been resized
		var size = TP.getSize();
		this.maxScroll = (size.pheight - size.height);

		// finds the top of the element
		this.y = TP.findLocation(this.element).y;
		
		this.scroll();
		
		if(event != null)
			event.stop();		
		
		if(typeof callback != 'undefined')
			callback(event);
	},

	scroll: function(){
		if(TP.getScrollPosition() < this.y){
			//scroll down

			// if we're at the bottom of the page we need to stop
			if(TP.getScrollPosition() >= this.maxScroll)
				return;
			
			if ((TP.getScrollPosition()+this.scrollJump) < this.y) {
				window.scrollBy(0, this.scrollJump);
				setTimeout(function(){
					this.scroll();
				}.bind(this), this.scrollTimer);
			} else {
				window.scrollBy(0, this.y-TP.getScrollPosition());
			}							
		} else {
			//scroll up
			if ((TP.getScrollPosition()-this.scrollJump) > this.y) {
				// scroll by the specified amount
				window.scrollBy(0, -this.scrollJump);
				setTimeout(function(){
					this.scroll();
				}.bind(this), this.scrollTimer);
			} else {
				// scroll the rest of the way 
				window.scrollBy(0, this.y-TP.getScrollPosition());
			}							
		}
	}
	
});


