
String.implement({
	substitute: function(object, regexp){
		return this.replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
			if (match.charAt(0) == '\\') return match.slice(1);
			return (object[name] != undefined) ? object[name] : '';
		});
	}
});


var NewsTicker = new Class({
	Implements: [Options, Events],
	options: {
		template: "<span class=\"title\">{title}</span>{body}",
		switchDelay: 5000,
		fadeOptions: {
			duration: 'short'
		},
		scrollSpeed: 0.06,
		scrollOptions: {transition: 'linear'},
		scrollStartDelay: 2000
	},
	initialize: function(element, news, options) {
		this.setOptions(options);
		this.element = $(element);
		this.parentWidth = this.element.getParent().getSize().x;
		this.news = news;
		this.element.set('tween', this.options.fadeOptions);
		this.idx = -1;
		// this.element.fade('hide');
		this.initial = true;
		this.start();
	},
	switchover: function() {
		this.element.setStyle('left', 0);
		if(this.idx==this.news.length-1) this.idx = -1;
		var item = this.news[++this.idx];
		var data = {'title': item[0], 'body': item[1]};
		this.element.set('html', this.options.template.substitute(data));
		this.element.fade('in');
		if(this.initial) this.initial = false;
		var width = this.element.getSize().x;
		var switchNext = this.start.create({ delay: this.options.switchDelay, bind: this});
		if(width < this.parentWidth) switchNext();
		else {
			var length = width - this.parentWidth;
			var time = length/this.options.scrollSpeed;
			this.element.set('morph', $merge(this.options.scrollOptions, {duration: time}));
			this.element.get('morph').chain(switchNext);
			this.element.morph.delay(this.options.scrollStartDelay, this.element, {
				'left': -length
			});
		} 	
	},
	start: function(){
		if(!this.initial) {
			var tween = this.element.get('tween');
			tween.chain(this.switchover.bind(this));
			this.element.fade('out');
		}
		else this.switchover();

	}
});
