//

// Testimony Software Browser JavaScript Library

// © Turtle Lane Studios Pty Ltd, Australia

//

// http://www.turtlelane.com.au

// turtlelane@turtlelane.com.au

//

// Build 20080125

//



// -------- 	GLOBAL VARIABLE DECLARATIONS

//

var TLSMovieTimer = null; //an identifier for the master movie timer. Used by TLSSetTimer function

var TLSMovieTimeScale = null; //stores the time scale used by the movie. Set by TLSGetMovieTime function

var TLSSyncFromMovie = false; //TLSSyncFromMovie: a boolean set to true if the driving media is the movie. This is required so we don't re-set the movie and cause stuttering when syncing media

var TLSImageFrameTrue = (parent.imageframe)?"true":"false"; //a boolean indicating whether the current layout includes an imageframe element

var TLSMovie2True = (parent.document.movie2)?"true":"false"; //a boolean indicating whether the current layout includes a second movie element

var TLSTranscriptFrameTrue = (parent.transcriptframe)?"true":"false"; //a boolean indicating whther the current layout includes an transcriptframe element

var TLSTocFrameTrue = (parent.tocframe)?"true":"false"; //a boolean indicating whther the current layout includes an tocframe element

var TLSMovieFrameTrue = (parent.movieframe)?"true":"false"; //a boolean indicating whther the current layout includes an movieframe element



// -------- FUNCTION DECLARATIONS



//sets window size to the specified width & height

function TLSwindowresize(TLSwidth,TLSheight) {

	if (TLSwidth == undefined) return;

	if (TLSwidth <= 1) return;

	if (TLSheight == undefined) return;

	if (TLSheight <= 1) return;

	

	if (window.screen.outerwidth < TLSwidth) {

		TLSwidth = window.screen.outerwidth;

	}

	if (window.screen.outerheight < TLSheight) {

		TLSheighth = window.screen.outerheight;

	}

	self.resizeTo(TLSwidth,TLSheight);

}



// gets the movies current time and duration and returns it in seconds

//	

function TLSGetMovieTime() {

	//TLSdebug('TLSgetMovieTime');

	TLSMovieTimeScale = parent.movieframe.document.movie.GetTimeScale();

	movieTime = parent.movieframe.document.movie.GetTime();

	var TLSMovieDuration = parent.movieframe.document.movie.GetDuration();

	var TLSTimeInSeconds = Math.floor(movieTime / TLSMovieTimeScale);

	//TLSdebug('TLSgetMovieTime(TLSTimeInSeconds=' + TLSTimeInSeconds + ')');

	return TLSTimeInSeconds;

}



function TLSGetTLSMovieDuration() {

	//TLSdebug('TLSgetTLSMovieDuration');

	TLSMovieTimeScale = parent.movieframe.document.movie.GetTimeScale();

	TLSMovieDuration = parent.movieframe.document.movie.GetDuration();

	var TLSDurationInSeconds = TLSMovieDuration / TLSMovieTimeScale;

	//TLSdebug('TLSgetTLSMovieDuration(TLSDurationInSeconds=' + TLSDurationInSeconds + ')');

	return TLSDurationInSeconds;

}

// this function sets the movie to the time specified in seconds

//

function TLSSetMovieTime(TLSMovieNo,TLSTimeInSeconds) {

	//TLSdebug('TLSSetMovieTime(movieNo=' + movieNo + ' TLSTimeInSeconds=' + TLSTimeInSeconds + ')');

	var TLSMovieTime

	switch (TLSMovieNo) {

	case 1:

		TLSMovieTimeScale = parent.movieframe.document.movie.GetTimeScale();

		TLSMovieTime = TLSTimeInSeconds * TLSMovieTimeScale;

		parent.movieframe.document.movie.SetTime(TLSMovieTime);

		break;

	case 2:

		TLSMovieTimeScale = parent.document.movie2.GetTimeScale();

		TLSMovieTime = TLSTimeInSeconds * TLSMovieTimeScale;

		parent.document.movie2.SetTime(TLSMovieTime);

		break;

	default:

		break;

	}	

}



// this function is called when the user clicks on a link in the Table of Contents file, toc.html

//

