$(document).ready(function() {
  var width = 599;
  var height = 471;
  
  var fadeSpeed = 2000;
  var fadeTimeout = 5000;
  
  init();
  
  function init() {
    initFrame();
  
    if (images.length == 1) {
      initSingleImage();
    } else if (images.length > 0) {
      initSlideshow();
    }
  }
    
  function initSingleImage() {
    addImage(0);
  }
  
  function initSlideshow() {
    addImage(0);
    preloadImage(1, fadeImage);
  }
  
  function initFrame() {
    var html = '';
    
    $("#slideshow").append($("<div>").attr("id", "slideshowImages").css({
      width: width +'px',
      height: height +'px',
      position: 'absolute',
      overflow: 'hidden'
    })).append($("<div>").attr("id", "slideshowFrame").css({
      width: width +'px',
      height: height +'px', 
      position: 'absolute',    
      backgroundImage: 'url(/slideshow/images/frame.png)'
    }));
  }
  
  function addImage(i) {    
    $("#slideshowImages").prepend($("<img>").css({
      position: 'absolute'
    }).attr("src", '/slideshow/images/images/'+ images[i]).attr("alt", ""));
  }
  
  function preloadImage(i, func) {    
    $("<img>").bind("load", function() { 
      $("#slideshowImages").prepend($(this));
      
      if (func) {
        func(i);
      }
    }).attr("src", '/slideshow/images/images/'+ images[i]).attr("alt", "").css({
      position: 'absolute'
    });
  }
  
  function fadeImage(i) {
    setTimeout(function() {
      $("#slideshowImages img:last").fadeOut(fadeSpeed, function() {
        preloadImage(calculateNext(i), fadeImage);
        $(this).remove();
      });
    }, fadeTimeout);
  }
  
  function calculateNext(i) {
    var next = i +1;
    
    if (next == images.length) {
      next = 0;
    }
    
    return next;
  }
});
