// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var twdNewsticker = Class.create({
  initialize: function(element) {
    var defaults = {
      duration: 4,
			slide_css_class: 'slide'
    };
    var options = Object.extend(defaults, arguments[1] || { });
    this.options = options;
    this.element = $(element);
		this.slides = this.element.childElements('.' + this.options.slide_css_class);
		this.slides.each(function(slide) {
			if (this.slides.first() == slide) {
				slide.setStyle({
					top: '0px'
				});
			}
		}.bind(this));
		this.startTicker();
  },
  
  startTicker: function() {
	
		var callCount = 0;
		new PeriodicalExecuter(function(pe) {
				if(++callCount == this.slides.length) {
					pe.stop();
				}
				else {
					this.changeSlide();
				}
			}.bind(this),
				this.options.duration
		);
		
  },

	changeSlide: function() {
		var next = this.slides[1];
		new Effect.Move(this.slides[0], {x: 0, y: -112, mode: 'absolute'});
		new Effect.Move(next, {
			x: 0,
			y: 0,
			mode: 'absolute',
			afterFinish: this.positionSlides.bind(this)
		});
	},
	
	positionSlides: function() {
		var first = this.slides.first();
		this.slides.shift();
		this.slides.push(first);
		this.slides.each(function(slide) {
			if (this.slides.first() != slide) {
				slide.setStyle({
					top: '112px'
				});
			}
		}.bind(this));
	}
	
});
