//JavaScript Document
/*
	verticalScroller  for scrolling news in a website for prototype.
	by Erwin San Martin
	
	based on code by somebody on google prototype scriptaculous group..
	
	added some new functionalities like a pause everytime a news title reach the upper side
	and pausing the scroll while mouse over some news.	
*/

var VerticalScroller = Class.create({
        initialize: function(container, containment, options){			
			this.container = $(container);
			this.containment = $(containment);
			this.options = Object.extend(options || {}, {
				speed: 40,
				pause: 3000,   //time for a pause after a new news appear
				minItems: 2    //minimums items to start scrolling (items showing on screen) 
			});
			this.boxHeight = this.container.style.height.replace('px','');
			this.realHeight = this.container.scrollHeight; //get the current height so we know when to wrap 
			this.list = $(this.containment).select('li');
			this.listSize = this.list.length;
			this.timerID = null;
			this.helper = 0;  //helper variable for the scroll
			this.paused = 0;
			
			if(this.listSize > this.options.minItems)
			{
				this.containment.innerHTML = this.containment.innerHTML + this.containment.innerHTML;   //duplicate the content for carrousel effect
				this.itemHeight = (this.realHeight / this.list.length);   
				this.list = $(this.containment).select('li');    //as the content was duplicated we need all items to catch events...
				
				this.list.each( function(node){
					node.observe('mouseover',this.pauseScroll.bindAsEventListener(this));
					node.observe('mouseout', this.playScroll.bindAsEventListener(this));
				}.bind(this));
				
				this.playScroll();
			}
		},
		
		run: function(){
			clearTimeout(this.timerID);
			
			this.container.scrollTop=this.container.scrollTop + 1;  //move up container one pixel after another to the infinite			
			if(this.container.scrollTop <= this.realHeight){
				this.helper = this.container.scrollTop;
				if((this.helper % this.itemHeight) == 0) //when an item gets to the top... 
				{
					clearTimeout(this.timerID);
					this.timerID = setTimeout(this.run.bind(this),this.options.pause);   //stops and continue a few seconds after
				}
				else
				{
					this.playScroll();    //just continue to the infinite
				}
			} 
			else {    //the last original item is out of visible area, and now we are watching the clones.. so
				this.container.scrollTop = 0;   //move the container to show the original items
				this.playScroll();              // and then continue with the animation
			}
		},
		
		pauseScroll: function(event){
			clearTimeout(this.timerID);
		},
		
		playScroll: function(event){
			clearTimeout(this.timerID);
			this.timerID = setTimeout(this.run.bind(this), this.options.speed);
		}
}); 
