/*These variables are global defaults that you may want to edit*/

// Course home URL
var courseHome="../index.html";

// Widths of all slide images provided
var widths = new Array(400, 480, 512, 600, 640, 768, 800, 960);

// Heights of all slide images provided
var heights = new Array(300, 360, 384, 450, 480, 576, 600, 768);

/*End of global defaults*/


var presentationRoot;
var commonRoot;

var syncVideo = true;
var currentSlide = 1;
var popup;
var cacheImages=new Array();
var subtitleLang, subtitleFile;

var slideScale = 3;

// Supported player types

var NONE=0;
var REALPLAYER=1;
var QUICKTIME=2;
var JAVAAUDIO=3;
var MSMEDIA=4;

var avPlayerType=0;

// Supported slide types

var IMAGE=2;
var IMAGE_PRELOAD=3;
var APPLET=4;
var FLASH=5;

// Variables used for plugin detection

var hasQuicktime=false, hasRealPlayer=false, hasJavaPlugin=false, hasFlash=false, hasMSMedia=false, vbDetectOK=false;
var qtVersion, realVersion, msVersion=0;

var subtitlesActive=false;
var operaSpoof=false;
var initPres=true;

function initPresentation()
{
 //for (var loop=0; loop<navigator.plugins.length; loop++)
 //{
 // alert(navigator.plugins[loop].name);
 //}

 setBase();

 //Test that everything is properly configured
 if ( typeof(standalone)=="undefined" || standalone==false)
  if (typeof(times) == "undefined")
  {
    alert("Unable to read time values for slideshow.\n" + 
       "Please report this error to\n" + 
       "the website administrator.");
    times = new Array();
  }

 if (typeof(javaAudioSrc) == "undefined" && typeof(qtVideoSrc)  == "undefined" && typeof(realVideoSrc) == "undefined" && typeof(msMediaSrc) == "undefined")
 {
   alert("No Audio/Video source has been configured for this presentation.\n" + 
      "Please report this error to\n" + 
      "the website administrator.");
 }

 if (typeof(realVideoSrc) != "undefined")
  checkOldStyleMedia(realVideoSrc, "Real Player");
 if (typeof(qtVideoSrc) != "undefined")
  checkOldStyleMedia(qtVideoSrc, "Quicktime");
 if (typeof(msMediaSrc) != "undefined")
  checkOldStyleMedia(msMediaSrc, "Windows");
 if (typeof(javaAudioSrc) != "undefined")
  checkOldStyleMedia(javaAudioSrc, "Java Audio");

 if ( typeof(standalone)=="undefined" || standalone==false)
  if (flashSlides==false && appletSlides==false && imageSlidesPreload==false && imageSlides==false)
  {
    alert("No slide source has been configured for this presentation.\n" + 
       "Please report this error to:\n" + 
       "the website administrator.");
  }

 if (typeof(slideType) == "undefined")
    slideType = ".gif";

 //Plugin detection

 if (navigator.userAgent.toLowerCase().indexOf("mac")==-1 && navigator.userAgent.toLowerCase().indexOf("msie")>-1 && vbDetectOK==false)
 {
  //If this lot is true, we probably have a browser spoofing itself as IE, but that isn't actually IE.
  //This is most probably Opera, no other browser spoofs by default
  operaSpoof=true;
 }

 if (vbDetectOK==false) 
 {
  hasRealPlayer=findPlugin("RealPlayer");
  hasQuicktime=findPlugin("QuickTime");
  hasJavaPlugin=findPlugin("Java");
  hasFlash=findPlugin("Shockwave Flash");
  hasMSMedia=findPlugin("Windows Media Player");
 }
 else
  msVersion=parseInt(msVersion);

 if (navigator.userAgent.toLowerCase().indexOf("msie")>-1 || navigator.userAgent.toLowerCase().indexOf("konqueror")>-1 ||
     navigator.userAgent.toLowerCase().indexOf("opera")>-1 )
 {
  if (hasJavaPlugin==false)
   hasJavaPlugin=navigator.javaEnabled();
 }

 //Work out the slide type
 if ( typeof(standalone)=="undefined" || standalone==false)
 {
  var slidesCookie=getCookie("autoview_slides");
  if (validSlideType(slidesCookie))
   presentationType=slidesCookie;
  else
   chooseSlideType();
 }

 //Work out what type of AV source we should use.
 var playerCookie=getCookie("autoview_player");
 if (validAVSource(playerCookie))
  avPlayerType=playerCookie;
 else
  chooseAVType();

 //Should we use subtitles ?
 var subCookie=getCookie("autoview_subtitles");
 if (subCookie!="" && subCookie!="off" && typeof(subtitle_opts)!="undefined")
 {
  subtitleFile=subtitleFileFromLang(subCookie);
  if (subtitleFile!="")
  {
   subtitleLang=subCookie;
   subtitlesActive=true;
  }
 }

 //Image initialisation
 if (typeof(standalone)=="undefined" || standalone==false)
 {
  cacheImages=new Array();
  for (var loop=0; loop<times.length+1; loop++)
    cacheImages[loop]=new Image();

  if (presentationType==IMAGE)
   preloadImage(currentSlide + 1);
 }

}


