var slideShow = document.getElementById("frontpageslide");

var FPS = 25;
var Duration = .2;
var FlipWait = 3;

var FramesTotal = FPS*Duration;


function setCourse(slideIndex){
  fadeImage(slideIndex);
}



// Copy the slides to an internal array, so we can detach them from the DOM without loosing them.
var slides = new Array();
var SlidesInDOM = slideShow.getElementsByTagName("li");
for(var i=0; i<SlidesInDOM.length; i++){
  slides[i] = SlidesInDOM[i];
  setOpacity(slides[i], 0);
}

// Detach the hidden slides from the DOM.
while(slideShow.childNodes.length){
  slideShow.removeChild(slideShow.firstChild);
}


// insert the first.
slideShow.appendChild(slides[0]);
setOpacity(slideShow.getElementsByTagName("li")[0], 1);


var opacity = 1;
var timer = null;
var flipTimer = null;
var currentIndex = 0;
function fadeImage(index){
  if(currentIndex == index) return;

  currentIndex = index;

  clearInterval(timer);
  clearTimeout(flipTimer);
  timer = setInterval(
    function(){fadeOut();},
    1000/FPS
  );
}






var opacity = 1;

function fadeIn(){
  if(opacity < 1){
    opacity += 1/FramesTotal;
    setOpacity(slideShow.getElementsByTagName("li")[0], opacity);
  }else{
    clearInterval(timer);
    setOpacity(slideShow.getElementsByTagName("li")[0], 1);
    flipTimer = setTimeout(function(){setCourse((currentIndex+1)%slides.length);}, FlipWait*1000);
  }
}

function fadeOut(OnDone){
  if(opacity > 0){
    opacity -= 1/FramesTotal;
    setOpacity(slideShow.getElementsByTagName("li")[0], opacity);
  }else{
    clearInterval(timer);
    setOpacity(slideShow.getElementsByTagName("li")[0], 0);
    slideShow.removeChild(slideShow.getElementsByTagName("li")[0]);
    slideShow.appendChild(slides[currentIndex]);
    timer = setInterval(fadeIn, 1000/FPS);
  }
}

function setOpacity(obj, opacity) {
  opacity *= 100;
  opacity = (opacity == 100)?99.999:opacity;
  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";
  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;
  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;
  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}


flipTimer = setTimeout(function(){setCourse(1);}, FlipWait*1000);


