// Returns a array with begin as first element, end as second
// from a video URI fragment
function parseVideoFragment(fragment) {
  ret = Array();
  ret[0] = fragment.substring(fragment.indexOf('=')+1,fragment.indexOf(','));
  ret[1] = fragment.substring(fragment.indexOf(',')+1);
  return ret;
}
$(document).ready(function() {
  $("video source[type='application/ttaf+xml'][src]").each(function() {
        HTML5Caption_playVideo($(this).parent().get(0),$(this).get(0));
  });
  slides = new Array();
  notes = new Array();
  $("ul.toc li[about] a").each(function() {
        about = $(this).parent().eq(0).attr("about");
        fragment = about.substring(about.indexOf('#')+1);
        limits = parseVideoFragment(fragment);
        slideUrl = $(this).get(0).href;
        if ($(this).parents('object').length) {
          notes.push(new Array(HTML5Caption_toSeconds(limits[0]),HTML5Caption_toSeconds(limits[1]),slideUrl));
        } else {
          slides.push(new Array(HTML5Caption_toSeconds(limits[0]),HTML5Caption_toSeconds(limits[1]),slideUrl));
       }
  });
   setInterval(function() {
       video = document.getElementById('video');
       if (!video.paused) {
         currentTime = video.currentTime;
         for (i=0;i<slides.length;i++) {
            if (slides[i][0] < currentTime && slides[i][1] >= currentTime && slides[i][2]) {
               displaySlide(slides[i][2]);
	    }
	  }
         for (i=0;i<notes.length;i++) {
            if (notes[i][0] < currentTime && notes[i][1] >= currentTime && notes[i][2]) {
               displayNote(notes[i][2]);
	    }
	  }

        }
     }, 100);


  $(".toc ul.toc li[about] a").click(function(e) {
      e.preventDefault();
      displaySlide($(this).attr("href"));
      href = $(this).parent().attr("about");
      fragment = href.substring(href.indexOf('#') + 1);
      begin = parseVideoFragment(fragment)[0];
      $("#video").get(0).currentTime = HTML5Caption_toSeconds(begin);
  });
});

function displaySlide(slideUrl) {
 if ($("#slides").attr("data")!=slideUrl) {
   $("#slides").attr("data",slideUrl);
 }
}

function displayNote(url) {
 if ($("#notes").attr("data")!=url) {
   $("#notes").attr("data",url);
 }
}
