
// GLOBAL VARIABLES
// ************************
var sectionListArray = new Array(); // array of arrays of arrays - each holding an array of imageListArray
var sectionTitleArray =new Array(); // array holding section titles
var sectionFolderArray =new Array(); // array holding section folder names
var imageListArray = new Array(); // array of arrays - each imageListArray holding set of imageElement array: filename, thumb text and image text

var imageNumRef; // html element id = imageNumID to display current image number (rel 1)
var imageTotalRef; // html element id = imageTotalID to display total images

var imageContainer = document.getElementById("imageID"); // reference to the container for the image to be displayed

var currentSectionNum; // this is rel 0
var sectionCount; // total sections to be displayed

var currentImageNum; // this is rel 0
var imageCount; // total images to be displayed

var thisUrl; // window.location.href

// the following are the names of the sub-folders within each section image folder
var largeSize = "large";
var mediumSize = "medium";
var smallSize = "small";

// the following are controls for the section and thumbnail iframes
var thumbColumns = 2; // the number of columns in the image thumbnails
var thumbPadding = 5; // the cellpadding in thumbnails
var sectionColumns = 1; // the number of columns in the image thumbnails
var sectionPadding = 5; // the cellpadding in thumbnails

// the following are used by getImageList()
var sectionDelim = "%"; // this deliniates each section
var sectionTitleDelim = "@"; // this deliniates the end of the section title followed by the end of the section folder
var imageDelim = "#"; // this deliniates each image within section
var elementDelim = "::"; // this deliniates each image element within each image

// the following produces a slideshow of all images
var slideSection;
var slideImage;
var slideTime = 6*1000; // slideshow timer in seconds
var slideshow; // boolean to turn on and off

// ************************

function setSlideshowOnOff () {
	var checkbox = document.getElementById("slideshowID"); // checkbox to set slideshow on or off
	if (checkbox.checked == true) {
		slideshow = true;
		startSlideshow();
	}
	else {
		slideshow = false;
		displayImage(currentSectionNum, currentImageNum);
	}
}

function startSlideshow () {
	// start the slideshow at the current image
	slideSection = currentSectionNum;
	slideImage = currentImageNum;
	doTimerImage();
}

function doTimerImage () {
	
	if (slideshow == false) { // turn off slideshow and return to last image user was seeing
		return; // no more show
	}
	
	// display the current section - image for the slideshow
	displayImage(slideSection, slideImage);
	
	// increment to the next image of section and image
	slideImage++;
	if (slideImage >= sectionListArray[slideSection].length) {  // finished section -- move to next section and image 0, or reset to section 0
		slideSection++;
		slideImage = 0;
		if (slideSection >= sectionListArray.length) { // finished all sections -- reset to section 0 and image 0
			slideSection = 0;
		}
	}
	
	// repeat function with timeout
	setTimeout("doTimerImage()", slideTime);
}

