( function( $ ) {	
	$.fn.imageScroller = function ( options ) {
		return this.each( function() {
			var $this = $( this );
			var loadImgs = 0;
			
			var opt = $.extend( 
				{ 
					  speed: "2000"
					, loading: "Loading images..." 
					, direction: "left"
				}
				, options || {}
			);
			
			$this.children().hide();
			$this.append(
				"<div style='clear:both; padding: 0px; margin: 0px;'>" + 
				"<div id='loading'>" + opt.loading + "</div>" + 
				"</div>"
			);
			
			loadImgs = $( "img" , $this ).length;

			$this.bind(
				  "stopScroll"
				, function () {
					$( "div:eq(0)" , $this ).stop();
				}
			).bind(
				  "startScroll"
				, function (e) {
					scrollStart( $( "div:eq(0)" , $this ) , opt );
				}
			);
			
			var intVal = window.setInterval(
				function () {
					if ( loadImgs == $( "img" , $this ).length ) {
						window.clearInterval( intVal );
						$( "#loading" ).remove();
						$this.children().show();
						var totImg = 0;
			
						$.each(
							  $this.children( ":not(div)" )
							, function () {
								switch ( opt.direction ) {
									case 'left':
										if ( $( this ).children().length ) {
											$( this ).width( $( this ).children( ":eq(0)" ).width() );
										}
										totImg += $( this ).width();
										break;
								}
								
								$( this ).css({
									  margin:  "0px"
									, padding: "0px"
									, clear:   "both"
								});
								
								$( "div:eq(0)" , $this ).append( $( this ) );
							}
						);
						
						switch ( opt.direction ) {
							case 'left':
								$( "div:eq(0)" , $this ).css( "width" , totImg + "px" );
								break;
						}
	
						scrollStart( $( "div:eq(0)" , $this ) , opt );
					}
				}
				, 100
			);
			
			function scrollStart ( $scroll , opt ) {
				switch ( opt.direction ) {
					case 'left':
						var pos = -( $scroll.children( ":eq(0)" ).width() );
						var spd = opt.speed - ( Math.abs ( parseInt( $scroll.css( "marginLeft" ) ) ) * ( opt.speed / parseInt( $scroll.children( ":eq(0)" ).width() ) ) );
						break;
				}
				
				$scroll.animate(
					{
						  marginLeft: ( pos || "0" ) + "px"
					}
					, spd
					, "linear"
					, function () {
						switch ( opt.direction ) {
							case 'left':
								$scroll.append( $( this ).children( ":eq(0)" ) );
								if ( $.browser.msie )
									$scroll.css( "marginLeft" , "40px" );
								else
									$scroll.css( "marginLeft" , "0px" );
								break;
						}
						
						scrollStart( $scroll , opt );
					}
				);
			};
		});
	};
})(jQuery);