/*
 * slideshow.js
 *
 * depends on mootools 1.2 core
 * and Asset.image from mootools 1.2 more
 *
 * It looks for this structure
 *
 * <div class = "slideshow">
 *   <img class = "display placeholder" />
 *   <ul>
 *     <li>
 *       <a> ... </a>
 *     </li>
 *     ...
 *   </ul>
 * </div>
 *
 *
 */
/**/
//uncomment for debugging
var slideshows;
var S;
/**/
window.addEvent
('domready',
 function ()
 {
   Slide = function(src, parent)
   {
     return {
       image: null,
       effect: null,
       src: src,
       parent: parent,
       load: function()
       {
	 if (this.image == null)
	 {
	   this.image = new Asset.image(this.src);
	   this.effect = new Fx.Tween (this.image, { property: 'opacity',
						     duration: '400',
						     fps: 100 });
	   this.effect.set(0);
	   this.image.setAttribute('class', 'display');
	   this.image.inject(this.parent);
	 }
	 return this;
       }
     };
   };

   slideshows = $$('div.slideshow')
     .map(
       function (item)
       {
	 var slideshow = {
	   setSlide: function(slide)
	   {
	     slide = typeof slide == 'number'? this.slides[slide] : slide;
	     if (this.currentSlide !== null)
	     { slideshow.currentSlide.image.removeClass ('top');
	       slideshow.currentSlide.effect.set(0);}
	     slide.load();
	     slideshow.currentSlide = slide;
	     slide.effect.set(1);
	     slideshow.currentSlide.image.addClass ('top');
	   },

	   show: function (slide)
	   {
	     // if the argument is a number treat it as an index
	     // otherwise hopefully it's a slide that is a child of this slideshow
	     slide = typeof slide == 'number'? this.slides[slide] : slide;
	     if (slide == this.currentSlide)
	     { return; }

	     // load the image and set the opacity to 100%
	     slide.load();
	     slide.effect.set (1);

	     // fade out the current slide
	     var slideshow = this;
	     slideshow.currentSlide.effect.start (1,0)
	       .chain(function(){
			slideshow.setSlide(slide);
		      });
	   },
	   element: item,
	   slides: item.getElements('ul li')
	   .map( function (li)
		 { return Slide(li.getElement('a').getAttribute('href'), item); } ),
	   currentSlide: null
	 };

	 // Show the first slide
	 slideshow.setSlide(slideshow.slides[0]);
	 // Get rid of the place-holder image
 	 slideshow.element.getElement('img.placeholder').dispose();
	 return slideshow;
       });
   S = slideshows[0];
   S.index = 0;
   S.nextSlide = function()
   {
     S.index = S.index < S.slides.length - 1 ? S.index + 1 : 0;
     S.show(S.index);
   };
   S.nextSlide.periodical(6000);
 });