/*==================================================*
 $Id: slideshow.js,v 1.16 2003/10/14 12:39:00 pat Exp $
 Copyright 2000-2003 Patrick Fitzgerald
 http://slideshow.barelyfitz.com/

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *==================================================*/

// There are two objects defined in this file:
// "slide" - contains all the information for a single slide
// "slideshow" - consists of multiple slide objects and runs the slideshow

//==================================================
// slide object
//==================================================

var hiresAttribute = "resizable=1,location=0,scrollbars=1,menubar=0,status=0,toolbar=0,top=0,left=0,width="+(screen.width-10)+",height="+(screen.height-72);

function slide() {
  // This is the constructor function for the slide object.
  // It is called automatically when you create a new slide object.
  // For example:
  // s = new slide();

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

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

  //--------------------------------------------------
  this.load = function() {
    // This method loads the image for the slide

    if (!document.images) { return; }

    if (!this.loaded && this.src != undefined) {
      this.image.src = this.src;
      this.loaded = true;
    }
  }

  this.setMovie = function(movieURL) {
     path = window.location.pathname;
     path = path.substring(0, path.lastIndexOf('/'));
     this.movie     = movieURL;
     this.movieURL  = path + "/" + movieURL;
     this.movieflag = true;
     this.src       = "/images/spacer.gif";
  }


  //--------------------------------------------------
  this.hotlink = function() {
    // This method jumps to the slide's link.
    // If a window was specified for the slide, then it opens a new window.

    var mywindow;
    var pauseShow = false;

    // Right now, just assume the target is _blank
    if ( this.link )
    {
       mywindow = window.open(this.link, "_blank");
    }
    else if (this.hires)
    {
        if ( !this.movieflag ) {
           mywindow = window.open(this.hires, "_blank", hiresAttribute);
        } else {
           return;
        }
    }
    else
    {
       return;
    }

    // Pop the window to the front
    if (mywindow && mywindow.focus) mywindow.focus();
    pauseShow = true;

    return pauseShow;
  }

  //--------------------------------------------------
  this.savehires = function() {
    // This method uses the slides link, except places it inside the context of
    // a CGI script that forces the browser to download it instead of opening
    // it.

    // If this slide does not have a link, do nothing
    if (!this.hires) return;

    // Build a path to the image, since it's locally scoped and our script lives
    // in cgi-bin
    path = window.location.pathname;
    path = path.substring(0, path.lastIndexOf('/'));

    saveurl = this.hires;
    
    location.href = window.location.protocol + "//" + window.location.host +
                    "/cgi-bin/download.cgi?file=" + path + "/" + saveurl;
    return true;
  }


}