/*
imageListArray holds the hidden input provided for the image filename, thumbnail text, and image text
each group is separated by a imageDelim ("#")
within each group separated by elementDelim ("::") are the filename, thumbnail text, and image text
thus imageListArray[1][2] is the 2nd image, image text
*/
function getImageList () {
	
	// the following is the contents of outline.html placed in a hidden iframe via src="outline.html"
	var frame = window.parent.document.getElementById("outline");
	var frameDoc = frame.contentDocument || frame.contentWindow.document;
	
	// get the user's list of sections and images
	var list = frameDoc.body.innerHTML; 
	
	var imageArray = new Array(); // used locally to contain each image description
	var sectionArray = new Array(); // used locally to contain each section description
	
	// obtain and save the location (directory) of this request
	thisUrl = window.location.href;
	var last = thisUrl.lastIndexOf("/");
	thisUrl = thisUrl.substring(0, last + 1);
	
	// get the references needed to update relevant image numbers for user
	imageNumRef = document.getElementById("imageNumID");
	imageTotalRef = document.getElementById("imageTotalID");
	
	// test if there is a trailing sectionDelim - within 6 of the last characters in list- if so eliminate
	if (list.lastIndexOf(sectionDelim) > list.length - 6) list = list.substring(0, list.lastIndexOf(sectionDelim));
	
	sectionArray = list.split(sectionDelim);  // get array of all sections
	sectionCount = sectionArray.length;
	
	var sectionElements;
	var imageList;
	for (j = 0; j < sectionCount; j++) {
		sectionArray[j] = sectionArray[j].trim();
		sectionElements = new Array();
		sectionElements = sectionArray[j].split(sectionTitleDelim); // separates section text [0] from image list [1]
		sectionTitleArray[j] = sectionElements[0]; // this is the section title
		sectionFolderArray[j] = sectionElements[1].trim(); // this is the folder name containing the images for this section
		imageList = sectionElements[2]; // this is the list of images in this section
		
		// test if there is a trailing imageDelim - within 6 of the last character- if so eliminate
		if (imageList.lastIndexOf(imageDelim) > imageList.length - 6) imageList = imageList.substring(0, imageList.lastIndexOf(imageDelim));

		imageArray = imageList.split(imageDelim);; // array of images within section
		imageCount = imageArray.length; // this is the number of images -- global
		
		// split each imageArray to get the filename, thumbnail text, and image text
		var imageElements;
		imageListArray = new Array(); // initialize new image list
		for (i = 0; i < imageCount; i++) {
			imageArray[i] = imageArray[i].trim();

			imageElements = new Array();
			imageElements = imageArray[i].split(elementDelim); // this is array of all components of each image
	
			if (imageElements[0] == undefined) {
				alert("Improper filename");
				break;
			}
			if (imageElements[1] == undefined || imageElements[1].length < 2) imageElements[1] = imageElements[0]; // for thumbnail use image filename
			if (imageElements[2] == undefined || imageElements[2].length < 2) imageElements[2] = ""; // for image desc use nothing
			
			// trim each element
			imageElements[0] = imageElements[0].trim(); // take out any leading and ending whitespace from filename
			imageElements[1] = imageElements[1].trim();
			imageElements[2] = imageElements[2].trim();
			
			imageListArray[i] = imageElements; // place filename, thumb text, image text array in imageListArray
		}
		sectionListArray[j] = imageListArray; // place imageListArray into sectionListArray
	}
	
	currentSectionNum = 0;
	
	//printSectionArray(); // print for debug
	
	// load the sectionFrame
	loadSectionFrame();
	
	// setup other globals
	imageListArray = sectionListArray[0];
	imageCount = imageListArray.length;
	
	imageTotalRef.value = imageCount; // place total images into page at imageTotalID
	
	// load the first thumbFrame
	loadThumbFrame(0);
	
	// display the first image in the first section
	imageContainer = document.getElementById("imageID"); // reference to the container for the image to be displayed
	displayImage(0, 0);
	imageNumRef.value = 1;
	currentImageNum = 0;
}

// use this function for debugging the array setups
function printSectionArray () {
	var msg = "";
	for (m = 0; m < sectionCount; m++) {
		msg += sectionTitleArray[m] + " @ " + sectionFolderArray[m] + "\n";
		for (n = 0; n < sectionListArray[m].length; n++) {
			msg += "\t" + sectionListArray[m][n][0];
			msg += " --- " + sectionListArray[m][n][1] + "\n";
		}
	}
	alert (msg);
}