//*****End of start up functions*****

function subtitleFileFromLang(lang)
{
 for (var loop=0; loop<subtitle_opts.length; loop=loop+2)
  if (subtitle_opts[loop]==lang)
   return subtitle_opts[loop+1];

 return "";
}

function getCookie(Name)
{
 var search = Name + "="
 if (document.cookie.length > 0)
 {
  offset = document.cookie.indexOf(search) 
  if (offset != -1)
  {
   offset += search.length 
   end = document.cookie.indexOf(";", offset) 
   if (end == -1) 
    end = document.cookie.length
   return unescape(document.cookie.substring(offset, end))
  }

  return "";
 }
}

function setCookie(name, value, expire)
{
 if (expire==null)
 {
  var futdate = new Date();
  var expdate = futdate.getTime();
  expdate += ((3600*1000)*24)*365;
  futdate.setTime(expdate);
  expire=futdate;
 }

 document.cookie = name + "=" + escape(value) +" ; path=/ "
  + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))
}

function checkOldStyleMedia(source, name)
{
 //Check for old style configuration in media sources
 if (source.indexOf(relativePath)==0)
 {
  alert(name+" media source starts with the relativePath.\nThis is no longer required for Autoview 2.2, please amend the\nmedia source paths.\n" + 
      "Please report this error to " + 
      "the website administrator.");
 }
}

function validAVSource(type)
{
 if (type==JAVAAUDIO)
  if (typeof(javaAudioSrc) != "undefined" && hasJavaPlugin)
   return true;

 if (type==MSMEDIA)
  if (typeof(msMediaSrc) != "undefined" && hasMSMedia && msVersion>=7)
   return true;

 if (type==QUICKTIME)
  if (typeof(qtVideoSrc)  != "undefined" && hasQuicktime)
   return true;

 if (type==REALPLAYER)
  if (typeof(realVideoSrc)  != "undefined" && hasRealPlayer)
   return true;

 return false;
}

function chooseAVType()
{
 /*Default video player preferences, if more than one player type is found,
 the later one in the list will be choosen by default*/

 var avSequence = new Array(JAVAAUDIO, MSMEDIA, REALPLAYER, QUICKTIME);

 //This sequence works better for Apple Mac Browsers and Opera
 if (navigator.userAgent.toLowerCase().indexOf("mac")>-1 || navigator.userAgent.toLowerCase().indexOf("opera")>-1 || operaSpoof==true)
  avSequence = new Array(REALPLAYER, JAVAAUDIO, QUICKTIME);

 //Better sequences for unix browsers
 if (navigator.userAgent.toLowerCase().indexOf("linux")>-1 || navigator.userAgent.toLowerCase().indexOf("sunos")>-1)
 {
  if (navigator.userAgent.toLowerCase().indexOf("opera")>-1 || navigator.userAgent.toLowerCase().indexOf("konqueror")>-1)
   avSequence = new Array(REALPLAYER, JAVAAUDIO);
  else
  if (findPlugin("Helix DNA") || findPlugin("RealPlayer(tm) G2 LiveConnect-Enabled Plug-In (32-bit)"))
   avSequence = new Array(JAVAAUDIO, REALPLAYER);
  else
   avSequence = new Array(REALPLAYER, JAVAAUDIO);
 }

 for (var loop=0; loop<avSequence.length; loop++)
  if (validAVSource(avSequence[loop])==true)
   avPlayerType=avSequence[loop];

 if (avPlayerType==NONE)
 {
  alert("Unable to locate a suitable audio/video plugin.\n" + 
    "You may need to install additional software to view this presentation,\n" + 
    "please see the help file (click '?' button if it dosn't pop up automatically) for more information.");
 }
}