function TLSSyncFromTOC (TLSTimeInSeconds) { 

	//TLSdebug('TLSSyncFromTOC(' + TLSTimeInSeconds + ')');

	TLSSyncFromMovie = false;

	TLSSynchronise(TLSTimeInSeconds);

	TLSSyncFromMovie = true;



}



// this function is called when the user clicks on a link in the Transcript file, transcript.html

//

function TLSSyncFromTranscript (TLSTimeInSeconds) { 

	//TLSdebug('TLSSyncFromTranscript(' + TLSTimeInSeconds + ')');

	

	TLSSyncFromMovie = false;

	TLSSynchronise(TLSTimeInSeconds);

	TLSSyncFromMovie = true;

}



// this function is called to synchronise all media when the user clicks on a hyperlink 

// in the transcript or table of contents

//

function TLSSynchronise(TLSTimeInSeconds) {

	//TLSdebug("TLSSynchronise(" + TLSTimeInSeconds + ' TLSSyncFromMovie=' + TLSSyncFromMovie + ")");

	

	var TLSImageURL, TLSTheImage, TLSCaptionURL, TLSMovieRate, TLSMovieTwoTime;

		

	//set the movie to the required time but only if we are not sync'ing from the movie

	if (!TLSSyncFromMovie) {

		TLSSetMovieTime(1,TLSTimeInSeconds);

	}

	

	//switch images if imageframe is defined

	if (TLSImageFrameTrue == "true") {

		//set up sync'd image if there is one

		switch(TLSTimeInSeconds) {

		case undefined:

			break;

		case "" :

			//setup the image to the required image, get image url from first timertrack frame object

			if (parent.timertrack.document.getElementById("imageurl0")) {

				TLSImageURL = top.timertrack.document.getElementsByName("imageurl0")[0].value;						

			}

			else {

				TLSImageURL = "";

			}	



		default :

			//setup the image to the required image, get image url from timertrack frame object

			if (parent.timertrack.document.getElementById("imageurl" + TLSTimeInSeconds)) {

				TLSImageURL = parent.timertrack.document.getElementsByName("imageurl" + TLSTimeInSeconds)[0].value;

			}

			else {

				TLSImageURL = "";

			}	

		}



		//now switch the image to either a specified or random image

		switch (TLSImageURL) {

		case undefined:

			break;

		case "Random":

			TLSImageURL=TLSGetRandomImage();

			break;

		case "random" :

			TLSImageURL=TLSGetRandomImage();

			break;

		}

		//if there appears to be something wrong with TLSImageURL, then do nothing. Else switch the image

		switch (TLSImageURL) {

		case undefined:

			break;

		case "":

			//TLSdebug("TLSSynchronise TLSTimeInSeconds=" + TLSTimeInSeconds + " TLSImageURL="+ " case=Nil");

			break;

		case "Random":

			//TLSdebug("TLSSynchronise TLSTimeInSeconds=" + TLSTimeInSeconds + " TLSImageURL="+ " case=Random");

			break;

		case "random":

			//TLSdebug("TLSSynchronise TLSTimeInSeconds=" + TLSTimeInSeconds + " TLSImageURL="+ " case=random");

			break;

		case "undefined":

			//TLSdebug("TLSSynchronise TLSTimeInSeconds=" + TLSTimeInSeconds + " TLSImageURL="+ " case=undefined");

			break;

		default:

			//TLSdebug("TLSSynchronise TLSTimeInSeconds=" + TLSTimeInSeconds + " TLSImageURL=" + TLSImageURL + " case=default");

			if (parent.imageframe.image.document.getElementById('theimage')) {

				// switch images if 'TLSTheImage' object defined

				TLSTheImage = parent.imageframe.image.document.getElementById('theimage');

				TLSTheImage.src=TLSImageURL;

			}

			

			if (parent.imageframe.caption) {

				//if caption object exists, setvup required caption

				// replace image suffix by 'html' suffix

				TLSCaptionURL = TLSImageURL.substring(0,TLSImageURL.length - 3) + "html";

				

				// substitute 'Images' by 'Captions' in the URL

				TLSCaptionURL = TLSCaptionURL.split("Images/Images")[0] + "Images/Captions" + TLSCaptionURL.split("Images/Images")[1];

			

				//switch caption to correct url

				//TLSdebug('TLSSynchronise TLSCaptionURL=' + TLSCaptionURL);

				parent.imageframe.caption.location = TLSCaptionURL;

			}

			break;

		}

	}

	

		

	if (TLSTranscriptFrameTrue == "true") {

		//scroll transcript to correct anchor

		parent.transcriptframe.location = "../Assets/transcript.html#" + TLSTimeInSeconds;

	}

	

	if (TLSTocFrameTrue == "true") {

		//scroll toc to correct anchor

		parent.tocframe.location = "../Assets/toc.html#" + TLSTimeInSeconds;

	}

	

	if (TLSMovieFrameTrue == "true") {

		// if the movie is not playing, start it playing now so the user does not have to click the play button

		TLSMovieRate = parent.movieframe.document.movie.GetRate();

		if (TLSMovieRate == 0) {

			TLSPlayMovie();

			//parent.movieframe.document.movie.Play();

			//TLSSetTimer();

		}

	}

	

	//set TLSSyncFromMovie to true to stop movie stuttering at next sync time

	TLSSyncFromMovie = true;

	//TLSdebug('TLSSynchronise TLSSyncFromMovie=' + TLSSyncFromMovie);

	

	

	if (TLSMovie2True == "true" && parent.timertrack.document.getElementsByName("imageurl" + TLSTimeInSeconds)) {

	// there is a second movie and an TLSImageURLnn tag, set movie2 to correct position

		TLSMovieTwoTime=parent.timertrack.document.getElementsByName("imageurl" + TLSTimeInSeconds)[0].alt;	

		switch (TLSMovieTwoTime) {

		case undefined:

			break;

		default:

			TLSSetMovieTime(2,TLSMovieTwoTime);

			break;

		}

	}	

}



