//usage: document.observe('dom:loaded', function() { new diiFader('sponsors_foo_id', { effect_duration: 0.5, loop_duration: 4000 }); });

var diiFader = Class.create({
  initialize: function(container, options) {
    this.container = $(container);
    this.effect_duration = options['effect_duration'] || 0.5;
    this.loop_duration = options['loop_duration'] || 4000;

    this.getimages();
    var images = this.container.select('img');
    if (images.length == 1) {
		images[0].up('div').show();
	} else {
	    images.each(function(i) {
	      var img = new Image();
	      img.src = i.src;
	    });
	    this.image_index = images.length - 1;
	    this.loop();
    }
  },
  loop: function(){
    var divs = this.container.select('div.imageContainerDIV');
    if (divs.length == 0) {
      divs = this.container.select('div.imageContainerDIVSPN');
    };
    if (divs.length == 0) {
      divs = this.container.select('div');
    };
    if (divs.length > 0) {
      var e = this.image_index;
      var f = e + 1;
      if (f >= divs.length) f=0;

      new Effect.Parallel([
        new Effect.Fade(divs[e], { sync: true }),
        new Effect.Appear(divs[f], { sync: true })
      ], { duration: this.effect_duration });
      this.image_index = f;
      setTimeout(this.loop.bind(this), this.loop_duration);
    };
  },
  getimages: function() {
	var collection_name = (this.container.attributes['subdept'] != null) ? this.container.attributes['subdept'].value : this.container.id;
	new Ajax.Request("/_collections/" + collection_name + "/manifest.xml?r=" + Math.round(Math.random()*10000), {
      method: 'get',
      asynchronous: false,
      onCreate: function() { },
      onSuccess: function(r) {
	    this.container.innerHTML = '';
	    var files = $A(r.responseXML.getElementsByTagName('file'));
	    files.each(function(f) {
	      var filename = (f.hasChildNodes() ? f.firstChild.nodeValue : '');
	      if (filename != '') {
	        var hreftag = '', hrefend = '';
	        if (f.attributes.getNamedItem('href') != null) {
	          var target = f.attributes.getNamedItem('target').value;
	          hreftag = '<a href="' + f.attributes.getNamedItem('href').value + '" target="' + target + '">';
	          hrefend = '</a>';
	        }
	        var heightattr = ((f.attributes.getNamedItem('height') != null) ? 'height="' + f.attributes.getNamedItem('height').value + '" ' : ' ');
	        var widthattr = ((f.attributes.getNamedItem('width') != null) ? 'width="' + f.attributes.getNamedItem('width').value + '" ' : ' ');
	        this.container.insert('<div class="imageContainerDIV" style="display:none">' + hreftag + '<img src="' + filename + '" ' + 
	                              heightattr + widthattr + 'border="0"/>' + hrefend + '</div>');
	      };
	    }.bind(this));
      }.bind(this),
      onFailure: function(){  }
    });
  }
});