function validSlideType(type)
{
 if (type==FLASH)
  return flashSlides;

 if (type==IMAGE_PRELOAD)
  return imageSlidesPreload;

 if (type==IMAGE)
  return imageSlides;

 if (type==APPLET)
  return appletSlides;

 return false;
}

function chooseSlideType()
{
 //Work out what slides to use
 presentationType=NONE;

 if (flashSlides==true && hasFlash==true && navigator.userAgent.toLowerCase().indexOf("mac")==-1)
  presentationType=FLASH;
 else
 if (imageSlidesPreload==true)
  presentationType=IMAGE_PRELOAD;
 else
 if (imageSlides==true)
  presentationType=IMAGE;
 else
 if (appletSlides==true && navigator.javaEnabled())
  presentationType=APPLET;

 //Deal with people who can't view the slides
 if (presentationType==NONE)
 {
  var message="We cannot detect a suitable plugin for viewing the slides used with this presentation,\nplease download one of the plugins described below :\n\n";

  if (flashSlides==true)
  {
   if (navigator.userAgent.toLowerCase().indexOf("msie")==-1)
    message=message+" - Macromedia Flash player, please visit\nhttp://www.macromedia.com to download this plugin\n";
   else
    message=message+" - Macromedia Flash player,\nIf you have ActiveX enabled then selecting 'Macromedia Flash' from the\nSlide format menu to the left should start the download automatically.\nOtherwise, please visit http://www.macromedia.com to download this plugin.";
  }

  if (appletSlides==true)
   message=message+" - Sun Java Plugin, please visit http://www.java.com to download the latest plugin."; 

  alert(message);
 }
}
  
// function to determine the urls to be used as commonRoot and presentationRoot
function setBase()
{
 var base = window.location.href;
 var index = base.lastIndexOf('/');
 presentationRoot = base.substring(0, index + 1);

 // relativePath is a presentation specific variable declared in 
 // the frameset for a given presentation. It defines the path from the 
 // common root to the presentation root. If it is undefined it will cause 
 // problems referencing common files
 if (typeof(relativePath) == "undefined")
 {
  commonRoot = presentationRoot;
  alert("Value 'relativePath' has not been defined for this presentation.\n" + 
        "Some images may not display correctly.\nPlease report this error to\n" +
        "the website administrator.");
 }
 else
 {
  index = presentationRoot.lastIndexOf(relativePath);
  commonRoot = presentationRoot.substring(0, index);

  if (commonRoot.length==0)
   alert ("commonRoot length is 0.\nYou have probably not correctly configured the relativePath variable.\nPlease report this error to the website administrator.");
 }
}

function setSyncVideo(sync)
{
 if (syncVideo != sync)
 {
  syncVideo = sync;
  if (syncVideo)
   var newSrc = commonRoot + "vresource/images/syncicon.gif";
  else
   newSrc = commonRoot + "vresource/images/nosyncicon.gif";
    
  window.controls.document.syncButton.src = newSrc;
 }
}

function toggleSyncVideo()
{
 setSyncVideo(!syncVideo);
}

function setLocation(slideNumber)
{
 if (syncVideo && avPlayerType!=NONE)
  setPosition(times[slideNumber-1]);

 setSlide(slideNumber);
}

function setPosition(millis)
{
 if (avPlayerType==REALPLAYER)
  setRealPlayerPosition(millis);
 else
 if (avPlayerType==QUICKTIME)
  setQTPlayerPosition(millis);
 else
 if (avPlayerType==JAVAAUDIO)
  alert("Slide controls cannot be used in synchronised mode with the Java Audio Player.\n"
   +"We reccomend the use of either Real Player or Quicktime (depending on availability) if you require this function.\n\n"
   +"To simply move back and forth through the slides without seeing this message or sychronising the slides with the video,\n"
   +"click the 'Sychronise Slides' button (which should appear as a tick symbol) on the top menu bar.");
 else
 if (avPlayerType==MSMEDIA)
  window.video.document.mediaPlayer.Controls.CurrentPosition=millis/1000;
}

