$(window).load(function() {
  $("#fce_thumb_gallery_thumbs_container_loader").hide();
  $("#fce_thumb_gallery_thumbs").show();
  
  
});

$(document).ready(function(){
  
  $("#fce_thumb_gallery_thumbs_container").append('<img id="fce_thumb_gallery_thumbs_container_loader" src="fileadmin/templates/images/thumbs_loader.gif" alt="Lade Bilder..." />');
  
  var elemente = new Array();
  var position = 0;
  var interval;
  
  // Copy alt to src for all images 
  $("ul#fce_thumb_gallery_thumbs li").each(function(index,el){
    var tmp_img = $(el).find("img");
    var tmp_src = $(tmp_img).attr("src");
    var tmp_alt = $(tmp_img).attr("alt");
    $(tmp_img).attr('alt', tmp_src);
  });
  
  // load image into the main view
  function refreshImage(el){
    var image_src = $(el).find("img").attr("src");
    var image = $("#fce_thumb_gallery_main_view").find("img");
    $(image).animate({
      opacity: 0
    }, 500, function(){
      $(this).attr('src', image_src);
    });
    $(image).animate({
      opacity: 1
    }, 500);
  }
  
  // load image
  function LoadImage(el){
    var image = $(el).find("img");
    var image_scr = image.attr('alt');
    var img = new Image();
    $(img).load(function(){
      $(this).hide();
      $(this).attr('height', 45);
      $(this).attr('width', 73);
      $(image).remove();
      $(el).find("a").append(this);
      $(this).fadeIn();
    }).error(function(){}).attr('src',image_scr);
  }
  
  // Click handler for all images
  $("ul#fce_thumb_gallery_thumbs li").each(function(index,el){
    LoadImage(el);
    elemente.push(el);
    $(el).find("a").click(function(){
      window.clearInterval(interval);
      refreshImage(this);
      var link = $(this).attr('href');
      $("#fce_thumb_gallery_main_view").find("a").attr('href', link);
      interval = window.setInterval(nextslide, 5000);
      return false;
    });
  });
  
  // Show first image
  var image_src;
  var link;
  nextslide();
  
  // Show next image in main view
  function nextslide(){
    if (position < elemente.length){
       refreshImage(elemente[position]);
       link = $(elemente[position]).find("a").attr('href');
       $("#fce_thumb_gallery_main_view").find("a").attr('href', link);
       position++;
    } else {
       position = 0;
       refreshImage(elemente[position]);
       link = $(elemente[position]).find("a").attr('href');
       $("#fce_thumb_gallery_main_view").find("a").attr('href', link);
    }
  }
  
  // Start interval
  interval = window.setInterval(nextslide, 5000);
  
});

