
Event.observe(window, "load", function() {
	var ticker = new Marquee('marquee');

});


var Marquee = Class.create();
Marquee.prototype = {
	// Settings:
	direction: 'left',
	speed: 0.015,
	// Working variables:
	parentElement: null,
	parentWidth: 0,
	currentPosition: 0,
	timer: null,
	numItems: 0,


	initialize: function(element, speed, direction) {
		if($(element)) {

			if(speed && speed.match(new RegExp(/[1-9][0-9]{1,}/))) {
				this.speed = speed/100;
			}

			if(direction) {
				switch(direction) {
					case 'left':
					case 'right':
						this.direction = direction;
						break;
					case 'l':
						this.direction = 'left';
						break;
					case 'r':
						this.direction = 'right';
						break;
				}
			}

			this.parentElement = $(element);
			this.parentWidth = this.parentElement.offsetWidth;

			this.items = this.parentElement.getElementsByTagName('li');

			this.numItems = this.items.length;

			Event.observe(this.parentElement, 'mouseover', this.pause.bind(this));
			Event.observe(this.parentElement, 'mouseout', this.resume.bind(this));

			this.start();

		} else { /* fail silently for pages without a marquee */ }
	},

	start: function() {
		if(this.numItems > 0) {
			var totalWidth = 0;
			for(var i=0; i<this.numItems; i++) {
				totalWidth += this.items[i].offsetWidth;
			}
			if(totalWidth > this.parentWidth) {
				this.timer = new PeriodicalExecuter(this.update.bind(this), this.speed);
			}
		}
	},

	stop: function() {
		if(this.timer)
			this.timer.stop();
	},

	pause: function() {
		this.stop();
	},

	resume: function() {
		this.start();
	},

	// roep deze functie aan om de marquee te bewegen
	update: function() {
		// update the position:
		this.currentPosition = (this.currentPosition < this.parentWidth) ? ((this.direction == 'left') ? this.currentPosition-1 : this.currentPosition+1) : 0;
		this.parentElement.style.textIndent = this.currentPosition+'px';
		//
		if(0-this.currentPosition == this.items[0].offsetWidth) {
			// get the content:
			var content = this.items[0].innerHTML;
			// add the new message at the end of our marquee:
			new Insertion.Bottom(this.parentElement, '<li>'+content+'</li>');
			// remove the first message:
			Element.remove(this.items[0]);
			// update our internal array:
			this.items = this.parentElement.getElementsByTagName('li');
			this.parentElement.style.textIndent = 0;
			this.currentPosition = 0;

			// check for valid total width of the remaining items
			/*var totalWidth = 0;
			for(var i=0; i<(this.numItems-1); i++) {
				totalWidth += this.items[i].offsetWidth;
			}

			// remain items are not big enough, copy first item to the back

			if(totalWidth < this.parentWidth) {
				content = this.items[0].innerHTML;
				new Insertion.Bottom(this.parentElement, '<li>'+content+'</li>');
				this.items = this.parentElement.getElementsByTagName('li');
				this.numItems = this.items.length;
			}*/
		}
	}
	
}