function changeSection (sectionNum) {
	// all we need to do is reload the imageListArray with the contents of the selected section
	// the changeImage, goPrior, and goNext should then work fine
	// but first since this operates in the section frame we must reload the required variables from parent
	sectionListArray = window.parent.sectionListArray;
	imageListArray = sectionListArray[sectionNum];
	imageCount = imageListArray.length;
	sectionTitleArray = window.parent.sectionTitleArray;
	sectionFolderArray = window.parent.sectionFolderArray;
	imageTotalRef = window.parent.imageTotalRef;
	imageTotalRef.value = imageCount; // place total images into page at imageTotalID
	imageNumRef = window.parent.imageNumRef;
	thisUrl = window.parent.thisUrl;
	
	// load the section
	loadThumbFrame(sectionNum);
	
	// reset currentImageNum to 0
	window.parent.currentImageNum = 0;
	// reset the currentSectionNum
	window,parent.currentSectionNum = sectionNum;
}

// this function executes in the thumbFrame -- not it's parent - thus use window.parent
// also why this function must set the image in the element's innerHTML and not use displayImage()
function changeImage (fileName) {

	// the following is because the js is executing in the thumbFrame - need to get these from parent
	var imageListArray = window.parent.imageListArray;
	var imageNumRef = window.parent.imageNumRef;
	var thisUrl = window.parent.thisUrl;
	var imageCount = window.parent.imageCount;
	var sectionTitleArray = window.parent.sectionTitleArray;
	var sectionFolderArray = window.parent.sectionFolderArray;
	var section = window.parent.currentSectionNum;
	
	var i;
	var found;
	var imageCount = imageListArray.length;
	
	for (i = 0; i < imageCount; i++) {
		found = fileName.indexOf(imageListArray[i][0]);
		if (found > -1) break;
	}
	
	if (i < imageListArray.length) {
		var imageContainer = window.parent.document.getElementById("imageID");
		// for some reason this does not work displayImage();
		var output = "";
		var sectionTitle = sectionTitleArray[section];
		var sectionFolder = sectionFolderArray[section];
		var title = imageListArray[i][1].replace(/'/g, "\\\'"); // escape any embedded single quotes
		
		output += sectionTitle + "<br />";
		output += '<a href="javascript:openWindow(' + "'" + sectionFolder + "/" + largeSize + "/" + imageListArray[i][0] + ".jpg', " + "'" + title + "');" + '">'
		output += '<img src="' + sectionFolder + "/" + mediumSize + "/" + imageListArray[i][0] + ".jpg" + '">';
		output += '</a>';
		output += "<br />" + imageListArray[i][2]; // image description
		imageContainer.innerHTML = output;
		var currentImageNum = i;
		window.parent.currentImageNum = currentImageNum;
		imageNumRef.value = i + 1;
	}
	else alert(fileName + " not found -- call John");
		
}

function displayImage (section, image) {
	// displays the selected image (i) in the html element loc
	var output = "";
	var sectionTitle = sectionTitleArray[section];
	var sectionFolder = sectionFolderArray[section];
	var title = sectionListArray[section][image][1].replace(/'/g, "\\\'"); // escape any embedded single quotes in thumbnail description
	
	output += sectionTitle + "<br />";
	output += '<a href="javascript:openWindow(' + "'" + sectionFolder + "/" + largeSize + "/" + sectionListArray[section][image][0] + ".jpg', " + "'" + title + "');" + '">'
	output += '<img src="' + sectionFolder + "/" + mediumSize + "/" + sectionListArray[section][image][0] + ".jpg" + '">';
	output += '</a>';
	output += "<br />" + sectionListArray[section][image][2]; // the image description
	imageContainer.innerHTML = output;
	
}
	

function goCurrent () {
	// this function returns the user to the last image seen - e.g. they were looking at bio or other things
	var doImageNum;
	if (currentImageNum <= 0) doImageNum = 0;
	else doImageNum = currentImageNum;
	displayImage(currentSectionNum, doImageNum);
}

function goPrior () {
	var doImageNum;
	if (currentImageNum <= 0) doImageNum = 0;
	else doImageNum = currentImageNum - 1;
	displayImage(currentSectionNum, doImageNum);
	imageNumRef.value = doImageNum + 1;
	currentImageNum = doImageNum;
}

function goNext () {
	var doImageNum;
	if (currentImageNum >= imageListArray.length - 1) doImageNum = imageListArray.length - 1;
	else doImageNum = currentImageNum + 1;
	displayImage(currentSectionNum, doImageNum);
	imageNumRef.value = doImageNum + 1;
	currentImageNum = doImageNum;
}

var frameHeader = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
	'<html xmlns="http://www.w3.org/1999/xhtml">' +
	'<head>' +
	'<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
	'<link href="styles.css" rel="stylesheet" type="text/css">' +
	'<script type="text/javascript" src="script.js"></script>' +
	'<title>Untitled Document</title>' +
	'</head><body class="background" >'
	;
var frameTrailer = "</body></html>";

function loadSectionFrame () {
	var frameContent = "";
	var sectionFolder;
	frameContent = '<table cellpadding="' + sectionPadding + '" class="photo_verySmallText" width="100%">'; // preamble
	for (i = 0; i < sectionCount; i++) {
		sectionFolder = sectionFolderArray[i];
		if (i % sectionColumns == 0) frameContent += '\n<tr valign="middle">'; // separate rows
		frameContent += '<td align="center">';
		frameContent += '<a class="photo_verySmallText" onclick="changeSection(' + i + ")" + '">';
		frameContent += '<img src="' + sectionFolder + "/" + smallSize + "/" + sectionListArray[i][0][0] + ".jpg" + '"><br>' + sectionTitleArray[i] + '</a>';
	}
	frameContent += '</table>'; // postamble
	
	// write frameContent to sections frame
	window.sections.document.write(frameHeader + frameContent + frameTrailer);
}

function loadThumbFrame (sectionNum) {
	var frameContent = "";
	var sectionFolder = sectionFolderArray[sectionNum];
	frameContent = '<table cellpadding="' + thumbPadding + '" class="photo_verySmallText" width="100%">'; // preamble
	for (i = 0; i < imageCount; i++) {
		if (i % thumbColumns == 0) frameContent += '\n<tr valign="middle">'; // separate rows
		frameContent += '<td align="center">';
		frameContent += '<a class="photo_verySmallText" onclick="changeImage(';
		frameContent += "'" + sectionFolder + "/" + mediumSize + "/" + sectionListArray[sectionNum][i][0] + ".jpg" + "'";
		frameContent += ')"><img src="' + sectionFolder + "/" + smallSize + "/" + sectionListArray[sectionNum][i][0] + ".jpg" + '"><br>' 
			+ sectionListArray[sectionNum][i][1] + '</a>';
	}
	frameContent += '</table>'; // postamble
	
	// change imageListArray to the current sectionNum
	window.parent.imageListArray = sectionListArray[sectionNum];
	
	// setup reference to iframe content
	var frame = window.parent.document.getElementById("thumbsID");
	var frameDoc = frame.contentDocument || frame.contentWindow.document;
	
	var iframeContent = frameDoc.body.innerHTML; // returns "" if not yet loaded
	
	if (iframeContent.length ==0) { // nothing loaded yet
		// write frameContent to thumbs frame
		// use parent so that call here from another frame (e.g. section) will work
		window.parent.thumbs.document.write(frameHeader + frameContent + frameTrailer);  
	}
	else { // we have content there so just replace innerHTML
		frameDoc.body.innerHTML = frameContent;
		
		// display the first image
		imageContainer = window.parent.document.getElementById("imageID");
		displayImage(sectionNum, 0);
	}
	
	imageNumRef.value = 1;
	currentImageNum = 0;
	
	// change the section title
	window.parent.document.getElementById("sectionNameID").innerHTML = sectionTitleArray[sectionNum];

}



// to use openWindow, for example:
// <a href="javascript:openWindow('images/Museum/gallery-entry-hall.jpg', 'Entry Hall', 'image');">
//
function openWindow (page, title, winName) {
    // page is the relative location of the image to be displayed.
    // title is the name of the window that is displayed in title bar.
    // winName cannot contain spaces -- it is used to provide a unique name to the window
    //      and will determine whether the window is reused if the next request has the same winName.
    // if winName is null then use title.

	widthIncr = 145; heightIncr = 165;

	// The following html will be written to the new window after opening.
	// The body onblur performs a self.close() -- thus click anywhere but the image unloads the widow

	var html = "<html><head> "
			+ '<script type="text/javascript" src="script.js"></script>'
			+ "<title> " + title + " </title> "
	        + "<script language=\"javascript\">"

			+ "function resizeWindow() { "
			+ "window.resizeTo(document.image.width+" + widthIncr + ", document.image.height+" + heightIncr + "); "
			+ "} \n"+ "</script> "

			+ "<link href=\"styles.css\" rel=\"stylesheet\" type=\"text/css\"></head> "
			+ "<body class=\"background\"  onload=\"javascript:resizeWindow();\" onblur=\"self.close();\"> "
			+ "<table id=\"outer\" align=\"center\"><tr align=\"center\" valign=\"middle\"><td align=\"center\" valign=\"middle\">"
			+ "<div align=\"center\">"
			+ "<h3>" + title + "</h3>"
			+ "<img border=2 name=\"image\" alt=\"" + title +"\" src=\"" + page +"\"> "
			+ "</div></table>"
			+ "<script language=\"JavaScript\" type=\"text/javascript\">"
			+ "resizeWindowById('outer');"
			+ "</script>"
			+ "</body></html>";


	// if winName is null - remove any spaces from title to create window name (no spaces allowed)
	if (winName == null) {
		winName = "";
		string = '' + title;
		splitstring = string.split(" ");
		for (i = 0; i < splitstring.length; i++) winName += splitstring[i];
	}

	// if winName is the same as another displayed photo the original window is re-used

	// open a new window with initially no content
    	var newWindow = window.open("", "window", "scrollbars=no,resizable=yes,width=100,height=100");
    	newWindow.document.open();

	// write the html created above to the window document and close document, set focus
	newWindow.document.write(html);
	newWindow.document.close();
	newWindow.focus();
}

function resizeWindowById (id) {
	var oH = getRefToDivMod( id ); if( !oH ) { return false; }
	var oW = oH.clip ? oH.clip.width : oH.offsetWidth;
	var oH = oH.clip ? oH.clip.height : oH.offsetHeight;
	if( !oH ) { return false; }
	var x = window; x.resizeTo( oW + 200, oH + 200 );
	var myW = 0, myH = 0, d = x.document.documentElement, b = x.document.body;
	if( x.innerWidth ) { myW = x.innerWidth; myH = x.innerHeight; }
	else if( d && d.clientWidth ) { myW = d.clientWidth; myH = d.clientHeight; }
	else if( b && b.clientWidth ) { myW = b.clientWidth; myH = b.clientHeight; }
	if( window.opera && !document.childNodes ) { myW += 16; }
	x.resizeTo( oW + ( ( oW + 200 ) - myW ), oH + ( (oH + 200 ) - myH ) );
	return;
}

function getRefToDivMod( divID, oDoc ) {
  if( !oDoc ) { oDoc = document; }
  if( document.layers ) {
    if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } else {
      for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {
        y = getRefToDivMod(divID,oDoc.layers[x].document); }
      return y; } }
  if( document.getElementById ) { return oDoc.getElementById(divID); }
  if( document.all ) { return oDoc.all[divID]; }
  return document[divID];
}

// flip the visibility of a element container (container), this could be a <td>, <tr>, <div>, etc
// the (cb) must be a checkbox that is either checked or unchecked 
// setting opposite = true will set visibility to hidden if checked -- if opposite missing or false then set visibility to visible when checked
// setting collapse will cause the container to "collapse" rather than set "hidden" -- it will also set display:none or display:("")
function setVisibility(cb, container, opposite, collapse) {
	var state = 0; // 1 visible, 0 hidden
	var toDisappear = "hidden";
	var doFullCollapse = false; // This is for e.g. IE that doesn't understand visibility:collapse
	// Determine whether to set either hidden or collapse
	if (collapse && collapse == "collapse") {
		// IE does not support visibility:collapse
		// Using "hidden" as opposed to "collapse" works with IE and Firefox -- this is because we also do display = "none" or ""
		toDisappear = "hidden"; 
		doFullCollapse = true;
	}
	if (document.getElementById)	{  //gecko(NN6) + IE 5+ -- modern browsers that follow standards
		var obj = document.getElementById(container); // this is the container element that will have visiblity changed
		var checkbox = document.getElementsByName(cb); // array of checkboxes returned
		if (checkbox[0].checked == true) state = 1; // we really only want the first one (s/b only one)
		
		if (opposite) {
			// set the obj visibility to the opposite of the checkbox (checked means make obj disappear)
			obj.style.visibility = state ? toDisappear : "visible";
			// using "" so both IE and FF go back to their normal -- FF does not recognize "block" properly
			if (doFullCollapse) {
				obj.style.display = state ? "none" : "";
				//if (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion >= "4.0") ;
				//else obj.style.display = state ? "none" : "";
			}
		}
		else {
			// set the obj visibility to the checkbox (checked means make obj visible)
			obj.style.visibility = state ? "visible" : toDisappear;
			if (doFullCollapse) {
				obj.style.display = state ? "" : "none";
				//if (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion >= "4.0") ;
				//else obj.style.display = state ? "" : "none";
			}
		}
	}
}



// trim functions and prototypes
// trim all whitespace
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }

