// JavaScript Document
Effect.DefaultOptions.duration = 0.3;

NewsTicker = Class.create();

Object.extend(NewsTicker.prototype, {
	
	tickerTitle: "ticker_text", 
	getURL: "/ticker.xml",
	pauseLength: 3500,
	timer: 0,
	currentTitle: 0,
	items: null,

	initialize: function() {
		
		
		this.items = [];
		
		new Ajax.Request(
			this.getURL, {
				method: "get",
				onSuccess: function(response) {
					this.parseXML(response.responseXML);
					this.initTicker();
				}.bind(this)
			}
		);
	},
	
	initTicker: function() {
		// replace the placeholder content with the first news title
		if (this.items[this.currentTitle]) {
			$(this.tickerTitle).innerHTML = this.items[this.currentTitle]['title'];
			this.start();// start the timer if we have valid headlines
		}
	},
	
	parseXML: function(xml) {
		// build the array of news titles
		$A(xml.getElementsByTagName("item")).each(function(item) {
			title = item.getElementsByTagName("title")[0].childNodes[0].nodeValue;
			this.items.push({title: title});
		}.bind(this));
	},
	
	start: function() {
		this.interval = setInterval(this.showNext.bind(this), this.pauseLength);
	},
	
	stop: function() {
		clearInterval(this.interval)
	},
	
	showNext: function() {
		
		//determine next headline
		if ( this.currentTitle < this.items.length-1 ) {
			this.currentTitle = this.currentTitle+1;
		} else {
			this.currentTitle = 0;
		}
		
		new Effect.Fade(this.tickerTitle, {
			afterFinish: function() {
				this.switchData();
				new Effect.Appear(this.tickerTitle); }.bind(this)});

	},
	
    switchData: function() {
		if (this.items[this.currentTitle]) 
		{
			$(this.tickerTitle).innerHTML = this.items[this.currentTitle]['title'];
		}
	}
});

Event.observe(window, 'load', function() {
	var ticker = new NewsTicker();
});