//==================================================
// slideshow object
//==================================================
function slideshow( slideshowname ) {
  // This is the constructor function for the slideshow object.
  // It is called automatically when you create a new object.
  // For example:
  // ss = new slideshow("ss");

  // Name of this object
  // (required if you want your slideshow to auto-play)
  // For example, "SLIDES1"
  this.name = slideshowname;

  // When we reach the last slide, should we loop around to start the
  // slideshow again?
  this.repeat = false;

  // Number of images to pre-fetch.
  // -1 = preload all images.
  //  0 = 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;
  this.prefetch = 3;

  // IMAGE element on your HTML page.
  // For example, document.images.SLIDES1IMG
  this.image;

  // ID of a DIV element on your HTML page that will contain the text.
  // For example, "slides2text"
  // Note: after you set this variable, you should call
  // the update() method to update the slideshow display.
  this.textid;

  this.stateid;

  this.state_paused  = "<font color='yellow'><b>Slideshow is Paused</b></font>";
  this.state_playing = "Slideshow is Playing";
  this.state = this.state_paused;
  this.previousState;

  this.numberid;

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

  // Hook functions to be called before and after updating the slide
  // this.pre_update_hook = function() { }
  // this.post_update_hook = function() { }

  // These are private variables
  this.slides = new Array();
  this.current = 0;
  this.timeoutid = 0;

  //--------------------------------------------------
  // Public methods
  //--------------------------------------------------
  this.add_slide = function(slide) {
    // Add a slide to the slideshow.
  
    var i = this.slides.length;

    // Prefetch the slide image if necessary
    if (this.prefetch == -1) { slide.load(); }

    this.slides[i] = slide;
  }


  //--------------------------------------------------
  // Move to the next slide, then start playing
  this.nextAndPlay = function(timeout) {
     this.next();
     this.play(timeout);
  }
   
  //--------------------------------------------------
  this.play = function(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.
  
    // Make sure we're not already playing
    this.pause(1);
  
    // If the timeout argument was specified (optional)
    // then make it the new default
    if (timeout) {
      this.timeout = timeout;
    }

    this.state = this.state_playing;
    this.display_state()
    
  
    // If the current slide has a custom timeout, use it;
    // otherwise use the default timeout
    if (typeof this.slides[ this.current ].timeout != 'undefined') {
      timeout = this.slides[ this.current ].timeout;
    } else {
      timeout = this.timeout;
    }

    // After the timeout, call this.loop()
    this.timeoutid = setTimeout( this.name + ".loop()", timeout);
  }

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

      clearTimeout(this.timeoutid);
      this.timeoutid = 0;

      if ( silentMode != 1 ) {
         this.state = this.state_paused;
         this.display_state();
      }
    }
  }

  //----------------------------------------------------------------------
  this.setState = function(stateText) 
  {
     // Pause the slideshow
     this.pause(1);
     this.state = stateText;
     this.display_state();
  }

  //--------------------------------------------------
  this.update = function() {
    // This method updates the slideshow image on the page

    // Make sure the slideshow has been initialized correctly
    if (! this.valid_image()) { return; }

    // Convenience variable for the current slide
    var slide = this.slides[ this.current ];

    // First, see if this is a movie or a photo.  If this is a movie, there's no
    // need to call the update hooks...
    var dofilter = false;
    if ( !slide.movieflag ) 
    {
       // Call the pre-update hook function if one was specified
       if (typeof this.pre_update_hook == 'function') {
         this.pre_update_hook();
       }

       // Determine if the browser supports filters
       if (this.image &&
           typeof this.image.filters != 'undefined' &&
           typeof this.image.filters[0] != 'undefined') {
         dofilter = true;
       }

       // Load the slide image if necessary
       slide.load();
     
       // Apply the filters for the image transition
       if (dofilter) {

         // If the user has specified a custom filter for this slide,
         // then set it now
         if (slide.filter &&
             this.image.style &&
             this.image.style.filter) {
           this.image.style.filter = slide.filter;
         }
         this.image.filters[0].Apply();
       }
    }
    else
    {
       // Even an empty spacer must be loaded to be displayed...
       slide.load();
    }

    // Update the image.
    this.image.src = slide.image.src;

    // Play the image transition filters
    if (dofilter) {
      this.image.filters[0].Play();
    }

    // Update the text
    this.display_text();
    this.display_state();

    // Call the post-update hook function if one was specified
    if (!slide.movieflag && typeof this.post_update_hook == 'function') {
      this.post_update_hook();
    }

    // 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.slides.length) next = 0;
        if (--prev < 0) prev = this.slides.length - 1;

        // Preload the slide image
        this.slides[next].load();
        this.slides[prev].load();

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

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

  //--------------------------------------------------
  this.goto_slide = function(n) {
    // This method jumpts to the slide number you specify.
    // If you use slide number -1, then it jumps to the last slide.
    // You can use this to make links that go to a specific slide,
    // or to go to the beginning or end of the slideshow.
    // Examples:
    // onClick="myslides.goto_slide(0)"
    // onClick="myslides.goto_slide(-1)"
    // onClick="myslides.goto_slide(5)"
  
    if (n == -1) {
      n = this.slides.length - 1;
    }
  
    if (n < this.slides.length && n >= 0) {
      this.current = n;
    }
  
    this.update();
  }


  //--------------------------------------------------
  this.next = function() {
    // This method advances to the next slide.

    // Increment the image number
    if (this.current < this.slides.length - 1) {
      this.current++;
    } else if (this.repeat) {
      this.current = 0;
    } else { // No repeat mode
      this.setState("<b>Slideshow is complete</b><br><a href='"+ window.location.pathname +"?image=1&play=1'>Click here to return to restart the show</a>");
    }

    this.update();
  }


  //--------------------------------------------------
  this.previous = function() {
    // This method goes to the previous slide.
  
    // Decrement the image number
    if (this.current > 0) {
      this.current--;
    } else if (this.repeat) {
      this.current = this.slides.length - 1;
    }
  
    this.update();
  }



  //--------------------------------------------------
  this.get_text = function() {
    // This method returns the text of the current slide
  
    return(this.slides[ this.current ].text);
  }


  //--------------------------------------------------
  this.display_text = function() {
    // Display the text for the current slide
  
    // Construct the text for this slide from the parameters specified
    s = this.slides[ this.current ];

    var photocredit = "Photo by ";
    var text = "";

    // Is this a movie?  If so, add the movie display text
    if ( s.movieflag )
    {
       text += flashEmbedCode(s);

       photocredit = "Video by ";
    }
    // End movie checkout section

    if ( s.credit != undefined ) {
      text += "<p id=photoPage_credit>" + photocredit +
             s.credit + "</p>";
    }

    text += "<p id=photoPage_caption>" + s.caption + "</p>";

    if ( s.timestamp != undefined ) {
       text += "<p id=photoPage_timeStamp>" + s.timestamp + "</p>";
    }

    if ( s.description != undefined ) {
       text += "<p id=photoPage_desc>" + s.description + "</p>";
    }

    // Add the "Get Flash" link to the text block:
    if ( s.movieflag )
    {
       text += '<br><br><p id=photoPage_getFlash>Video Not Working?  Download the free Adobe Flash Player<br><a href="http://www.macromedia.com/go/getflashplayer" target="_blank" ><img src="/images/get_flash_player.gif" width=88 height=31 border="0"></a></p>';
    }
   


    // If a text id has been specified,
    // then change the contents of the HTML element
    if (this.textid) 
    {
      r = this.getElementById(this.textid);
      if (r && (typeof r.innerHTML != 'undefined') ) {
         // Update the text
         r.innerHTML = text;
      }
    }

    // DISPLAY THE SLIDE NUMBER, if a number id has been defined
    if (this.numberid) 
    {
      r = this.getElementById(this.numberid);
      if (r && (typeof r.innerHTML != 'undefined') ) {
         // Update the text
         r.innerHTML = (this.current + 1) + " of " + this.slides.length;
      }
    }

    // DISPLAY LINK TEXT
    if (this.linkid) 
    {
      r = this.getElementById(this.linkid);
      if (r && (typeof r.innerHTML != 'undefined') ) 
      {
         if ( this.slides[ this.current ].hires ) 
         {

            // If this is a movie, display slightly different text
            if ( this.slides[ this.current ].movieflag )
            {
               r.innerHTML = "<a href='javascript:SLIDES.savehires();'>" + 
                             "Click here to download this video</a>"; 
            }
            else
            {
               // Update the text
               r.innerHTML = "Click on the photo to view it larger, " + 
                             "or <a href='javascript:SLIDES.savehires();'>" + 
                             "click here to download the image.</a>" + 
                             " The slideshow will pause automatically.";
            }
         }
         else { r.innerHTML = "&nbsp;" }
      }
    }


    
  }



  //--------------------------------------------------
  // Brian's homegrown additions
  this.display_state = function() {
  
    // If the "text" arg was not supplied (usually it isn't),
    // get the text from the slideshow
    text = this.state;
    if ( text != this.previousState )
    {
       // If a text id has been specified,
       // then change the contents of the HTML element
       if (this.stateid) {
         r = this.getElementById(this.stateid);
         if (!r) { return false; }
         if (typeof r.innerHTML == 'undefined') { return false; }

         // Update the text
         r.innerHTML = text;
         this.previousState = text;
       }
    }

  }



  //--------------------------------------------------
  this.hotlink = function() {

    // This method calls the hotlink() method for the current slide.
  
    var pauseShow = this.slides[ this.current ].hotlink();
    if ( pauseShow ){
       this.pause();
     }
  }

  //--------------------------------------------------
  this.savehires = function() {
    // This method calls the savehires() method for the current slide.
  
    var pauseShow = this.slides[ this.current ].savehires();
    if ( pauseShow ){
       this.pause();
     }
  }


  //--------------------------------------------------
  this.save_position = function(cookiename) {
    // Saves the position of the slideshow in a cookie,
    // so when you return to this page, the position in the slideshow
    // won't be lost.
  
    if (!cookiename) {
      cookiename = this.name + '_slideshow';
    }
  
    document.cookie = cookiename + '=' + this.current;
  }

  //--------------------------------------------------
  this.go = function()
  {
     if ( this.defPlay ) {
        this.play();
     }
  }
  
  //--------------------------------------------------
  this.restore_position = function(cookiename) {

     // If this URL was called with a web query specifying an image, jump to it
     // and don't start playing
    
     FORM_DATA = createRequestObject();
     // This is the array/object containing the GET data.
     // Retrieve information with 'FORM_DATA [ key ] = value'.

	  var image    = FORM_DATA['image'];
	  var playFlag = FORM_DATA['play'];

     
     if ( image != null )
     {
        this.current = parseInt(image - 1);
        this.defPlay = false;
     }
     else // Just grab a cookie
     {
        this.defPlay = true;
        // If you previously called slideshow_save_position(),
        // returns the slideshow to the previous state.
       
        //Get cookie code by Shelley Powers
       
        if (!cookiename) {
          cookiename = this.name + '_slideshow';
        }
       
        var search = cookiename + "=";
       
        if (document.cookie.length > 0) {
          offset = document.cookie.indexOf(search);
          // if cookie exists
          if (offset != -1) { 
            offset += search.length;
            // set index of beginning of value
            end = document.cookie.indexOf(";", offset);
            // set index of end of cookie value
            if (end == -1) end = document.cookie.length;
            this.current = parseInt(unescape(document.cookie.substring(offset, end)));
            }
         }
     }
     
     if ( playFlag == '1' ) {
        this.defPlay = true;
     }

  }



  //==================================================
  // 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.

    var lastSlide = false;
    // Make sure the next slide image has finished loading
    if (this.current < this.slides.length - 1) 
    {
      next_slide = this.slides[this.current + 1];
      if (next_slide.image.complete == null || next_slide.image.complete) {
        this.next();
      }
    } 
    else // we're at the last slide
    { 
      this.next();
      lastSlide = true;
    }
    
    if (!this.repeat && lastSlide) 
    {    
       // Do nothing...we're at the end   
    } 
    else if ( this.slides[ this.current ].movieflag )
    {
       // This is a movie slide...pause
       this.pause();
    }
    else 
    {
       // Keep playing the slideshow
       this.play( );
    }
  }


  //--------------------------------------------------
  this.valid_image = function() {
    // Returns 1 if a valid image has been set for the slideshow
    if (!this.image) { return false; } else { return true; }
  }

  //--------------------------------------------------
  this.getElementById = function(element_id) {
    // This method returns the element corresponding to the id

    if (document.getElementById) {
      return document.getElementById(element_id);
    }
    else if (document.all) {
      return document.all[element_id];
    }
    else if (document.layers) {
      return document.layers[element_id];
    } else {
      return undefined;
    }
  }

}