function setRealPlayerPosition(millis)
{
 var player = window.video.document.rplayer;
 if (!player)
 {
  alert("No Player");
  syncVideo=false;
  return;
 }

 if (typeof(player.CanPlay)!="undefined")
 {
  player.DoPlay();
  player.setPosition(millis);
 }
 else
  alert("Warning : Your RealPlayer plugin dosn't support the necesary\nfunctions to synchronise the video stream.");

}

function setQTPlayerPosition(millis)
{
 var rate=window.video.document.qtmovie.GetRate();
 if (rate!=0)
  window.video.document.qtmovie.Stop();

 window.video.document.qtmovie.SetTime((millis/1000)*window.video.document.qtmovie.GetTimeScale());

 if (rate!=0)
  window.video.document.qtmovie.Play();
}

function loadPosition()
{
 var position=getCookie("autoview_"+relativePath);

 if (position>-1)
 {
  setPosition(position);

  var slideNum=getCookie("autoview_currentSlide_"+relativePath);
  if (slideNum>-1)
   setSlide(slideNum);

  var subNum=getCookie("autoview_currentSubtitle_"+relativePath);
  if (subNum>-1 && subtitlesActive)
   getSubtitleFrame().setPosition(slideNum);
 }
 else
  alert("There is no saved position.");
}

function savePosition()
{
 if (avPlayerType==JAVAAUDIO)
 {
  alert("Sorry, the video position cannot be saved in Java Audio mode.");
  return;
 }

 var position=getVideoPosition();
 if (position==-1)
  alert("Position could not be saved");
 else
 {
  setCookie("autoview_"+relativePath, position);
  setCookie("autoview_currentSlide_"+relativePath,currentSlide);
  if (subtitlesActive)
   setCookie("autoview_currentSubtitle_"+relativePath,getSubtitleFrame().currentSubtitle);
  else
   setCookie("autoview_currentSubtitle_"+relativePath,-1);
 }
}

function getVideoPosition()
{
 if (avPlayerType==REALPLAYER)
  return window.video.document.rplayer.GetPosition();
 else
 if (avPlayerType==QUICKTIME)
  return (window.video.document.qtmovie.GetTime()/window.video.document.qtmovie.GetTimeScale())*1000;
 else
 if (avPlayerType==MSMEDIA)
  return window.video.document.mediaPlayer.Controls.CurrentPosition*1000;

 return -1;
}

//Called by A/V Player
function setSlideIfSync(number)
{
 if (syncVideo)
  setSlide(number);
}

function setSlide(number)
{
 if (currentSlide==number)
  return;

 if (typeof(parent.standalone)!="undefined" && parent.standalone==true)
  return;

 if (presentationType==APPLET)
  window.slides.document.slideViewer.setSlide(number);

 if (presentationType==FLASH)
 {
  //var InternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
  //var s = InternetExplorer ? window.slides.flashSlides : window.slides.document.flashSlides;   //embeds[0];

  var s=window.slides.document.flashSlides;

  if (typeof(s)=="undefined" || typeof(s.GotoFrame)=="undefined")
  {
   alert("We have detected that your browser does not support\nthe required functions for the presentation slide\n"+
         "synchronisation and buttons to work when using the\nMacromedia Flash slide format.\n\n"+
         "If you are using Mozilla or Netscape 6/7, we\nhave found that if you have upgraded your browser from\n"+
         "an older version it is sometimes necessary to update\nthe Macromedia Flash player plugin before it will work\n"+
         "properly with the upgraded browser. Visit http://www.macromedia.com\nto get the latest version of the Flash Player.\n\n"+
         "You will now be switched to an alternative slide format\nfor this presentation (see box on the left) if one is available.");

   hasFlash=false;
   chooseSlideType();
   updateSlideOption();
   window.slides.document.location=commonRoot+"/vresource/slideframe.html";
  }
  else
  {
   if (number<currentSlide)
    s.Rewind(); 

   if (number==1)
    window.slides.location.reload();

   s.GotoFrame((number*2)-1);
  }
 }

 if (presentationType==IMAGE || presentationType==IMAGE_PRELOAD)
 {
  // then set the appropriate image in the slides frame and update the 
  // value of currentSlide
  var newImage = getImageFilename(number);
  window.slides.document.slideImage.src = newImage;

  // finally attempt to preload the next image
  preloadImage(number + 1);
 }

 // first of all check to see where we are at the moment so we know whether 
 // we need to change any of the slide control buttons
 var wasFirstOrLast = (currentSlide == 1 || currentSlide == slideCount());

 currentSlide = number;

 // if we have changed to/from the first or last slide, we need to 
 // enable/disable some of the slide controls
 if (wasFirstOrLast || currentSlide == 1 || currentSlide == slideCount())
  updateSlideButtons();
}