// trim spaces
function ltrim(s)
{
	var i = 0;
	while(i < s.length && s[i] == ' ') i++; 
	return s.substring(i, s.length);
}

function rtrim(s)
{
	var i = s.length - 1;
	while(i > 0 && s[i] == ' ') i--;
	return s.substring(0, i + 1);
}


// loadImageArea is a function needed to overcome the inability of IE and Safari to respond to the option onclick event
// it is used to load an html file into the image area with id of imageID
// obtain the value from the option selected and perform the necessary logic here
function loadImageArea () {
	var theSelect = document.getElementById("selectID"); // reference to the select with options
	var index = theSelect.value;
	/* here are the values translated to function calls -CHECK THESE WITH INDEX.HTML
					<option value="0">Select for additional information</option>  
                    <option value="1" onclick="setHTML('CurrentEvents.html', 550, 600);">Upcoming Events</option>  
                    <option value="2" onclick="setHTML('bio.html', 550, 600);">Biography</option>  
                    <option value="3" onclick="setHTML('TimInGallery.html', 550, 600);">Tim Sutherland photo</option>  
                    <option value="4" onclick="setHTML('Giclee.html', 550, 600);">Gicl&eacute;e printing services</option>  
                    <option value="5" onclick="setHTML('Links.html', 550, 600);">Links</option>  
                    <option value="-1" onclick="goCurrent();">Return to image</option>  
	*/
	if (index == 0); // do nothing
	else if (index == 1) setHTML('CurrentEvents.html', 550, 600);
	else if (index == 2) setHTML('bio.html', 550, 600); 
	else if (index == 3) setHTML('TimInGallery.html', 550, 600);
	else if (index == 4) setHTML('Giclee.html', 550, 600);
	else if (index == 5) setHTML('Links.html', 550, 600);
	else if (index == -1) goCurrent();
}


// write the html file provided to the container with id of imageID
function setHTML (file, height, width) {
	 var container = document.getElementById("imageID");
	 output = '<object width="' + width + '" height="' + height + '" class="photo_verySmallText" type="text/html" data="' + file + '"></object>';
	 container.innerHTML = output;
}





