var SlidingBar = Class.create({
	initialize: function(container) {
		this.container = container = $(container);
		this.init.bind(this).defer();
	},
	
	init: function() {
		this.width = 0;
		this.container.select('div.list').each(function(container) {
			var width = (container.select('div.related_product').inject(0, function(w, item) {
				return w + 20 + item.getWidth();
			})) + 20;
			this.width += width;
			container.setStyle({
				'width': width + 'px'
			});
		}.bind(this));
		this.width -= this.container.getWidth();
		
		if (this.width <= 0) {
			return;
		}
		
		this.lastLeft = 0;
		Event.observe(this.container, 'scroll', function() {
			var diff = this.container.scrollLeft - this.lastLeft;
			if (diff > 0 && this.speed < 0 || diff < 0 && this.speed > 0) {
				this.speed *= -1;
			}
			this.lastLeft = this.container.scrollLeft;
		}.bind(this));
		Event.observe(this.container, 'mouseover', function() {
			if (this.timeout) {
				window.clearTimeout(this.timeout);
			}
		}.bind(this));
		Event.observe(this.container, 'mouseout', function() {
			if (this.timeout) {
				window.clearTimeout(this.timeout);
			}
			this.timeout = this.trigger.bind(this).delay(3);
		}.bind(this));
		
		this.running = true;
		this.speed = 3;
		this.time = 100;
		this.trigger.bind(this).delay(1.5);
	},
	
	trigger: function() {
		if (this.timeout) window.clearTimeout(this.timeout);
		this.container.scrollLeft += this.speed;
		if (this.container.scrollLeft <= 0) {
			this.speed *= -1;
		} else if (this.container.scrollLeft >= this.width) {
			this.speed *= -1;
		}
		this.timeout = window.setTimeout(function() { this.trigger(); }.bind(this), this.time);
	}
});
