Effect.DefaultOptions.duration = 0.3;
RecentUpdates = Class.create({
	tickerContainer: null,
	promoContainer: null,
	feedURL: '/wwdc/rss/recent.xml',
	pauseLength: 5000,
	timer: 0,
	currentItem: 0,
	items: null,
	initialize: function() {
		this.tickerContainer = $('rss-view') ? $('rss-view') : null;
		this.promoContainer = $('footer-feed') ? $('footer-feed') : null;
		this.items = [];

		new Ajax.Request(
			this.feedURL, {
				method: 'get',
				onSuccess: function(response) {
					this.parseXML(response.responseXML);
					if(this.promoContainer) this.buildPromo();
					if(this.tickerContainer) this.buildTicker();
				}.bind(this)
			}
		)
	},
	
	parseXML: function(xml) {
		var date, title, link;
		$A(xml.getElementsByTagName('item')).each(function(item) {
			date = item.getElementsByTagName('date')[0].childNodes[0].nodeValue;
			title = item.getElementsByTagName('title')[0].childNodes[0].nodeValue;
			link = item.getElementsByTagName('link')[0].childNodes[0].nodeValue;
			this.items.push({date: date, title: title, link: link});
		}.bind(this));
	},
	
	buildPromo: function() {
		var li;
		this.items.each(function(item,i) {
			if(i<5) {
				li = new Element('li').update('<span>'+item.date+'</span><a href="'+item.link+'">'+item.title+'</a>');
				this.promoContainer.appendChild(li);
			}	
		}.bind(this));
	},
	
	buildTicker: function() {
		var span = new Element('span', { 'class':'rss-item' }).update('<strong>'+this.items[this.currentItem].date+'</strong><a href="'+this.items[this.currentItem].link+'">'+this.items[this.currentItem].title+'</a>');
		this.tickerContainer.appendChild(span);
		this.start();
	},
	
	start: function() {
		this.interval = setInterval(this.showNext.bind(this), this.pauseLength);
	},
	
	stop: function() {
		clearInterval(this.interval);
	},
	
	showNext: function() {
		if(this.currentItem < this.items.length-1) {
			this.currentItem = this.currentItem+1;
		} else {
			this.currentItem = 0;
		}
		
		new Effect.Fade(this.tickerContainer, {
			afterFinish: function() {
				this.tickerContainer.update('<span class="rss-item"><strong>'+this.items[this.currentItem].date+'</strong><a href="'+this.items[this.currentItem].link+'">'+this.items[this.currentItem].title+'</a></span>');
				new Effect.Appear(this.tickerContainer);
			}.bind(this)
		});
	}
	
});

Event.onDOMReady(function() {
	new RecentUpdates();
});