//

// this function starts the movie playing. Called from the Play Movie button in movie.html

function TLSPlayMovie() {

	//TLSdebug('TLSPlayMovie');

	TLSSetTimer();

	parent.movieframe.document.movie.Play();	

	TLSSyncFromMovie = true;



}



// 

//this function sets the master timer, frequency is 1 second

function TLSSetTimer() {

	TLSMovieTimer=parent.movieframe.setTimeout("TLSCheckTimer()",1000);

	//TLSdebug('TLSSetTimer(TLSMovieTimer=' + TLSMovieTimer + ')');

}



//

// this function is actioned by the timer when the time period is up

function TLSCheckTimer() {

	//check to see if we have an event specified for the current movie time

	var TLSTimeInSeconds = TLSGetMovieTime();

	var TLSEvent = top.timertrack.document.getElementById("imageurl" + TLSTimeInSeconds);

	//TLSdebug('TLSCheckTimer(TLSEvent=' + TLSEvent + ' TLSTimeInSeconds=' + TLSTimeInSeconds + ' TLSSyncFromMovie=' + TLSSyncFromMovie + ')');

	if (TLSSyncFromMovie) {

		if (TLSEvent != null) {

			TLSSynchronise(TLSTimeInSeconds);

		}

	}	

	

	//reset the timer

	TLSSetTimer();	

}



// 

//this function sets the load timer, frequency is 5 second

function TLSSetLoadTimer(TLSTimeInSeconds) {

	//TLSdebug('TLSSetLoadTimer(' + TLSTimeInSeconds + ')');

	

// commented out for now

//	loadTimer=parent.movieframe.setTimeout("TLSCheckLoadTimer(" + TLSTimeInSeconds + ")",5000);

}



//

// this function is actioned by the load timer when the time period is up. The parameter is the time to be sync'd to