// END SLIDESHOW OBJECT --------------------------------------------------

function flashEmbedCode(slideObj)
{
   var width = 330;
   var height = 270;
   // autoPlay=true&flvPath=/photos/2007/flash/lowres/flash_exp-3.flv&flvTitle=&bgColor=0x000066&startFrame=1


   var FlashVars = 'autoPlay=true&flvPath=' + slideObj.movieURL + 
                   '&flvTitle=' + slideObj.caption + 
                   '&bgColor=0x000066&startFrame=1';
   

   //var FlashVars = "autoPlay=true&flvPath=/photos/2007/flash/lowres/flash_exp-3.flv&flvTitle=&bgColor=0x000066&startFrame=1";

   var flashText = '<p id=photoPage_photoBlock>' +
          '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' 
          + width + '" height="'+height+'">' 
          + '<PARAM NAME="width"   VALUE="' + width + '"/>'
          + '<PARAM NAME="height"  VALUE="'+height+'"/>'
          + '<PARAM NAME="align"   VALUE="middle"/>'
          + '<PARAM NAME="src"     VALUE="/styles/flvplayer.swf"/>'
          + '<PARAM NAME="name"    VALUE="' + slideObj.caption + '"/>'
          + '<PARAM NAME="quality" VALUE="high"/>'
          + '<PARAM NAME="bgColor" VALUE="#000066"/>'
          + '<PARAM NAME="type" VALUE="application/x-shockwave-flash"/>'
          + '<PARAM NAME="allowScriptAccess" VALUE="sameDomain"/>'
          + '<PARAM NAME="pluginspage" VALUE="http://www.macromedia.com/go/getflashplayer"/>'
          + '<PARAM NAME="FlashVars" VALUE="' + FlashVars + '"/>'
          + '<embed width="' + width + '" height="'+height+'" align="middle" src="/styles/flvplayer.swf" '
          + 'name="' + slideObj.caption + '" '
          + 'FlashVars="'+ FlashVars + '"'
          + 'bgColor="#000066"'
          + 'allowScriptAccess="sameDomain"'
          + 'quality="high"'
          + 'type="application/x-shockwave-flash"'
          + 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>' 
          + '</object></p>';

   return flashText;

}

