var Scroller = new Class({
	initialize: function(elem){
		this.auto_scroll = true;
		var xoxo = elem.getElementsBySelector('.xoxo')[0];
		xoxo.setStyle('left', '0');
		xoxo._index = 0;
		xoxo._step = xoxo.getChildren()[0].getSize().size.x;
		xoxo.setStyles({'width': (xoxo.getChildren().length * xoxo._step)});
		xoxo._min_index = (elem.getSize().size.x - xoxo.getSize().size.x) / xoxo._step;

		elem.adopt(new Element('a', {'class':"control control_left",'href':"#"}).setText('Left').addEvent('click', function() {
			this.scrollTo(xoxo, xoxo._index + 1, 400);
			return false;
		}.bind(this)));
		
		elem.adopt(new Element('a', {'class':"control control_right", 'href':"#"}).setText('Right').addEvent('click', function() {
			this.scrollTo(xoxo, xoxo._index - 1, 400);
			return false;
		}.bind(this)));

		elem.addEvent('mouseover', function() {
			this.auto_scroll = false;
		}.bind(this));
		
		elem.addEvent('mouseout', function() {
			this.auto_scroll = true;
		}.bind(this));
			
		xoxo.getElements('a').each(function(e) {
			var span = e.getElement('span');
			var slide = new Fx.Slide(span, {duration: 300});
			slide.hide();

			e.setStyle('opacity', 0.9);
			
			e.addEvent('mouseenter', function(){
				this.auto_scroll = false;
				slide.stop();
				slide.slideIn();
			}.bind(this));
			
			e.addEvent('mouseleave', function(){
				this.auto_scroll = true;
				slide.stop();
				slide.slideOut();
			}.bind(this));
		});

		this.autoScroll(xoxo, 1, 2000);
	},

	autoScroll: function(xoxo, direction, speed) {
		if (this.auto_scroll) {
			if (this.scrollTo(xoxo, xoxo._index + direction, speed)) {
				direction *= -1;
			}
		}
		setTimeout((function() {
			this.autoScroll(xoxo, direction, speed);
		}).bind(this), 6000);
	},

	scrollTo: function(xoxo, i, speed) {
		if (i > 0) {
			i = 0;
		} else if (i <= xoxo._min_index) {
			i = xoxo._min_index;
		}
		var scroll = xoxo.effect('left', {duration: speed});
		scroll.start(i * xoxo._step);
		xoxo._index = i;

		return (i == 0) || (i == xoxo._min_index);
	}
});
