// Newsticker class
// Original copyright 2006 Wolfgang Bartelme, Bartelme Design - http://bartelme.at
//
// Ported and edited for mootools by Huug Helmink, Ace Group bv - http://www.acegroup.nl
// version 0.12
// date 2007-05-08
//
// Usage:
// var myTicker = new Ticker('idOfDivElement');
//     or (with options)
// var myTicker = new Ticker('idOfDivElement',{interval:####});
// with #### as an integer > 2000
 
var Ticker = new Class({
  initialize: function(containerId,options) {
  	// Set container div
  	this.container = $(containerId);
    // Set options
    this.options = {
      interval: 6500
	  };
    Object.extend(this.options, options || {});
    this.interval = this.options.interval;
 
    this.messages = $A($ES('li',this.container));
    this.number_of_messages = this.messages.length;
    if (this.number_of_messages == 0) {
      this.showError();
      return false;
    }
    this.current_message = 0;
    this.previous_message = null;
 
    // Create toggle button
    // this.toggle_button = new Element('a').setProperties({
    //  'href': '#',
    //  'id': 'togglenewsticker'
    // }).setHTML('Toggle').addEvent('click',this.toggle);
 
    // this.container.adopt(this.toggle_button);
 
    // Display first message
    this.hideMessages();
    this.showMessage();
    // Install timer
    this.timer = this.showMessage.periodical(this.interval,this);
  },
 
  showMessage: function(Appear) {
    Appear = new Fx.Style(this.messages[this.current_message],'opacity',{onStart:function(item) {
      item.setStyle('display','block');
    }}).start(0,1);
    this.fadeMessage.delay(this.interval-2000,this);
    if (this.current_message < this.number_of_messages-1) {
      this.previous_message = this.current_message;
      this.current_message  = this.current_message + 1;
    } else {
      this.current_message  = 0;
      this.previous_message = this.number_of_messages - 1;
    }
  },
 
  fadeMessage: function(myFade) {
    myFade = new Fx.Style(this.messages[this.previous_message],'opacity',{onComplete:function(item) {
    item.setStyle('display','none');
    }}).start(1,0);
  },
 
  hideMessages: function() { 
    this.messages.each(function(message) { 
	  message.setStyle('display','none');
	  message.setStyle('opacity',0);
    })
  },
 
  toggle: function(myBlinder) { 
    myBlinder = new Fx.Slide(this.container,{duration:2000}).toggle();
  },
 
  // Display error message when there is no list, or the list is empty
  showError: function() {
    if ($ES('ul',this.container).length == 0) {
      this.list = new Element('ul');
      this.container.adopt(this.list);
    } else {
      this.list = $ES('ul',this.container)[0];
    }
    this.errorMessage = new Element('li');
    this.errorMessage.addClass('error');
    this.errorMessage.setHTML('Could not retrieve data');
    this.list.adopt(this.errorMessage);
  }
});
