Effect.DefaultOptions.duration = 0.3;
NewsTicker = Class.create();
Object.extend(NewsTicker.prototype, {
	
	tickerDiv:      "ticker", 
	tickerTitle:    "news-link",
	feedURL:        "rss/items.rss",
	pauseLength:    3500,
	timer:          0,
	titleIndex:     0,
	items: null,
	initialize: function()
	{
		this.items = [];
		
		new Ajax.Request(
			this.feedURL,
			{
				method: "get",
				onSuccess: function(response)
					{
					this.parseXML(response.responseXML);
					this.buildTicker();
					}.bind(this),
				onFailure: function()
					{
					console.log("Please visit http://www.fatlion.com/sailplanes/whatsnew.html for the latest news and information on R/C Sailplanes");
					},
				onException: function(req, err) 
					{
					// throw(err);
					}
			}
		);
	},
	
	buildTicker: function()
	{
		// replace the placeholder content with the first news title
		if (this.items[this.titleIndex])
		{
			$(this.tickerTitle).innerHTML = this.items[this.titleIndex]['title'];
			
			// start the timer if we have valid headlines
			this.start();
		}
	},
	
	parseXML: function(xml)
    {
		// build the array of news titles
		$A(xml.getElementsByTagName("item")).each(function(item) {
			title = item.getElementsByTagName("title")[0].childNodes[0].nodeValue;
			var link = item.getElementsByTagName("link")[0].childNodes[0].nodeValue;
			this.items.push({title: title, link: link});
		}.bind(this));
	},
	
	start: function()
    {
		this.interval = setInterval(this.showNext.bind(this), this.pauseLength);
	},
	
	stop: function()
    {
		clearInterval(this.interval)
	},
	
	showNext: function()
	{
		//determine next headline
		this.titleIndex++;
		
		if (this.titleIndex >= this.items.length)
			{
			this.titleIndex = 0;
			}
		
		new Effect.Fade('news-link',
			{
			afterFinish: function()
				{
				this.switchData();
				new Effect.Appear('news-link'); 
				}.bind(this)
			});
	},
	
    switchData: function()
    {
		$(this.tickerTitle).setAttribute("href", this.items[this.titleIndex]['link']);
		if (this.items[this.titleIndex])
			{
			$(this.tickerTitle).innerHTML = this.items[this.titleIndex]['title'];
			}
	}
});

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