/*
* jQuery Sidescroller
* Timothy Oliver
*
* A small jQuery plugin that 
* sets up a DIV to scroll a list
* of objects across it.
*
* <div id="scroller">
* 	<ul>
*		<li>Object 1</li>
*		<li>Object 2</li>
*	</ul>
* </div>
*
* $('#scroller').scroller();
*/

(function($) {
	var settings = {
		speed: 120000,		//the time (in milliseconds) to scroll through 1 cycle (higher is slower)
		stoponhover: false 	//pause the animation if the mouse hovers over an element
	};
	
	function reset_animation_loop(resume)
	{
		var inner = $(this);
		var width = inner.data( 'width' );
		var speed = settings.speed;
		
		if( !resume )
			inner.css( 'left', '0' );
		else //calc the new speed based on the point we paused (else it resets the timer, but not the pos)
			speed = speed * ( 1.0 - ( -(inner.position().left)/(width*0.5) ) );

		inner.animate( { 'left': '-'+(width*0.5)+'px' }, speed, 'linear', reset_animation_loop );
	}
	
	var methods = {
		init: function( options )
		{
			if ( options ) { 
        		$.extend( settings, options );
     		}
			
			$(this).each( function() {
				var outer = $(this);		//the main container div for the scroller
				var inner = $('<div>');		//container div that will be set to animate
				
				//set relevant CSS for outer		
				outer.css( 'position', 'relative' );
				outer.css( 'overflow', 'hidden' );

				//insert the inner class between outer block and its children
				var kids = outer.children();
				inner.append( kids );
				inner.append( kids.clone() );
				
				outer.append( inner );		

				//set the animation
				inner.addClass( 'scroller_inner' );
				inner.css( 'position', 'absolute' );
				inner.css( 'top', '0' );
				
				//set action callbacks
				if( settings.stoponhover )
				{
					inner.mouseover( function() {
						inner.stop(); //settings.mouseover.apply( this, arguments );
					} );
					
					inner.mouseout( function() {
						reset_animation_loop.apply( inner, [ true ] );	//settings.mouseout.apply( this, arguments );
					} );
				}
				
				//init animation parameters
				var width = inner.width();
				inner.data( 'width', width );
				inner.css( 'left', '0' );
		
				inner.animate( { 'left': '-'+(width/2)+'px' }, settings.speed, 'linear', reset_animation_loop );
			} );
		}
	}
		  
	$.fn.scroller = function( method )
	{
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			console.log( 'Method ' +  method + ' does not exist on jQuery.scroller' );
		} 
	};
	
})(jQuery);
