/*==================================================*
 
 Copyright 2006 Michael Mowery
 
 Thanks to Patrick Fitzgerald for writing part of the Slideshow and Slide objects.
 
 *==================================================*/

// There are five objects defined in this file:
// "Slide" - contains all the information for a single slide
// "Slideshow" - consists of multiple slide objects and runs the slideshow
// "Projector" - loads a slide to be displayed on the screen.
// "Carousel" - Holds the slides for the projector.
// "Screen" - Displays the slide in the projector.

//==================================================
// Projector Object
//==================================================
function Projector( screen, transitionFilter ) {
    // The Screen the projector will project the slide
    this.screen = screen;
    this.transitionFilter = transitionFilter;
    /*
        This projects a slide onto the screen,
        
        @parma slide The slide that will be projected on the screen.
      */
    this.loadSlide = function( slide ) {
        try {
            if ( screen ) {
                if ( this.transitionFilter ) {
                    this.screen.setSlide( slide );
                    this.transitionFilter.apply( screen );
                } 
                else {
                    this.screen.show( slide );
                }
            }
        }
        catch( err ) {
            alert( "[Projector.loadSlide] " + err );
        }
    }
}

function Screen( ) {
    this.slide=null;
    this.show = function( slide ){
        try {
            if ( slide ) this.slide = slide;
            var surface = document.getElementById( this.getSurface( ) );
            surface.src = this.slide.src;
            if ( this.slide.width && this.slide.height ) {
                surface.width = this.slide.width;
                surface.height = this.slide.height;
            }
            var marquee = document.getElementById( this.getMarquee( ) );
            marquee.innerHTML = this.getSlide( ).text;
        }
        catch( err ) {
            alert( "[Screen.show] " + err );
        }
    }
    this.getFrame = function( ) {
        return "screen";
    }
    this.getSurface = function( ) {
        return "surface";
    }
    this.getMarquee = function( ) {
        return "marquee"
    }
    this.getSlide = function( ) {
        return this.slide;
    }
    this.setSlide = function( slide ) {
        this.slide = slide;
    }
}

var FadingTransitionFilter= {
	lockedTimerID:0,
    apply:function( screen ) {
    	if ( ! this.isLocked( ) ) {
    		this.setLock( 2000 );
    		FadeEffect.opacity( screen.getSurface( ), FadeEffect.currentOpacity( ) + 1, 0, 1000, screen, FadingTransitionFilter );
    	}
    	else {
    		this.resetLock( 2000 );
    		FadeEffect.reset( );
    		screen.show( );
        	FadeEffect.setOpacity( 100, screen.getSurface( ) );
    	}
    },
    complete:function( screen ) {
    	if ( screen ) {
    		screen.show( );
        	FadeEffect.opacity( screen.getSurface( ), FadeEffect.currentOpacity( ) - 1, 100, 1000, null, FadingTransitionFilter );
        }
    },
    isLocked:function( ) {
    	return this.lockedTimerID != 0;
    },
    resetLock:function( millisec ) {
    	clearTimeout( this.lockedTimerID );
    	this.setLock( millisec );
    },
    setLock:function( millisec ) {
    	this.lockedTimerID = setTimeout( "FadingTransitionFilter.releaseLock( )", millisec );
    },
    releaseLock:function( ) {
    	this.lockedTimerID = 0;
    }
}