//================================================================================
//================================================================================
//================================================================================

/*
Webmonkey GET Parsing Module
Language: JavaScript 1.0
The parsing of GET queries is fundamental
to the basic functionality of HTTP/1.0.
This module parses GET with JavaScript 1.0.
Source: Webmonkey Code Library
(http://www.hotwired.com/webmonkey/javascript/code_library/)
Author: Patrick Corcoran
Author Email: patrick@taylor.org
*/

function createRequestObject() {
  FORM_DATA = new Object();
    // The Object ("Array") where our data will be stored.
  separator = ',';
    // The token used to separate data from multi-select inputs
  query = '' + this.location;
  qu = query
    // Get the current URL so we can parse out the data.
    // Adding a null-string '' forces an implicit type cast
    // from property to string, for NS2 compatibility.
  query = query.substring((query.indexOf('?')) + 1);
    // Keep everything after the question mark '?'.
  if (query.length < 1) { return false; }  // Perhaps we got some bad data?
  keypairs = new Object();
  numKP = 1;
    // Local vars used to store and keep track of name/value pairs
    // as we parse them back into a usable form.
  while (query.indexOf('&') > -1) {
    keypairs[numKP] = query.substring(0,query.indexOf('&'));
    query = query.substring((query.indexOf('&')) + 1);
    numKP++;
      // Split the query string at each '&', storing the left-hand side
      // of the split in a new keypairs[] holder, and chopping the query
      // so that it gets the value of the right-hand string.
  }
  keypairs[numKP] = query;
    // Store what's left in the query string as the final keypairs[] data.<
  for (i in keypairs) {
    keyName = keypairs[i].substring(0,keypairs[i].indexOf('='));
      // Left of '=' is name.
    keyValue = keypairs[i].substring((keypairs[i].indexOf('=')) + 1);
      // Right of '=' is value.
    while (keyValue.indexOf('+') > -1) {
      keyValue = keyValue.substring(0,keyValue.indexOf('+')) + ' ' + keyValue.substring(keyValue.indexOf('+') + 1);
        // Replace each '+' in data string with a space.
    }
    keyValue = unescape(keyValue);
      // Unescape non-alphanumerics
    if (FORM_DATA[keyName]) {
      FORM_DATA[keyName] = FORM_DATA[keyName] + separator + keyValue;
        // Object already exists, it is probably a multi-select input,
        // and we need to generate a separator-delimited string
        // by appending to what we already have stored.
    } else {
      FORM_DATA[keyName] = keyValue;
        // Normal case: name gets value.
    }
  }
  return FORM_DATA;
}