function updateSlideOption()
{
 if (typeof(video.updateSlideOption)!="undefined")
  video.updateSlideOption();
}

function preloadImage(number)
{
 if (number > 0 && number <= slideCount())
  if (cacheImages[number].src =! getImageFilename(number) && cacheImages[number].complete==false)
    cacheImages[number].src = getImageFilename(number);
}

function previous() 
{
 if (currentSlide > 1)
  setLocation(currentSlide - 1);
}

function next()
{
 if (currentSlide < slideCount())
  setLocation(currentSlide + 1);
}

function first()
{
 setLocation(1);
}

function last()
{
 setLocation(slideCount());
}

function slideCount() 
{
 return times.length;
}

function getCurrentSlideNumber()
{
 return currentSlide;
}

function getImageFilename(slideNumber)
{
 var fname = presentationRoot + "images/img";

 if (slideNumber < 10)
  fname += "0";
 if (slideNumber < 100)
  fname += "0";
  
 fname += slideNumber + "_" + slideScale + slideType;
  
 return fname;
}

function popupWindow(file)
{
 if (!popup || popup.closed)
 {
  popup=window.open(file,"popUp", 
   "width=350,height=400,status=no,toolbar=no," + 
   "menubar=no,scrollbars=yes,resizable=1");
 }
 else
 {
  popup.location=file;
  popup.focus();
 }
}

function goHome()
{
 window.location = courseHome;
}

function getFrameWidth(frame)
{
 return (frame.innerWidth) ? frame.innerWidth : 
  frame.document.body.clientWidth;
}

function getFrameHeight(frame)
{
 var height = (frame.innerHeight) ? frame.innerHeight : frame.document.body.clientHeight;

 /** IE manages to return 0 for frames which aren't fully loaded, so return the 
     height of the main frame minus the height of the button bar if result is 0 **/
 if (height==0 && navigator.userAgent.toLowerCase().indexOf("msie")>-1)
  height=window.document.body.clientHeight-44;

 return height;
}

function getSlideWidth()
{
 return widths[slideScale - 1];
}

function getSlideHeight()
{
 return heights[slideScale - 1];
}

function calculateSlideSize()
{
 var availableWidth = parseInt(getFrameWidth(window.slides) * 0.93);
 var factor=0.93;
 if (subtitlesActive)
  factor=0.80;
 var availableHeight = parseInt(getFrameHeight(window.slides) * factor);
 var slideWidth;
 var slideHeight;
 var aspect = 0.75;
 var scaleToWidth = (availableWidth * aspect) < availableHeight;

 /**
 if (availableHeight==0)
 {
  alert(availableHeight);
  scaleToWidth=true;
  availableHeight=availableWidth*0.75;
 }
 **/

 if (scaleToWidth)
 {
  slideWidth = availableWidth;
  slideHeight = parseInt(availableWidth * aspect);
  setSlideScale(slideWidth, true);
 }
 else
 {
  slideHeight = availableHeight;
  slideWidth = parseInt(availableHeight / aspect);
  setSlideScale(slideHeight, false);
 }
}

function setSlideScale(dim, isWidth)
{
 var i = 1;
 if (isWidth)
 {
  while (i < widths.length && dim > widths[i])
   i++;
 }
 else
 {
  while (i < heights.length && dim > heights[i])
   i++;
 }

 slideScale = i;
}
    

