/*==================================================*
 $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 self 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 self file:
// "slide" - contains all the information for a single slide
// "slideshow" - consists of multiple slide objects and runs the slideshow

//==================================================
// slide object
//==================================================
function slide(src, thumbsrc, link,text,target,attr) {
  // 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();
  var self = this;
  // Image URL
  self.src = src;
  self.thumbsrc = thumbsrc;
  // Link URL
  self.link = link;

  // Text to display
  self.text = text;

  // Name of the target window ("_blank")
  self.target = target;

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

  // Attributes for the target window:
  // width=n,height=n,resizable=yes or no,scrollbars=yes or no,
  // toolbar=yes or no,location=yes or no,directories=yes or no,
  // status=yes or no,menubar=yes or no,copyhistory=yes or no
  // Example: "width=200,height=300"
  self.attr = attr;

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

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

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

    if (!document.images) { return; }

    if (!self.loaded) {
      self.image.src = self.src;
    //  self.thumbImage.src = self.thumbsrc;
      self.loaded = true; 
    }
  }

  //--------------------------------------------------
  self.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;

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

    // Open the link in a separate window?
    if (self.target) {

      // If window attributes are specified,
      // use them to open the new window
      if (self.attr) {
        mywindow = window.open(self.link, self.target, self.attr);
  
      } else {
        // If window attributes are not specified, do not use them
        // (self will copy the attributes from the originating window)
        mywindow = window.open(self.link, self.target);
      }

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

    } else {
      // Open the link in the current window
      location.href = self.link;
    }
  }
}

function thumb (src, index)
{
    var self = this;
    self.src = src;
    self.index = index;
    
     // Create an image object for the slide
      if (document.images) {
        self.image = new Image();
      }

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

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

        if (!document.images) { return; }

        if (!self.loaded) {
          self.image.src = self.src;
          self.loaded = true;
        }
      }
}
//==================================================
// slideshow object
//==================================================

function slideshow( slideshowname, config_file, thumbsPlaceId ) {
   var self = this;
  // 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 self object
  // (required if you want your slideshow to auto-play)
  // For example, "SLIDES1"
  self.name = slideshowname;

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

  // 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.
  self.prefetch = -1;

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

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

    self.thumbsPlaceId = thumbsPlaceId;
     self.thumbsPlace  = null;
  // TEXTAREA element on your HTML page.
  // For example, document.SLIDES1FORM.SLIDES1TEXT
  // This is a depracated method for displaying the text,
  // but you might want to supply it for older browsers.
  self.textarea;

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

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


  self.config_file = config_file;
  self.configXDoc = null;
  
  // These are private variables
  self.slides = new Array();
  self.current = 0;
  self.timeoutid = 0;
  
  self.thumbs = new Array();

  //--------------------------------------------------
  // Public methods
  //--------------------------------------------------
  self.init = function()
  {
    self.thumbsPlace = self.getElementById(self.thumbsPlaceId);
    if (self.config_file != null)
    {
        var url = window.location.href;
        var ind = url.lastIndexOf("/");
        if (ind >0)
        {
            url = url.substr(0,ind);
        }
        if (config_file.indexOf('/') != 0)
            url +='/';
        url = url + config_file;
        self.configXDoc = XML.load(url);//xmlHelper.createFromURL(url);
        var nodes = XML.selectNodes(self.configXDoc, "//image");
        var len = nodes.length;
        ind = url.lastIndexOf("/");
        if (ind >0)
        {
            url = url.substr(0,ind);
        }
        
        for (var i = 0; i< len; i++)
        {
            var src = XML.selectNodeText(nodes[i],"filename");
            if (src.indexOf('/') != 0)
            {
                src = '/'+src;
            }
            var d = new Date();
            var thumbsrc = '/thumbs'+src + '?'+d.getMonth()+d.getDate()+d.getHours()+d.getMinutes()+d.getSeconds();
            src = '/images'+src;
            var text = XML.selectNodeText(nodes[i],"caption");
            var sl = new slide(url+src, url+thumbsrc, null, text);
            self.add_slide(sl);
        }
     }
    if (self.thumbsPlace != null)
    {
        self.initThumbs();
    }
  }
  
  self.thumbCurrentPage = 0;
 
  self.thumbPages = new Array();
  self.thumbRows = 3;
  self.thumbCols = 3;
  
  self.initThumbs = function()
  {
    if (self.thumbsPlace != null)
    {  
        var len = self.slides.length;
        for (var i =0; i<len;i++)
        {
            var t = new thumb(self.slides[i].thumbsrc, i);
            self.add_thumb(t);
        }
        self.onThumbsClick = self.thumbsPlace.getAttribute("onThumbsClick");
        
        self.drawThumbs();
    }
  }
  
  self.ThumbsClick = function(obj, evt)
  {
    var index = parseInt(obj.getAttribute("curInd"));
    if (self.onThumbsClick)
    {
        Exec(self.onThumbsClick);
    }
    self.pause();
    self.goto_slide(index);
  }
  
   self.drawThumbs = function()
   {
        var perPage = self.thumbRows*self.thumbCols;
        var len = self.thumbs.length;
        var thumbPagesCount = parseInt((len + perPage - 1)/ perPage);
        self.thumbPages = new Array();
        for(var i = 0; i< thumbPagesCount; i++)
        {
            var page = self.drawThumbPage(i, i ==0);
            self.thumbsPlace.appendChild(page);
            self.thumbPages.push(page);
        }
   }
   
  self.drawThumbPage = function(index, show)
  {
    var page = document.createElement('div');
    page.id = self.thumbsPlaceId +"_page_"+index;    
    page.style.display = show ? '' : 'none';
    
    var tbl = document.createElement('table');
    tbl.className = "thumb_table";
    tbl.cellPadding = 0;
    tbl.cellSpacing = 10;    
    var tbody = document.createElement('tbody');
    for (var r = 0; r < self.thumbRows; r++)
    {
        var tr = document.createElement('tr');
        for (var c =0; c< self.thumbCols; c++)
        {
            var td = document.createElement('td');
            var curInd = index*self.thumbRows*self.thumbCols + r*self.thumbCols + c;
            if (curInd >=  self.thumbs.length)
            {
                td.innerHTML = "&nbsp;";
                td.className = "empty";
            }
            else
            {
                var img = document.createElement('img');
                img.id = page.id+"_img_"+curInd;
                img.setAttribute('curInd', curInd);
                img.src = self.thumbs[curInd].src;
                AddHandler(img, 'click', self.ThumbsClick);
                td.appendChild(img);
            }
            tr.appendChild(td);
        }
        tbody.appendChild(tr);
    }
    tbl.appendChild(tbody);
    page.appendChild(tbl);
    return page;
  }
  self.goto_page = function(n)
  {     
        var len = self.thumbPages.length;
        for (var i = 0; i< len;i++)
        {
            if (self.thumbPages[i] != null)
            {
                self.thumbPages[i].style.display = (i != n) ? 'none' : '';
            }
        }
  }
  
  self.nextpage = function()
  {
        var cur = self.thumbCurrentPage;
        var next = cur +1;
        if (next >= self.thumbPages.length)
            next = 0;
        self.thumbPages[cur].style.display = 'none';
        self.thumbPages[next].style.display = '';
        self.thumbCurrentPage = next;
  }
  
  self.prevpage = function()
  {
    var cur = self.thumbCurrentPage;
        var prev = cur - 1;
        if (prev < 0)
            prev = self.thumbPages.length - 1;
        self.thumbPages[cur].style.display = 'none';
        self.thumbPages[prev].style.display = '';
        self.thumbCurrentPage = prev;
  }
  
  
  self.add_slide = function(slide) {
    // Add a slide to the slideshow.
    // For example:
    // SLIDES1.add_slide(new slide("s1.jpg", "link.html"))
  
    var i = self.slides.length;
  
    // Prefetch the slide image if necessary
    if (self.prefetch == -1) {
      slide.load();
    }

    self.slides[i] = slide;
    return i;
  }

  self.add_thumb = function(thumb){
    thumb.load();
    self.thumbs.push(thumb);  
  }
  //--------------------------------------------------
  self.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
    self.pause();
  
    // If the timeout argument was specified (optional)
    // then make it the new default
    if (timeout) {
      self.timeout = timeout;
    }
  
    // If the current slide has a custom timeout, use it;
    // otherwise use the default timeout
    if (typeof self.slides[ self.current ].timeout != 'undefined') {
      timeout = self.slides[ self.current ].timeout;
    } else {
      timeout = self.timeout;
    }

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

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

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

    }
  }

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

    // Make sure the slideshow has been initialized correctly
    if (! self.valid_image()) { return; }
  
    // Call the pre-update hook function if one was specified
    if (typeof self.pre_update_hook == 'function') {
      self.pre_update_hook();
    }

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

    // Determine if the browser supports filters
    var dofilter = false;
    if (self.image &&
        typeof self.image.filters != 'undefined' &&
        typeof self.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 self slide,
      // then set it now
      if (slide.filter &&
          self.image.style &&
          self.image.style.filter) {

        self.image.style.filter = slide.filter;

      }
      self.image.filters[0].Apply();
    }

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

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

    // Update the text
    self.display_text();

    // Call the post-update hook function if one was specified
    if (typeof self.post_update_hook == 'function') {
      self.post_update_hook();
    }

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

      var next, prev, count;

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

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

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

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

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

  //--------------------------------------------------
  self.goto_slide_by_src = function (src)
  {
    var len = self.slides.length;
    for (var i =0; i<len;i++)
    {
        if (self.slides.length.src == src)
        {
            self.goto_slide(i);
            return;
        }
    }
  }
  
  self.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 self 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.3_slide(5)"
  
    if (n == -1) {
      n = self.slides.length - 1;
    }
  
    if (n < self.slides.length && n >= 0) {
      self.current = n;
    }
  
    self.update();
  }


  //--------------------------------------------------
  self.goto_random_slide = 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 (self.slides.length > 1) {

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


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

    // Increment the image number
    if (self.current < self.slides.length - 1) {
      self.current++;
    } else if (self.repeat) {
      self.current = 0;
    }

    self.update();
  }


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


  //--------------------------------------------------
  self.shuffle = function() {
    // This method randomly shuffles the order of the slides.

    var i, i2, slides_copy, slides_randomized;

    // Create a copy of the array containing the slides
    // in sequential order
    slides_copy = new Array();
    for (i = 0; i < self.slides.length; i++) {
      slides_copy[i] = self.slides[i];
    }

    // 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
    self.slides = slides_randomized;
  }


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


  //--------------------------------------------------
  self.get_all_text = function(before_slide, after_slide) {
    // Return the text for all of the slides.
    // For the text of each slide, add "before_slide" in front of the
    // text, and "after_slide" after the text.
    // For example:
    // document.write("<ul>");
    // document.write(s.get_all_text("<li>","\n"));
    // document.write("<\/ul>");
  
    all_text = "";
  
    // Loop through all the slides in the slideshow
    for (i=0; i < self.slides.length; i++) {
  
      slide = self.slides[i];
    
      if (slide.text) {
        all_text += before_slide + slide.text + after_slide;
      }
  
    }
  
    return(all_text);
  }


  //--------------------------------------------------
  self.display_text = function(text) {
    // Display the text for the current slide
  
    // If the "text" arg was not supplied (usually it isn't),
    // get the text from the slideshow
    if (!text) {
      text = self.slides[ self.current ].text;
    }
  
    // If a textarea has been specified,
    // then change the text displayed in it
    if (self.textarea && typeof self.textarea.value != 'undefined') {
      self.textarea.value = text;
    }

    // If a text id has been specified,
    // then change the contents of the HTML element
    if (self.textid) {

      r = self.getElementById(self.textid);
      if (!r) { return false; }
      if (typeof r.innerHTML == 'undefined') { return false; }

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


  //--------------------------------------------------
  self.hotlink = function() {
    // This method calls the hotlink() method for the current slide.
  
    self.slides[ self.current ].hotlink();
  }


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


  //--------------------------------------------------
  self.restore_position = function(cookiename) {
  // If you previously called slideshow_save_position(),
  // returns the slideshow to the previous state.
  
    //Get cookie code by Shelley Powers
  
    if (!cookiename) {
      cookiename = self.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;
        self.current = parseInt(unescape(document.cookie.substring(offset, end)));
        }
     }
  }


  //--------------------------------------------------
  self.noscript = function() {
    // This method is not for use as part of your slideshow,
    // but you can call it to get a plain HTML version of the slideshow
    // images and text.
    // You should copy the HTML and put it within a NOSCRIPT element, to
    // give non-javascript browsers access to your slideshow information.
    // This also ensures that your slideshow text and images are indexed
    // by search engines.
  
    $html = "\n";
  
    // Loop through all the slides in the slideshow
    for (i=0; i < self.slides.length; i++) {
  
      slide = self.slides[i];
  
      $html += '<P>';
  
      if (slide.link) {
        $html += '<a href="' + slide.link + '">';
      }
  
      $html += '<img src="' + slide.src + '" ALT="slideshow image">';
  
      if (slide.link) {
        $html += "<\/a>";
      }
  
      if (slide.text) {
        $html += "<BR>\n" + slide.text;
      }
  
      $html += "<\/P>" + "\n\n";
    }
  
    // Make the HTML browser-safe
    $html = $html.replace(/\&/g, "&amp;" );
    $html = $html.replace(/</g, "&lt;" );
    $html = $html.replace(/>/g, "&gt;" );
  
    return('<pre>' + $html + '</pre>');
  }


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

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

    // Make sure the next slide image has finished loading
    if (self.current < self.slides.length - 1) {
      next_slide = self.slides[self.current + 1];
      if (next_slide.image.complete == null || next_slide.image.complete) {
        self.next();
      }
    } else { // we're at the last slide
      self.next();
    }
    
    // Keep playing the slideshow
    self.play( );
  }


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

  //--------------------------------------------------
  self.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;
    }
  }
  

  //==================================================
  // Deprecated methods
  // I don't recommend the use of the following methods,
  // but they are included for backward compatibility.
  // You can delete them if you don't need them.
  //==================================================

  //--------------------------------------------------
  self.set_image = function(imageobject) {
    // This method is deprecated; you should use
    // the following code instead:
    // s.image = document.images.myimagename;
    // s.update();

    if (!document.images)
      return;
    self.image = imageobject;
  }

  //--------------------------------------------------
  self.set_textarea = function(textareaobject) {
    // This method is deprecated; you should use
    // the following code instead:
    // s.textarea = document.form.textareaname;
    // s.update();

    self.textarea = textareaobject;
    self.display_text();
  }

  //--------------------------------------------------
  self.set_textid = function(textidstr) {
    // This method is deprecated; you should use
    // the following code instead:
    // s.textid = "mytextid";
    // s.update();

    self.textid = textidstr;
    self.display_text();
  }
  
  self.init();
}

