$(document).ready(function(){
  // Make an ajax call on the images.xml and make sure IE6 gets it right
  $.ajax({
     url: "images.xml",
     dataType: ($.browser.msie) ? "text" : "xml",
     success: function(data){
       var xml;
       if (typeof data == "string") {
         xml = new ActiveXObject("Microsoft.XMLDOM");
         xml.async = false;
         xml.loadXML(data);
       } else {
         xml = data;
       }
      
       // parse the xml, find all the images and preload them
       $(xml).find('image').each(function() {
          image = new Image();
          
          // If the last image is loading, attach the slideshow.init() to its 
          // onload callback so the slideshow can start. All Images will be
          // preloaded before the slideshow starts.
          if (slideshow.images.length == $(xml).find('image').length-1) {
            image.onload = function() {
             slideshow.init(); 
            }
          }
          
          image.src = "/slideshow_images/" + this.firstChild.nodeValue;
          image.id = "image-" + slideshow.images.length;
          slideshow.images.push(image);      
       });
     }
   });
});

var slideshow = {
  "images" : [],
  
  // Start the sildeshow with the given Interval in milliseconds
  init : function() {
    setInterval("slideshow.next_image()", 5000);
  },
  
  next_image : function() {
    var current = parseInt($("img").attr("id").match(/\d+/));
    
    // check if there is a next image - else start over at the beginning
    if (slideshow.images[current+1] != undefined) {
      var next_image = current + 1
    } else {
      var next_image = 0;
    }
      
    $("#container").css({opacity: 1.0})
      .animate({opacity: 0.0}, 1000, function() {
        $("img").replaceWith(slideshow.images[next_image]);
      });
    $("#container").animate({opacity: 1.0}, 1000);
  }
}