/*
	ProtoTicker- an RSS News Ticker that makes use of the Prototype javascript library (1.6.0 or newer):
		Jude Venn 2005, based on the BBC News ticker
	Initially based on Jude Venn's Work and modified to remove Mochikit Dependency, later rewritten from
	scratch and made more prototype-like by Greg Jones @ Senokian, 2007 - http://codemeetsmusic.com
	
	Usage:
	var myTicker = new ProtoTicker($('container'),'/url/to/rss',options);
	available options:
	 frequency: the delay between start() and the first item being displayed, defaults to 500ms (1/2 a second)
	 item_frequency: the delay between the last character of one item and the first character of the next
	 char_frequency: the delay between characters appearing
	 endBits: an array of characters used to help the ticking effect
*/
/*
//This is one way of using it:

Event.observe(window,'load',function() {
  var myTicker = new ProtoTicker('ticker','/ticker.rss');
  myTicker.start();
});
/**/
var ProtoTicker = Class.create({
  initialize: function(container,url,options) {
    this.url = url;
    this.container = $(container);
    this.options = Object.extend(options || {},{
      frequency: 1000,
      item_frequency: 4000,
      char_frequency: 50,
      endBits: ['_','-']
    });
    this.items = [];
    this.current = 0;
    this.currentChar = 0;
  },
  start: function() {
     var options = {
       method:'get',
       onComplete: this.receiveRSS.bind(this)
     };
     new Ajax.Request(this.url,options);
  },
  receiveRSS: function(xhr) {
    this.items = xhr.responseXML.documentElement.getElementsByTagName('item');
    if(this.items.length==0) {
      this.items = xhr.responseXML.documentElement.getElementsByTagName('entry');
    }
    setTimeout(this.onTick.bind(this), this.options.frequency);
  },
  onTick: function() {
    if(this.currentChar==0) {
      this.current_item = this.items[this.current%this.items.length];
      this.current_title = this.current_item.getElementsByTagName('title')[0].firstChild.nodeValue.unescapeHTML();
      var link_el = this.current_item.getElementsByTagName('link')[0];
      this.current_link = link_el.firstChild ? link_el.firstChild.nodeValue : link_el.getAttribute('href');
      this.link_element = new Element('a',{href:this.current_link});
      this.container.update(this.link_element);
	  this.link_element.setAttribute("target","_blank");
      this.current++;
    }
    
   this.link_element.update(this.current_title.substring(0,this.currentChar)+this.options.endBits[this.currentChar&this.options.endBits.length-1]);
    if(this.currentChar==this.current_title.length) {
      this.currentChar=0;
      var t = this.options.item_frequency || 1000;
    }
    else {
      this.currentChar++;
      var t = this.options.char_frequency || 50;
    }
    setTimeout(this.onTick.bind(this),t);
  }
});
