// Clever Javascript animated from
//     http://www.the-digital-picture.com/Reviews/Canon-EOS-1D-Mark-III-Digital-SLR-Camera-10fps-Video.aspx

document.getElementById('loading_images').innerHTML = "Loading Images";
var nloop=0;
var reload_loop=1000;
var inc = 1.50;
var num_loaded_images = 0;
var frame=-1;
var timeout_id=null;
var dir=1, playing=0, run=0;
var index=0;
var testintro = /intro.jpg/; 


function load_img() {        // asynchronously load all images into cache
 for (i=0; i < maxImages ; i++) {
  id[i]=setTimeout("load_src()",0);
 }
 return;
}

function load_src() {      // load individual images into cache
 if (index < maxImages) {
  images[index] = new Image();
  images[index].onload=count_images;
  images[index].src = urls[index];
  index++;
 }
 return;
}

function clear_ids() {         // clear asynchronous id's
 for (i=0; i < maxImages ; i++) {clearTimeout(id[i]);}
 return;
}

function count_images() { 
 // count images as they are loaded into cache
 if (++num_loaded_images == maxImages) {
  show_speed();
  clear_ids();
  animate();
 } else {
  // Lets not start the slide-show until they are all loaded
  // document.JPGAnimation.src=images[num_loaded_images-1].src;
  document.getElementById('loading_images').innerHTML = "<strong>Loading "+num_loaded_images+" of "+maxImages+ " Images</strong>"; 
 }
}

function start_play()  {
 // start movie
 if (playing == 0) {
  if (timeout_id == null && num_loaded_images==maxImages) animate();
 }
} 

function stop_play() { 
// stop movie
 if (timeout_id) clearTimeout(timeout_id); 
  timeout_id=null;
  playing = 0;
} 

function animate()  {
 // control movie loop
 var j;
 frame=(frame+dir+maxImages)%maxImages;
 j=frame+1;
 if (j == maxImages) 
  { nloop = nloop + 1;
    if (nloop > reload_loop) 
     { nloop = 0;
       document.getElementById('loading_images').innerHTML = "Reloading... ";
       window.location.reload();
     }
  }
 if (images[frame].complete) {
  // This handles the case where everything has been loaded and keeps looping
  document.JPGAnimation.src=images[frame].src;
  document.getElementById('loading_images').innerHTML = "Displaying #"+j+" of "+maxImages+ " Images";
  if (testintro.test(images[frame].src) ) { 
     timeout_id=setTimeout("animate()",intro_delay);
  } else {
     timeout_id=setTimeout("animate()",delay);
  }
  playing=1;
 }
}

function step() {
 // step frames
 var j;
 if (timeout_id) clearTimeout(timeout_id); timeout_id=null;
 frame=(frame+dir+maxImages)%maxImages;
 j=frame+1;
 if (images[frame].complete) {
  document.JPGAnimation.src=images[frame].src;
  document.getElementById('loading_images').innerHTML = "Displaying #"+j+" of "+maxImages+ " Images";
  playing=0;
 }
}

function show_speed() {
  // show speed
  document.getElementById('frame_rate').innerHTML = (Math.round(10*speed))/10+" frames/sec";
  delay = 1000.0/speed; 
  reload_loop = 1200*speed/maxImages ;
}
