var Ticker = new Class({
	Binds: ['tickFinish', 'setup'],
	
	element: null,
	wrapper: null,
	msPerPixel: 25,
	content: null,
	
	initialize: function(element, msPerPixel) {
		if(msPerPixel) this.msPerPixel = msPerPixel;
		
		this.element = $(element);
		this.content = this.element.get('html');
		this.element.empty();
		this.wrapper = new Element('div', { 'class': 'wrapper', style: 'position: absolute;' }).inject(this.element);
		
		this.setup();
		
		window.addEvent('resize', this.setup);
	},
	
	setup: function() {
		this.wrapper.empty();
		
		var initialContainer = this.newContainer(0);
		initialContainer.set('tween', { onComplete: this.tickFinish });
		
		var neededContainers = Math.ceil(this.element.getWidth() / initialContainer.getWidth());
		if(neededContainers < 2) neededContainers = 2;
		
		for(var i = 0; i < neededContainers; i++) {
			this.newContainer(i + 1);
		}
		
		this.setPositions();
		this.tick();
	},
	
	newContainer: function(i) {
		return new Element('div', { 'class': 'container '+ i, html: this.content, style: 'position: absolute; left: 0;' })
					 .inject(this.wrapper);
	},
	
	setPositions: function() {
		var elements = this.element.getElements('.container');
		elements.setStyle('left', 0);
		
		var i = 0;
		elements.each(function(c) {
			c.setStyle('left', (i == 0 ? 0 : this.getNextLeft()));
			i++;
		}, this);
		
		this.wrapper.setStyle('width', this.getNextLeft());
	},
	
	tick: function() {
		var elements = this.element.getElements('.container');
		elements.each(function(c) {
			var cWidth = c.getWidth();
			c.set('tween', { duration: this.msPerPixel * cWidth, transition: 'linear' })
			 .tween('left', c.getStyle('left').toInt() - cWidth);
		}, this);
	},
	
	tickFinish: function() {
		this.element.getElement('.container:first-child').inject(this.wrapper).setStyle('left', this.getNextLeft());
		this.setPositions();
		this.tick();
	},
	
	getNextLeft: function() {
		var hl = 0;
		this.element.getElements('.container').each(function(c) {
			var cl = c.getStyle('left').toInt() + c.getWidth();
			if(cl > hl) hl = cl;
		}, this);
		return hl;
	}
});
