
(function($){

	var methods = {

		init: function (options){

			var options = $.extend({
				interval: 50, // milliseconds in step
				speed: 56 // pixels in second
				}, options);

			return this.each(function(){

				if($(this).hasClass('_dsmScrollableInitialized')) return;
				$(this).addClass('_dsmScrollableInitialized');


				var outerWidth = $(this).width();
				var innerWidth = 0;

				$(this).children().each(function(){
					innerWidth += $(this).outerWidth(true);
					$(this).css({
						float: 'left'
						});
				});
				if(outerWidth >= innerWidth) return;


				var innerDiv = $('<div class="dsmScrollableInnerArea"></div>');
				
				$(this).children().appendTo(innerDiv).clone().appendTo(innerDiv);
				innerDiv.append('<div style="clear:both"></div>');
			//	alert(innerWidth);
				$(this).append(innerDiv);
				innerDiv.css({
					width: innerWidth * 2 + 50,
					height: '1px'
					});
				$(this).css({
					overflow: 'hidden'
					});
			//	$(this).after('<div id="debug"></div>');

				$(this).attr('_dsm_scrollable_position', 0);
				$(this).attr('_dsm_scrollable_speed', options.speed);

				var $this = $(this);
				setInterval(function(){
					var interval = options.interval;
					var pos = parseFloat($this.attr('_dsm_scrollable_position'));
					var speed = parseInt($this.attr('_dsm_scrollable_speed'));
					pos += speed / 1000 * interval;
					if(pos < 0) pos += innerWidth;
					else if(pos > innerWidth) pos = pos - innerWidth;
					$this.attr('_dsm_scrollable_position', pos);
					$this.scrollLeft(Math.floor(pos));

			//		$('#debug').html(pos+' : '+innerWidth);

					}, options.interval);
			});
		},

		speed: function(value){
			if(!value) return $(this).attr('_dsm_scrollable_speed');
			$(this).attr('_dsm_scrollable_speed', parseInt(value));
		}
	};

$.fn.dsmScrollable = function(method){

	// Method calling logic
    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 {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    

};

})(jQuery)

