/*
	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-items a');
  myTicker.start();
});
/**/
var ProtoTicker = Class.create({
  initialize: function(container,item_selector,options) {
    this.container = $(container);
    this.options = Object.extend(options || {},{
      item_selector: item_selector,
      frequency: 500,
      item_frequency: 1500,
      char_frequency: 75,
      endBits: ['_','-']
    });
    this.items = [];
    this.current = 0;
    this.currentChar = 0;
    this.link_element = new Element('a',{});
    this.container.update(this.link_element);
  },
  start: function() {
    this.extractFromHTML();
    setTimeout(this.onTick.bind(this), this.options.frequency);
  },
  extractFromHTML: function() {
    var ticker = this;
		$$(this.options.item_selector).each(function(a_link, index) {
			ticker.items[index] = {title: a_link.readAttribute('title'), href: a_link.readAttribute('href')};
			if (a_link.readAttribute('target')) {
			  ticker.items[index]['target'] = a_link.readAttribute('target');
			}
		});
  },
  onTick: function() {
    if(this.currentChar==0) {
      this.current_item = this.items[this.current%this.items.length];
      this.link_element.writeAttribute('title', this.current_item.title);
      this.link_element.writeAttribute('href', this.current_item.href);
      if (this.current_item.target) {
        this.link_element.writeAttribute('target', this.current_item.target);        
      }
      this.current_title = this.current_item.title;
      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);
  }
});