$(document).ready(function() {
  var width = 838;
  var height = 353;
  
  var fadeSpeed = 1000;
  var fadeTimeout = 2000;
  
  var timer;
      
  init();
  
  function init() {
    if (typeof(images) == "undefined") {
      return;
    }
    
    $("#headerImage").css("cursor", "pointer");
    $("#headerImage").bind("click", function() {
      document.location.href = '/webshop/category/53/Hangornamenten.html';
    });
    
//    $(".slideshowInfo").show();
    
    initFrame();
    
//    var html = '';
    
//    for (var i = 0; i < images.length; i++) {
//      html += '<div class="slideshowBlok"></div>';
//    }
    
//    $("#slideshowBloks").append(html);
    
//    $("#slideshowBloks div").bind("click", function() {  
//      var i = $(this).prevAll().length;
//      
//      toIndex(i);
//    });
  
    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 = '';
    
    $("#headerImage").append($("<div>").attr("id", "slideshowImages").css({
      width: width +'px',
      height: height +'px',
      position: 'absolute',
      overflow: 'hidden'
    }));
  }
  
//  function toIndex(i) {
//    $("#slideshowBloks .slideshowBlok").removeClass("highlight");
//    $("#slideshowBloks .slideshowBlok").eq(i).addClass("highlight");
//    
//    clearTimeout(timer);
//    
//    showImage(i);    
//    
//    preloadImage(calculateNext(i), fadeImage);
//  }
  
  function addImage(i) {         
//    $("#slideshowBloks .slideshowBlok").removeClass("highlight");
//    $("#slideshowBloks .slideshowBlok").eq(i).addClass("highlight");
    
    $("#slideshowImages").prepend($("<img>").css({
      position: 'absolute'
    }).attr("src", images[i]).attr("alt", ""));
  }
  
  function preloadImage(i, func) {    
    $("<img>").bind("load", function() { 
      $("#slideshowImages").prepend($(this));
      
      if (func) {
        func(i);
      }
    }).attr("src", images[i]).attr("alt", "").css({
      position: 'absolute'
    });
  }
  
  function showImage(i) {
    $("#slideshowImages img").remove();
    
    addImage(i);

  }
  
  function fadeImage(i) {               
    timer = setTimeout(function() {      
//      $("#slideshowBloks .slideshowBlok").removeClass("highlight");
//      $("#slideshowBloks .slideshowBlok").eq(i).addClass("highlight");
      
      $("#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;
  }
});