(function($) {

	$.fn.flatRoll=function(args)
	{
		if(this.length == 0){
			return this;
		}

		if(typeof args.speed!='number')
			args.speed=500;

		if(typeof args.step!='number')
			args.step=1;

		var list=this.addClass('flatRollerList');
		var container=$('<div/>').addClass('flatRoller');

		container.insertBefore(list).append(list);

		var children=container.find('.flatRollerList > div');
		
		var childrenWidth = 0;
		children.each(function() {
		    childrenWidth += $(this).outerWidth(true);
		});
		//alert(childrenWidth);
		//alert(container.width());
		var wider=container.width()>=childrenWidth;
		if(wider)
		{
			//children=children.add($('<li></li>').appendTo(list))
			childrenWidth=container.width();
			//alert(childrenWidth);
		}
		
		children.addClass('child');

		list.css('width', childrenWidth+'px');
		//container.css('height', children.outerHeight(true)+'px');

		var buttons=args.btnLeft.add(args.btnRight);
		buttons.bind('click', function() {return false;} );

		var changeBtn=function(btn, disabled)
		{
			if(disabled) {
				btn.addClass('disabled').removeAttr('href');
			}
			else {
				btn.removeClass('disabled').attr('href', '#');
			}
		}

		var scrollList=function(positive)
		{
			var stepSize=args.step*(childrenWidth/children.size());
			var newLeft=parseInt(list.css('left'))+(positive? +stepSize: -stepSize);
			var maxLeft=childrenWidth-container.width();

			changeBtn(buttons, false);

			if(newLeft>=0)
			{
				changeBtn(args.btnLeft, true);
				newLeft=0;
			}
			else if(-newLeft>=maxLeft)
			{
				changeBtn(args.btnRight, true);
				newLeft=-maxLeft;
			}

			list.animate({ 'left': newLeft+'px' }, args.speed);
		}

		if(wider)
		{
			changeBtn(buttons, true);
		}
		else
		{
			changeBtn(args.btnLeft, true);
			args.btnLeft.bind('click', function() { scrollList(true); });
			args.btnRight.bind('click', function() { scrollList(false); });
		}

		return this;
	}
}) (jQuery);