function handleResize()
{
 if (presentationType == IMAGE_PRELOAD)
  window.slides.document.location="slideframe.html";
 else
  window.slides.document.location.reload();

 // we only want to reload the video frame if the player is stopped, 
 // otherwise we'll reset it back to the beginning of the clip
 stopPlayer()
  
 // NN has a habit of redrawing the button frame with reference to the 
 // original images, regardless of the current state, so just make sure 
 // that all the buttons are correct
 if (!syncVideo)
  window.controls.document.syncButton.src = commonRoot + "vresource/images/nosyncicon.gif";

 updateSlideButtons();
}

function stopPlayer()
{
 if (avPlayerType==REALPLAYER)
  stopRealPlayer();
 else
 if (avPlayerType==QUICKTIME)
  stopQT();
 else
 if (avPlayerType==JAVAAUDIO)
  stopJavaAudio();
}

function stopRealPlayer()
{
 var player = window.video.document.rplayer;  
 if (player && !player.CanStop())
  window.video.location.reload();
}

function stopQT()
{
 if (window.video.document.qtmovie)
 {
  window.video.document.qtmovie.Stop();
  window.video.location.reload();
 }
}

function stopJavaAudio()
{
 if (window.slides.document.slideViewer)
  window.slides.document.slideViewer.stopPlayer();
}


function updateSlideButtons()
{
 var doc = window.controls.document;
 var iroot = commonRoot + "vresource/images/";
  
 var fsrc = (currentSlide > 1) ? iroot + "firstactive.gif" :
   iroot + "firstinactive.gif";
 var psrc = (currentSlide > 1) ? iroot + "prevactive.gif" : 
   iroot + "previnactive.gif";
    
 var nsrc = (currentSlide < slideCount()) ? iroot + "nextactive.gif" : 
   iroot + "nextinactive.gif";
 var lsrc = (currentSlide < slideCount()) ? iroot + "lastactive.gif" : 
   iroot + "lastinactive.gif";
    
 doc.firstImage.src = fsrc;
 doc.prevImage.src = psrc;
 doc.nextImage.src = nsrc;
 doc.lastImage.src = lsrc;
}

function allSlides()
{
 var exwin;
 exwin=window.open("blank.html","all_slides","width=640,height=480,status=yes,toolbar=yes,menubar=yes,scrollbars=yes,resizable=1");
 exwin.focus();

 exwin.document.writeln('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');

 exwin.document.writeln("<html>\n"+
  "<head><title>All Presentation Slides</title></head>\n"+
  "<body bgcolor='#ffffff'>\n");

 exwin.document.writeln("<h1 align=\"center\">"+window.document.title+"</h1>");

 for (loop=1; loop<times.length+1; loop++)
 {
  exwin.document.writeln("<p style='page-break-after: always' align='center'>");

  exwin.document.writeln("<b>Slide "+loop+"</b><br/><br/>\n"+
   "<img src='"+getFixedImageFilename(loop)+"' broder='1' width='480' height='360'><br/><br/><br/>");

  loop++;
  if (loop<times.length+1)
   exwin.document.writeln("<b>Slide "+loop+"</b><br/><br/>\n"+
    "<img src='"+getFixedImageFilename(loop)+"' border='1' width='480' height='360'><br/><br/><br/>");

  exwin.document.writeln("</p>\n");
 }

 exwin.document.writeln("</body>\n</html>");
}

function getFixedImageFilename(slideNumber)
{
 var fname = presentationRoot + "images/img";
  
 if (slideNumber < 10)
  fname += "0";
 if (slideNumber < 100)
  fname += "0";
  
 fname += slideNumber + "_8" + slideType;
 return fname;
}

function getSubtitleFrame()
{
 if (typeof(parent.standalone)!="undefined" && parent.standalone==true)
  return window.video.subtitles;
 else
  return window.slides.subtitles;
}

//*****Plugin detection*****

function findPlugin(toFind)
{
 for (var loop=0; loop<navigator.plugins.length; loop++)
 {
  if (navigator.plugins[loop].name.indexOf(toFind)>-1)
   return true;
 }

 return false;
}