function TLSCheckLoadTimer(TLSTimeInSeconds) {

	//TLSdebug('TLSCheckLoadTimer(' + TLSTimeInSeconds + ')');

	

	var pluginStatus;

	

	// indicate that we are not sync'ing from the movie

	TLSSyncFromMovie = false;

	

	//check to see the status of the plugin

	pluginStatus = top.movieframe.document.movie.GetPluginStatus();

	switch(pluginStatus) {

		case undefined:

			break;

		case "Waiting":

			//reset the timer

			TLSSetLoadTimer(TLSTimeInSeconds);	

		case "Loading:":

			//reset the timer

			TLSSetLoadTimer(TLSTimeInSeconds);	

		case "Playable":

			TLSSynchronise(TLSTimeInSeconds);

			break;

		case "Complete":

			TLSSynchronise(TLSTimeInSeconds);

			break;

		default:

			//error condition

			alert('There has been an error in the Testimony Browser. Please send an email to testimony@turtlelane.com.au quoting error number TLS02 and providing your details and the following message: ' + pluginStatus);

			break;

	}		

}





//

// this function stops the movie and also stops the master timer

function TLSStopMovie() {

	//TLSdebug('TLSStopMovie');

	

	parent.movieframe.clearTimeout(TLSMovieTimer);

	parent.movieframe.document.movie.Stop();

}



//

// this function returns the URL of a random image from the timertrack.html file's RandomImages container.

function TLSGetRandomImage() {

	//TLSdebug('TLSGetRandomImage');

	

	var randomTLSImageURL, randomImages;

	

	randomImages = top.timertrack.document.testimonyevents.randomimageurls.value.split("\n");

	

	switch (randomImages.length) {

		case undefined:

			return "undefined";

			break;

		case "0":

		//	no images defined so return false

			//TLSdebug('TLSGetRandomImage return=undefined');

			return "undefined";

			break;

		case "1":

			//TLSdebug('TLSGetRandomImage return=1');

			return randomImage[0];

			break;

		default:

			randomTLSImageURL= (randomImages[Math.round((Math.random() * 1000) % randomImages.length)]);

			//TLSdebug('TLSGetRandomImage return=' + randomTLSImageURL);

			return randomTLSImageURL;

			break;

	}

}



//

// this function syncs the browser to a specified image. Sent by the user clicking an image on the image gallery layout

// imageName is determined by the anchor in the html document and represents the cell of the thumbnail table the user clicked on, 

// eg, image01 for row 0, column1.

function TLSSyncToImage(imageName) {

	//TLSdebug('TLSSyncToImage(' + imageName + ')');



	var thumbnailURL, i, containerName, TLSImageURL, TLSImageURLArray, TLSImageURLArrayIndex, thumbnailURLArray, thumbnailURLArrayIndex;	

	var imageTime = "" //this will hold the time in seconds the movie is to be sync'd to

	var urlMatch = false; //this signals whether a matching url has been found in the timertrack frame

	

	//get the image url from the container

	thumbnailURL=eval("top.imagesframe.document." + imageName + ".src;");

				

	//now find the TLSImageURL in the timertrack fields

	for (i=0;i < top.timertrack.document.testimonyevents.elements.length;i++) {			

		

		containerName = top.timertrack.document.testimonyevents.elements[i].name;			

		

		// if container's name does not start with 'TLSImageURL', ignore and go to next container

		if (containerName.substring(0,8) != "TLSImageURL") {

			continue;

		}

		

		// get url string from inside the container

		TLSImageURL = top.timertrack.document.testimonyevents.elements[i].value;	



		//if this is a random image URL, go to next container

		if (TLSImageURL == "random") {

			continue;

		}

		if (TLSImageURL == "Random") {

			continue;

		}

		

		//verify thumbnailURL and TLSImageURL point to the same location. Remember that TLSImageURL might be a relative URL, eg, ../Assets/Images/animage.jpg whilst thumbnailURL is a complete URL, eg, http://.....

		// so we walk backwards along both arrays until either a mismatch of we reach the beginning

		TLSImageURLArray = TLSImageURL.split("/");

		thumbnailURLArray = thumbnailURL.split("/");

		thumbnailURLArrayIndex = thumbnailURLArray.length - 1;

				

		for (TLSImageURLArrayIndex = TLSImageURLArray.length - 1;TLSImageURLArrayIndex > -1;TLSImageURLArrayIndex-1) {



			//alert('imageUTRLArray[' + TLSImageURLArrayIndex + ']=' + TLSImageURLArray[TLSImageURLArrayIndex] + '\n' + 'thumbnailURLArray[' + thumbnailURLArrayIndex + ']=' + thumbnailURLArray[thumbnailURLArrayIndex]);



			switch(TLSImageURLArray[TLSImageURLArrayIndex]) {							

			case undefined:

				break;

			case thumbnailURLArray[thumbnailURLArrayIndex] : //we have a match, so check previous cell

				urlMatch = true;

				TLSImageURLArrayIndex = TLSImageURLArrayIndex - 1;

				thumbnailURLArrayIndex= thumbnailURLArrayIndex - 1;

				break;

			case ".." : //processed to where the thumbnailURL is relative, ie. value is '..', so exit the loop

				TLSImageURLArrayIndex = -1; 

				break;

			default : //mismatch, so stop further processing

				urlMatch = false;

				TLSImageURLArrayIndex = -1;

				break;

			}	

			if (urlMatch == true) {

				continue;

			}

			else {

				break;

			}

		}

				

		if (urlMatch == true) {

			//now extract the time in seconds, field is named 'image' + TLSTimeInSeconds, eg, image10 for ten seconds into the movie

			imageTime = containerName.split("url")[1];



			//stop the loop as we have a match and we have the required time

			break;



		}

	

		// mismatch with this container so continue to check next container				

				

	}

	

	//sync to required time

		switch (imageTime) {

		case "":

			alert('There has been an error in the Testimony Browser. Please send an email to testimony@turtlelane.com.au quoting error number TLS01 and providing your details.');	

			return;

		default:

		//switch window to browser url

			TLSSwitchTo("narrative",imageTime);

		}



}