var FadeEffect = {
        opacityStart:0,
        opacityEnd:0,
        opacityCurrent:100,
        callback:null,
        screen:null,
        id:null,
        timeouts:new Array( ),
        currentOpacity:function( ) {
        	return this.opacityCurrent;
        },
        opacity:function(id, opacStart, opacEnd, millisec, screen, callback) { 
        	// Clear the timeouts
        	this.reset( );
        	//this.reseting = false;
            //speed for each frame 
            var speed = Math.round(millisec / 100); 
            var timer = 0; 
            this.opacityStart = opacStart;
            this.opacityEnd = opacEnd;
            this.callback = callback;
            this.screen = screen;
            this.id = id;
            //determine the direction for the blending, if start and end are the same nothing happens 
            if(opacStart > opacEnd) { 
                for(i = opacStart; i >= opacEnd; i--) { 
                    var timeoutID = setTimeout("FadeEffect.setOpacity(" + i + ",'" + this.id + "')",(timer * speed)); 
                    this.addTimeout( timeoutID );
                   	timer++; 
                }    
            } else if(opacStart < opacEnd) { 
                for(i = opacStart; i <= opacEnd; i++) { 
                    var timeoutID = setTimeout("FadeEffect.setOpacity(" + i + ",'" + this.id + "')",(timer * speed)); 
                    this.addTimeout( timeoutID );
                    timer++; 
                } 
            }   
        }, 
        addTimeout:function( timeoutID ) {
        	    this.timeouts.push( timeoutID );
        },
        clearTimeouts:function( ) {
        	for ( i = 0; i < this.timeouts.length; i++ ) {
        		clearTimeout( this.timeouts[ i ] );
        	}
        	this.timeouts = new Array( );
        },
        setOpacity:function( opacity, id ) {
        	try {
                var object = document.getElementById(id);
                this.opacityCurrent = opacity;
                opacity = ( opacity / 100 );
                object.style.opacity = opacity;
                object.style.MozOpacity = opacity;
                object.style.KhtmlOpacity = opacity;
                object.style.filter = " alpha(opacity=" + this.opacityCurrent + ")";
                object.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacityCurrent + ")";
                if ( this.callback && this.opacityCurrent == this.opacityEnd) {
                    this.callback.complete( this.screen )
                }
            }
            catch( err ) { }
        },
        reset:function( ) {
        	this.clearTimeouts( );
        	this.id = null;
        	this.screen = null;
        	this.callback = null;
        }
    }

function Carousel( ) {
    this.slides = new Array();
    this.addSlide = function( slide ) {
        this.slides.push( slide );
    }
    this.getSlide = function( index ) {
        if( index > this.slides.length || index < 0 ) {return;}
        return this.slides[ index ];
    }
    this.removeSlide = function( index ) {
        if( index > this.slides.length || index < 0 ) {return;}
        slides.splice( index, 1 );
    }
    this.replaceSlide = function( index, slide ) {
        if( index > this.slides.length || index < 0 ) {return;}
        slides.splice( index, 1, slide );
    }
    this.getSlides = function( ) {
        return slides;
    }
    this.setSlides = function( slides ) {
        this.slides = slides;
    }
    this.length = function( ) {
        return this.slides.length;
    }
}


//==================================================
// slide object
//==================================================
function Slide( src, link, text, timeout, width, height ) {

  // Image URL- required
  this.src = src;

  // Link URL - optional
  this.link = link;

  // Text to display - optional
  this.text = text;
  
  // width of the image - optional
  this.width = width;
  
  // height of the image - optional
  this.height = height;

  // Custom duration for the slide, in milliseconds.
  // This is an optional parameter.
  this.timeout = timeout;

  // Create an image object for the slide
  if ( document.images ) {
    this.image = new Image();
    if ( width && height ) {
        this.image.width = width;
        this.image.height = height;
    }
  }

  // Flag to tell when load() has already been called
  this.loaded = false;

  //--------------------------------------------------
  this.load = function() {
       if (!document.images) { return; }
       if (!this.loaded) {
            this.image.src = this.src;
            this.loaded = true;
       }
  }

  //--------------------------------------------------
  this.hotlink = function() {
    location.href = this.link;
  }
}

