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

	var Slideshow = Class.create({
    initialize: function(elmtName) {
      this.delay = 3;  // only used for automatic slideshow, see the end of init() function
      this.fade_speed = 0.5;
       
      this.totalElmt = $$('#' + elmtName + ' .images li').size();
      this.paused = 0;
      this.arrSlideElmt = [this.totalElmt];
      this.curElmtNum = 1;

      // setup counter
      this.setupNav(elmtName);
      
      //preload all elements into array and preload all images within element
      for (i = 1; i <= this.totalElmt; i++) {
      	this.arrSlideElmt[i] = $(elmtName + i);
        // this.arrSlideElmt[i].observe('mouseover', function() { this.paused = 1; }.bind(this));  //pause on mouseover
        // this.arrSlideElmt[i].observe('mouseout', function() { this.paused = 0; }.bind(this));  //resume on mouseout
      	$$(this.arrSlideElmt[i].img).each(function(img) {	
      		img = new Image();
      	});
      }
      $$('#' + elmtName + ' a.next').each(function(node) {
      	node.observe('click', function(s){
      		this.next(elmtName);
      	}.bind(this));
      }.bind(this));
      this.init(elmtName);			
    },
    
    setupNav: function(elmtName){
      totalImages = this.totalElmt
      if (totalImages > 1)
    	  $$('#' + elmtName + ' .counter .total').each(function(e){e.update(totalImages)});
    	else
    	  $$('#' + elmtName + ' .slideshow_nav').each(function(e){e.hide()})
    },
 
    init: function(elmtName) {
      this.arrSlideElmt[1].setStyle({
    	  display: 'block'
    	});   
      // this.start(elmtName)  // uncomment this for autoslide show   
    },

    start: function(elmtName) {
    	//show first element without effect
    	this.arrSlideElmt[this.curElmtNum].setStyle({
    	  display: 'block'
    	});
    	this.executor = new PeriodicalExecuter(function() { 
    		this.next(elmtName); //start slidehow
    	}.bind(this), this.delay);		
    },

    next: function(elmtName){
    	if (!this.paused) {
    		this.update(elmtName);
    	}
    },

    update: function(elmtName) {
    	new Effect.Fade(this.arrSlideElmt[this.curElmtNum], {duration: this.fade_speed, afterFinish:function(){
    		this.checkSlide(elmtName);
    		for (i = 1; i <= this.totalElmt; i++) {
    			this.arrSlideElmt[i].setStyle({
    			  display: 'none'
    			});
    		}
    		new Effect.Appear(this.arrSlideElmt[this.curElmtNum], {duration: this.fade_speed});
    	}.bind(this)});
    },

    checkSlide: function(elmtName) {
    	if (this.curElmtNum == this.totalElmt) { this.curElmtNum = 1; }
    	else { this.curElmtNum ++; }		
    	currentImage = this.curElmtNum;
    	$$('#' + elmtName + ' .counter .current').each(function(e){e.update(currentImage)});
    }
	});