//

// this function switches the current window to a different part of the browser environment

function TLSSwitchTo(targetName, TLSTimeInSeconds) {

	//TLSdebug("TLSSwitchTo(" + targetName + "," + TLSTimeInSeconds + ")");

	

	var syncToTime, urlParts;

	

	var switchToTarget = targetName;

	if (TLSTimeInSeconds >= 0) {

		syncToTime = "?syncTo=" + TLSTimeInSeconds;

	}

	else {

	syncToTime="";

	}

	switch(switchToTarget) {

		case undefined:

			break;

		case "imagegallery" :

			urlParts = top.location.href.split("/");

			urlParts[urlParts.length-1] = "imagegallery.html";

			top.location.href=urlParts.join("/");

			break;

		case "narrative" :

			urlParts = top.location.href.split("/");

			urlParts[urlParts.length-1] = "testimonybrowser.html" + syncToTime;

			top.location.href=urlParts.join("/");

			break;

	}

}



//

// this function loads the next 20 thumbnails from the

// timertrack.html file. startingIndex is the number of the image to start from.

function TLSLoadThumbnails(startingIndex) {

	//TLSdebug('TLSLoadThumbnails(' + startingIndex + ')');

	

	var thumbnailURL, i;

	var thumbnailIndex = 0; //this is the pointer to the thumbnail container on the page, values 0 to 19

	var containerName = "";

	

	

	//process timertrack frame containers to extract image url's

	for  (i=startingIndex;i <= startingIndex+19;i++){

		//TLSdebug('TLSLoadThumbnails i=' + i);

	

		// if processed 20 thumbnails, exit loop

		if (i > top.timertrack.document.testimonyevents.elements.length - 1) {

			break;

		}

		

		containerName = top.timertrack.document.testimonyevents.elements[i].name;		

		// if container's name does not start with 'TLSImageURL, ignore and go to next container

		if (containerName.substring(0,8) != "TLSImageURL") {

			continue;

		}

		

		thumbnailURL = top.timertrack.document.testimonyevents.elements[i].value;

		// if url is 'random' go to next container

		if (thumbnailURL == "random") {

			continue;

		}

		// if url is 'Random' go to next container

		if (thumbnailURL == "Random") {

			continue;

		}

		

		//process timertrack container url		



		switch(thumbnailIndex) {

		case undefined:

			break;

		case 0:

			top.imagesframe.document.image00.src = thumbnailURL;

			break;

		case 1:

			top.imagesframe.document.image01.src = thumbnailURL;

			break;

		case 2:

			top.imagesframe.document.image02.src = thumbnailURL;

			break;

		case 3:

			top.imagesframe.document.image03.src = thumbnailURL;

			break;

		case 4:

			top.imagesframe.document.image04.src = thumbnailURL;

			break;

		case 5:

			top.imagesframe.document.image10.src = thumbnailURL;

			break;

		case 6:

			top.imagesframe.document.image11.src = thumbnailURL;

			break;

		case 7:

			top.imagesframe.document.image12.src = thumbnailURL;

			break;

		case 8:

			top.imagesframe.document.image13.src = thumbnailURL;

			break;

		case 9:

			top.imagesframe.document.image14.src = thumbnailURL;

			break;

		case 10:

			top.imagesframe.document.image20.src = thumbnailURL;

			break;

		case 11:

			top.imagesframe.document.image21.src = thumbnailURL;

			break;

		case 12:

			top.imagesframe.document.image22.src = thumbnailURL;

			break;

		case 13:

			top.imagesframe.document.image23.src = thumbnailURL;

			break;

		case 14:

			top.imagesframe.document.image24.src = thumbnailURL;

			break;

		case 15:

			top.imagesframe.document.image30.src = thumbnailURL;

			break;

		case 16:

			top.imagesframe.document.image31.src = thumbnailURL;

			break;

		case 17:

			top.imagesframe.document.image32.src = thumbnailURL;

			break;

		case 18:

			top.imagesframe.document.image33.src = thumbnailURL;

			break;

		case 19:

			top.imagesframe.document.image34.src = thumbnailURL;

			break;		

		}

		thumbnailIndex++;

	}

}