//==================================================
// slideshow object
//==================================================
function Slideshow( projector, carousel ) {

  // The reference to the slide show object. This is needed if you want to play the show.
  this.slideshowObj;
  
  // The projector that shows the slides onto a screen
  this.projector = projector;
  
  // The carousel where all the slides are stored.
  this.carousel = carousel;
  
  // Is the slide set up and ready to play
  this.isSetup = false;

  // Continuously plays the show
  this.repeat = true;
  
  // This is the slide that is shown while the slide is waiting to play.
  this.curtain = null;

  // Number of images to pre-fetch.
  // -1 = preload all images.
  //  1 = load each image is it is used.
  //  n = pre-fetch n images ahead of the current image.
  // I recommend preloading all images unless you have large
  // images, or a large amount of images.
  this.prefetch = -1;

  // Milliseconds to pause between slides.
  // Individual slides can override this.
  this.timeout = 3000;

  // These are private variables
  this.current = 0;
  this.timeoutid = 0;

  //--------------------------------------------------
  // Public methods
  //--------------------------------------------------
  this.setup = function( ) {
    if ( ! this.isSetup ) {
        this.isSetup = true;
        this.update( );
    }
  }
  
  this.setTimeout = function( timeout ) {
  	this.timeout = timeout;
  }
  
  this.setCurtain = function( slide ) {
    this.curtain = slide;
  }
  
  this.setPrefetch = function( prefetch ) {
    this.prefetch = prefetch;
  }
  
  this.showCutain = function( ) {
    if ( this.projector )
        this.projector.loadSlide( curtain );
  }
  
  this.addSlide = function( slide ) {
    if ( ! this.carousel ) { return; }
    
    this.carousel.addSlide( slide );
  
    // Prefetch the slide image if necessary
    if (this.prefetch == -1) {
        slide.load();
    }
    
  }

  //--------------------------------------------------
  this.play = function( slideshowObj, timeout ) {
    // This method implements the automatically running slideshow.
    // If you specify the "timeout" argument, then a new default
    // timeout will be set for the slideshow.
    if ( ! this.carousel ) { return; }
    
    if ( slideshowObj ) {
        this.slideshowObj = slideshowObj;
    }
    
    this.setup( );
    // Make sure we're not already playing
    this.pause();
  
    // If the timeout argument was specified (optional)
    // then make it the new default
    if ( timeout ) {
      this.timeout = timeout;
    }
  
    // If the current slide has a custom timeout, use it;
    // otherwise use the default timeout
    if ( this.carousel.getSlide( this.current ).timeout ) {
      timeout = this.carousel.getSlide( this.current ).timeout;
    } else {
      timeout = this.timeout;
    }
    // After the timeout, call this.loop()
    try {
        this.timeoutid = setTimeout( this.slideshowObj + ".loop()", timeout);
    }
    catch( err ) {
        alert( "[Slideshow.play] " + err );
    }
  }

  //--------------------------------------------------
  this.pause = function() {
    // This method stops the slideshow if it is automatically running.
    if (this.timeoutid != 0) {
      clearTimeout( this.timeoutid );
      this.timeoutid = 0;
    }
  }

  //--------------------------------------------------
  this.update = function() {
    // This method updates the slideshow image on the page
    
     if ( ! this.carousel || ! projector ) { return; }
     
     // Get the next slide
     var slide = this.carousel.getSlide( this.current )
     
     // Load the slide image if necessary
     slide.load();
     
     projector.loadSlide( slide, this.timeoutid == 0 );

    // Do we need to pre-fetch images?
    if (this.prefetch > 0) {

      var next, prev, count;

      // Pre-fetch the next slide image(s)
      next = this.current;
      prev = this.current;
      count = 0;
      do {

        // Get the next and previous slide number
        // Loop past the ends of the slideshow if necessary
        if (++next >= this.carousel.length() ) next = 0;
        if (--prev < 0) prev = this.carousel.length() - 1;

        // Preload the slide image
        this.carousel.getSlide( next ).load( );
        this.carousel.getSlide( prev ).load( );

        // Keep going until we have fetched
        // the designated number of slides

      } while (++count < this.prefetch);
    }
  }

  //--------------------------------------------------
  this.goToSlide = function(n) {
  
    if (n == -1) {
      n = this.slides.length - 1;
    }
  
    if (n < this.slides.length && n >= 0) {
      this.current = n;
    }
  
    this.update();
  }


  //--------------------------------------------------
  this.goToRandomSlide = function(include_current) {
    // Picks a random slide (other than the current slide) and
    // displays it.
    // If the include_current parameter is true,
    // then 
    // See also: shuffle()

    var i;

    // Make sure there is more than one slide
    if (this.slides.length > 1) {

      // Generate a random slide number,
      // but make sure it is not the current slide
      do {
        i = Math.floor(Math.random()*this.slides.length);
      } while (i == this.current);
 
      // Display the slide
      this.goto_slide(i);
    }
  }


  //--------------------------------------------------
  this._next = function() {
    // This method advances to the next slide.
    if ( ! this.carousel ) { return; }
    // Increment the image number
    if (this.current < this.carousel.length( ) - 1) {
      this.current++;
    } else if (this.repeat) {
      this.current = 0;
    }
    this.update();
  }
  
    //--------------------------------------------------
  this.next = function() {
  	var isPlaying = this.timeoutid != 0;
  	// Pause if playing
  	if ( isPlaying ) this.pause( );
 	this._next( );
 	// Restart  is nessary
  	if ( isPlaying ) this.play( );
  }


  //--------------------------------------------------
  this._previous = function() {
    // This method goes to the previous slide.
     if ( ! this.carousel ) { return; }
    // Decrement the image number
    if (this.current > 0) {
      this.current--;
    } else if (this.repeat) {
      this.current = this.carousel.length( ) - 1;
    }
  
    this.update();
  }
  
  //--------------------------------------------------
  this.previous = function() {
    var isPlaying = this.timeoutid != 0;
  	if ( isPlaying ) this.pause( );
  	this._previous( );
	if ( isPlaying ) this.play( );
  }


  //--------------------------------------------------
  this.shuffle = function() {
    // This method randomly shuffles the order of the slides.
    if ( ! this.carousel ) { return; }
    
    var i, i2, slides_copy, slides_randomized;

    // Create a copy of the array containing the slides
    // in sequential order
    slides_copy = this.carousel.getSlides( );
    
    // Create a new array to contain the slides in random order
    slides_randomized = new Array();

    // To populate the new array of slides in random order,
    // loop through the existing slides, picking a random
    // slide, removing it from the ordered list and adding it to
    // the random list.

    do {

      // Pick a random slide from those that remain
      i = Math.floor(Math.random()*slides_copy.length);

      // Add the slide to the end of the randomized array
      slides_randomized[ slides_randomized.length ] =
        slides_copy[i];

      // Remove the slide from the sequential array,
      // so it cannot be chosen again
      for (i2 = i + 1; i2 < slides_copy.length; i2++) {
        slides_copy[i2 - 1] = slides_copy[i2];
      }
      slides_copy.length--;

      // Keep going until we have removed all the slides

    } while (slides_copy.length);

    // Now set the slides to the randomized array
    this.carousel.setSlides( slides_randomized );
  }


  //--------------------------------------------------
  this.hotlink = function() {
    // This method calls the hotlink() method for the current slide.
    if ( ! this.carousel ) { return; }
    this.carousel.getSlide( this.current ).hotlink();
  }

  //==================================================
  // Private methods
  //==================================================

  //--------------------------------------------------
  this.loop = function() {
    // This method is for internal use only.
    // This method gets called automatically by a JavaScript timeout.
    // It advances to the next slide, then sets the next timeout.
    // If the next slide image has not completed loading yet,
    // then do not advance to the next slide yet.
    if ( ! this.carousel ) { return; }
    // Make sure the next slide image has finished loading
    if (this.current < this.carousel.length( ) - 1) {
      next_slide = this.carousel.getSlide( this.current + 1 );
      if (next_slide.image.complete == null || next_slide.image.complete) {
        this._next();
      }
    } else { // we're at the last slide
      this._next();
    }
    
    // Keep playing the slideshow
    this.play( );
  }
 
}