//

// this function is called by the onLoad event of the movie.html file

function TLSOnLoadMovie() {

	//TLSdebug('TLSOnLoadMovie(' + window.location.search + ')');

	

	var syncTLSTimeInSeconds;

	

	//check if any synctime supplied through the query part of the URL, ie, ?syncTo=nn	

	switch(window.location.search) {

		case undefined:

		//no sync time specified so just carry on loading as normal

			TLSStopMovie(); //stop the movie from auto playing

			TLSCheckLoadTimer(0);

			break;		

		case "" :

		//no sync time specified so just carry on loading as normal

			TLSStopMovie(); //stop the movie from auto playing

			TLSCheckLoadTimer(0);

			break;

		default :

			// sync time specified, so extract time and sync movie, etc

			syncTLSTimeInSeconds = location.search.split("=")[1];

			TLSCheckLoadTimer(syncTLSTimeInSeconds);

			break;

	}

}



// this debugger is based on the JavaScript Debug Utility described in http://www.isocra.com/articles/jsdebug.php



// Show the debug window

function TLSshowDebug() {

  //alert('TLSShowDebug'); 

  window.top.debugWindow =

      window.open("",

                  "Debug",

                  "left=0,top=0,width=300,height=700,scrollbars=yes,"

                  +"status=yes,resizable=yes");

  window.top.debugWindow.opener = self;

  // open the document for writing

  window.top.debugWindow.name = "TLS Debug";

  window.top.debugWindow.document.open();

  window.top.debugWindow.document.write(

      "<HTML><HEAD><TITLE>Debug Window</TITLE></HEAD><BODY><PRE>\n");

}



// If the debug window exists, then write to it

function TLSdebug(text) {

 //alert('TLSdebug'); 

  if (! window.top.debugWindow) {

  	TLSshowDebug();

  }

  //if (window.top.debugWindow && ! window.top.debugWindow.closed) {

   if (! window.top.debugWindow.closed) {

   window.top.debugWindow.document.write(text+"\n");

  }

}



// If the debug window exists, then close it

function TLShideDebug() {

  if (window.top.debugWindow && ! window.top.debugWindow.closed) {

    window.top.debugWindow.close();

    window.top.debugWindow = null;

  }

}



function TLStoggleDebug() {

  if (document.getElementById("debugOn").checked) {

    TLSshowDebug();

    debug("Check box checked, switched on debug");

    document.getElementById("checkboxLabel").innerHTML = "The debug window is <b>on</b>";

  } else {

    debug("Check box unchecked, switching off debug");

    TLShideDebug();

    document.getElementById("checkboxLabel").innerHTML = "The debug window is <b>off</b>";

  }

}

