//  *****************SUBROUTINES SECTION***********************
//
// Implement a user's changed slideshow delay, this is called when the value in the
// select box is changed
function changedelay()
{
	timeout = document.delayform.delay.options[document.delayform.delay.selectedIndex].value
}

// This function simply pops up the instructions window
function instruct()
{
	instructions=window.open('../instructions.html','instructions','width=600,height=450,location=no,menubar=no,scrollbars=yes,resizable=yes,status=no,toolbar=no')
}

// This routine traps any kestrokes, and tests for whether the navigation keys have been used.
// The left, right and up arrows go back, forwards and up.
function checkKeycode(e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	// alert("keycode: " + keycode);
	if (keycode == "37") {
		nextPrevious(-1)
	}
	else if (keycode == "38") {
		window.location = indexpage
	}
	else if ((keycode == "39") || (keycode == "32")) {
		nextPrevious(1)
	}
	else if (keycode == "80") {
		toggleSlideshow()
	}
}
document.onkeydown = checkKeycode


// Function to move to next/previous image, and pause the slideshow if it is running. 
// Called when the user manually clicks on NEXT or PREV.
// This assumes that the slide show should be paused if next/previous is clicked.
// Also used if a different image resolution is selected (direction = 0).
// If the slide show is paused, or is to be paused, then a + is added the url to signify this.
// If the slideshow is not running, a ~ is added to the url, so that the next page will not 
// show the timeout dropdown for the slideshow.
function nextPrevious(direction, newres)
{
	if (direction > 0)
	{
		if (nextUrl.indexOf("?") > 0)   
		{
			k = nextUrl.indexOf("?")
			selectedUrl = nextUrl.substring(0, k) + "?" + res + timeout
		}
		else
		{
			selectedUrl = nextUrl + "?" + res + timeout
		}
		pause = 1
	}
	if (direction < 0)
	{
		if (prevUrl.indexOf("?") > 0)   
		{
			k = prevUrl.indexOf("?")
			selectedUrl = prevUrl.substring(0, k) + "?" + res + timeout
		}
		else
		{
			selectedUrl = prevUrl + "?" + res + timeout
		}
		pause = 1
	}
	if (direction == 0)
	{
		if (thispage.indexOf("?") > 0)   
		{
			k = thispage.indexOf("?")
			selectedUrl = thispage.substring(0, k) + "?" + newres + timeout
		}
		else
		{
			selectedUrl = thispage + "?" + newres + timeout
		}
	}
	if (slideshow == 0)
	{
		selectedUrl += "~"
	}
	if ((slideshow == 1) && (pause == 1))
	{
		selectedUrl += "+"
	}
	window.location = selectedUrl
}

// Used to commence slide show when it hasn't been running, and no delay controls are present.
function commenceSlideshow()
{
	//  This simulates a paused slide show, so that the next routine call will start it
	pause = 1
	toggleSlideshow()
}

// Function start/stop the slideshow
function toggleSlideshow()
{
	if (pause)
	{
		// If the slideshow is paused, start it and change the displayed slideshow controls
		pause = 0;
		document.getElementById('both_startt').style.display = 'none';
		document.getElementById('both_stopp').style.display = 'block';
		setTimeout("next()", 1000)
	}
	else
	{
		// Otherwise pause the slideshow and change the displayed slideshow controls
		pause = 1;
		document.getElementById('both_stopp').style.display = 'none';
		document.getElementById('both_startt').style.display = 'block';
	}
}

// Function to go to the next page, used ONLY by the slideshow.  Don't know why it needs to be
// in a separate function, but that's the way it came to me.
function next()
{
	// Only move to next page if slideshow is running
	if (nextUrl.indexOf("?") > 0)   
	{
	nextUrl = nextUrl.substring(0, nextUrl.indexOf("?")) + "?" + res + timeout
	}
	else
	{
	nextUrl += "?" + res + timeout
	}
	if (!pause) window.location = nextUrl;
}

// Function to reload the page with a new size if one of the resize links is clicked on
function resize(newsize)
{
	resizeurl = thispage + "?" + newsize + timeout
	if (slideshow == 0)
	{
		resizeurl += "~"
	}
	if ((slideshow == 1) && (pause) == 1)
	{
		resizeurl += "+"
	}
	window.location = resizeurl
}


// cross-browser code for getting the ID of the DIV containing the image, this is to ensure
// that the dhtml is as cross-browser as possible, even if the styles aren't.  This is used
// in the init function for locating the image.
function getObj(name)
{
  if (document.getElementById)
  {
  	this.obj = document.getElementById(name);
	this.style = document.getElementById(name).style;
  }
  else if (document.all)
  {
	this.obj = document.all[name];
	this.style = document.all[name].style;
  }
  else if (document.layers)
  {
   	this.obj = document.layers[name];
   	this.style = document.layers[name];
  }
}


// This convoluted routine is merely to get the start/stop slideshow text to blink
// because IE does not support the blink property
blinke = ""
function blinking()
{
	if (blinke == "")
	{
		blinke = "colour"
		for (var li_item=0;li_item<document.getElementsByTagName("SPAN").length;li_item++)
		{
			if (document.getElementsByTagName("SPAN")[li_item].id=="start1")
			{
				document.getElementsByTagName("SPAN")[li_item].className="full_start"
			}
			else if (document.getElementsByTagName("SPAN")[li_item].id=="start2")
			{
				document.getElementsByTagName("SPAN")[li_item].className="full_start"
			}
//			else if (document.getElementsByTagName("SPAN")[li_item].id=="pause1")
//			{
//				document.getElementsByTagName("SPAN")[li_item].className="full_stop"
//			}
//			else if (document.getElementsByTagName("SPAN")[li_item].id=="pause2")
//			{
//				document.getElementsByTagName("SPAN")[li_item].className="full_stop"
//			}
		}
	}
	else	
	{
		blinke = ""
		for (var li_item=0;li_item<document.getElementsByTagName("SPAN").length;li_item++)
		{
			if (document.getElementsByTagName("SPAN")[li_item].id=="start1")
			{
				document.getElementsByTagName("SPAN")[li_item].className="full_whyte"
			}
			else if (document.getElementsByTagName("SPAN")[li_item].id=="start2")
			{
				document.getElementsByTagName("SPAN")[li_item].className="full_whyte"
			}
//			else if (document.getElementsByTagName("SPAN")[li_item].id=="pause1")
//			{
//				document.getElementsByTagName("SPAN")[li_item].className="full_whyte"
//			}
//			else if (document.getElementsByTagName("SPAN")[li_item].id=="pause2")
//			{
//				document.getElementsByTagName("SPAN")[li_item].className="full_whyte"
//			}
		}
	}
}
window.setInterval("blinking()", 900)


//  This function is intended to vertically size the thin vertical margin that runs along the 
//  right hand edge of the left hand menu bar.
function resize_window() 
{
	// This block of lines is a workaround because I can't get FF to shorten the height of the 
	// category tree simply by measuring the available space and adjusting it accordingly, in 
	// the case of panoramas, where the image is too wide but not too high.  It seems that the 
	// measurement is not taking into account the horizontal scroll bar.
	// It is only used in the category scrolling version.
	divwidth = document.getElementById('full_photoouter').offsetWidth
	divheight = document.getElementById('full_photoouter').offsetHeight
	toowide = divwidth + left_margin + 4 - windowwidth // how far does the image hang to the right of the document window 
	toohigh = divheight + top_margin + 4 - windowheight // how far does the image hang below the document window 
	scroll_height_fudge=0
	if ((toowide > 0) && (toohigh < 0) && (self.innerWidth)) scroll_height_fudge = 21;
	
	document.getElementById('full_left_margin').style.height = totalheight - top_margin - 4 + 'px'
	document.getElementById('full_banner').style.width = totalwidth - scroll_width_fudge - 20 + 'px'
	setTimeout("resize_window()", 10);
}


function position_image()
{
	// Now calculate the centre of the image accordingly in the space reserved for it
	imagelocation = left_margin + 0.5*(windowwidth - left_margin - divwidth - scroll_width_fudge - 0)
	imagelocatiom = top_margin + 0.5*(windowheight - top_margin - divheight - 0)

	// Make an exception for images that are too large
	if (toowide > 0)
	{
    		imagelocation = left_margin + 15
	}
	if (toohigh > 0)
	{
		imagelocatiom = top_margin + 2
	}

	// Set the location
	photoout.style.left = imagelocation + 'px';
	photoout.style.top = imagelocatiom + 'px';

	//This has been commented out in this version because subsequent positioning is controlled by the float_image routine
	//setTimeout("position_image()", 10);
}


// These following functions will cause the image to move down on the web page if needed in  
// order to keep it visible and not have it scroll off the page - i.e. if the category tree
// is expanded downwards to such an extent that in viewing the lower part of the category
// tree the image would otherwise disappear off the top of the screen.  The routine is called
// at the end of the init routine below, which is called at by <body onLoad="init()">
// Floating Menu script-  Roy Whittle (http://www.javascript-fx.com/)
// Script featured on/available at http://www.dynamicdrive.com/

// It's a disappointment to me that I had to replicate this function three times to move
// three elements on the page, but I failed in my attempts to turn this into a subroutine.

function Float_Image()
{
	startX = imagelocation;
	startY = imagelocatiom;
	function ml(id)
	{
		var el=document.getElementById?document.getElementById(id):document.all?document.all[id]:document.layers[id];
		if(document.layers)el.style=el;
		el.sP=function(x,y){this.style.left=x + 'px';this.style.top=y + 'px';};
		el.x = startX;
		el.y = startY;
		return el;
	}
	window.stayTopLeft=function()
	{
		startX = left_margin + 0.5*(windowwidth - left_margin - divwidth - scroll_width_fudge - 0) // need to continuously remeasure where we want to position the image
		startY = top_margin + 0.5*(windowheight - top_margin - divheight - 0) // need to continuously remeasure where we want to position the image
		if (startX < left_margin + 15) startX = left_margin + 15 // keep wide images against the left margin
		if (startY < top_margin + 2) startY = top_margin + 2; // don't let the image go above the top margin
		scrollamount = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop; // how far scrolling has already occurred

		if (totalheight == windowheight)
		{
			scrollpercent = 0; // if there is no scrolling possible, reflect this in the percentage parameter
		}
		else
		{
			scrollpercent = scrollamount / (totalheight - windowheight) // the percent of the maximum scroll that has already occurred
		}
		var scrolltarget = (totalheight - windowheight)- toohigh  // this is the maximum we want the the image to move

		if ((toohigh > 0) && (toohigh < scrolltarget)) // If the image doesn't fit on the screen, only move it if the category tree extends below the image, otherwise you'd never get to see the bottom of the image and the page keeps growing
		{
			ftlObj.y += ( ( (1-scrollpercent)*startY + scrollpercent*scrolltarget) - ftlObj.y)/jumps;
		}
		else if (toohigh < 0) // normal movement of image if it fits on the screen
		{
			ftlObj.y += (scrollamount + startY - ftlObj.y)/jumps;
		}
		ftlObj.y = Math.floor(ftlObj.y)
		ftlObj.sP(startX, ftlObj.y);
		setTimeout("stayTopLeft()", millisecs);
	}
	ftlObj = ml("full_photoouter");
	stayTopLeft();
}

// These next two functions are duplicates of the previous one,
// except that they can be abbreviated because a number of the variables 
// have already been defined in the previous function, and as these routines
// are repeated, the values are constantly updated.

function Float_Heading()
{
	strtX = 10;
	strtY = 0;
	function mlh(id)
	{
		var elh=document.getElementById?document.getElementById(id):document.all?document.all[id]:document.layers[id];
		if(document.layers)elh.style=elh;
		elh.sPh=function(x,y){this.style.left=x + 'px';this.style.top=y + 'px';};
		elh.x = strtX;
		elh.y = strtY;
		return elh;
	}
	window.stayTopLefth=function()
	{
		htlObj.y += (scrollamount + strtY - htlObj.y)/jumps;
		htlObj.y = Math.floor(htlObj.y)
		htlObj.sPh(htlObj.x, htlObj.y);
		setTimeout("stayTopLefth()", millisecs);
	}
	htlObj = mlh("full_banner");
	stayTopLefth();
}

function Float_Controls()
{
	sttX = 0;
	sttY = 35;
	function mln(id)
	{
		var eln=document.getElementById?document.getElementById(id):document.all?document.all[id]:document.layers[id];
		if(document.layers)eln.style=eln;
		eln.sPn=function(x,y){this.style.left=x + 'px';this.style.top=y + 'px';};
		eln.x = sttX;
		eln.y = sttY;
		return eln;
	}
	window.stayTopLeftn=function()
	{
		gtlObj.y += (scrollamount + sttY - gtlObj.y)/jumps;
		gtlObj.y = Math.floor(gtlObj.y)
		gtlObj.sPn(gtlObj.x, gtlObj.y);
		setTimeout("stayTopLeftn()", millisecs);
	}
	gtlObj = mln("full_controls");
	stayTopLeftn();
}

// Optional persistence feature from dynamicdrive.com
// These next two routines set and retrieve a cookie, which is used to maintain the page scroll 
// position when you go from one page to another, thus keeping the same location in the category
// tree displayed on the screen.
function get_cookie(Name) {
	//Get cookie routine by Shelley Powers 
	var search = Name + "="
	var returnvalue = "";
	if (document.cookie.length > 0) 
	{
		offset = document.cookie.indexOf(search)
		// if cookie exists
		if (offset != -1) 
		{ 
			offset += search.length
    		// set index of beginning of value
			end = document.cookie.indexOf(";", offset);
			// set index of end of cookie value
			if (end == -1) end = document.cookie.length;
			returnvalue=unescape(document.cookie.substring(offset, end))
		}
	}
	return returnvalue;
}
function set_cookie(){
	var name = "fp_scroll"
	var cookiedata = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop
	if (cookiedata=="") cookiedata=0;
	document.cookie=name+"=; -1 ; path=/;"
	document.cookie=name+"="+cookiedata+"; 0 ; path=/;"
}
scrollamountprevious = get_cookie("fp_scroll")


function display_image()
{
	if (image_display != 1)
	{
		// DHTML fixes for centering the images. 
		// The source for this idea from www.xs4all.nl/~ppk/js/fixedmenu.html
		// See also www.mark.ac/help/sticky.html for some ideas
		image_display = 1
	
		// The screen and image width were measured at the outset, but need to be remeasured
		// for NS/FF, because this is the first place that they can be guaranteed to do it.
		// Of course, if the image was preloaded, NS/FF could have done it at the start 
		// of the page load, but preload is only guaranteed if traversing the images in sequence.
	 	imagewidth = thePhoto.width
		imageheight = thePhoto.height;

		// Unhide the image as a last step, otherwise it may jump around
		// If the image was preloaded, this won't really be needed
		// But if it wasn't preloaded, i.e. a thumbnail other than the first on was clicked
		// on, then we need to hide it until it has beed fully loaded and positioned.
		// Size the height of the left margin and the width of the banner.
		photoout = new getObj('full_photoouter');
	 	set_dimensions()
		resize_window();
		position_image()
		photoout.style.visibility = 'visible';

	}
}

// This function is called from the "body tag onload action" to do a range of things that need
// to be done last, after the page has fully loaded
function init()
{
	// If this hasn't been triggered already, then we need to do it here at the last gasp
	display_image()
	
	// Move the image down on the web page if needed in order to keep it visible and not have 
	// it scroll off the page.  This will also relocate the image if the browser size changes or 
	// changes to full screen. It will also keep the thin lines sized correctly.
	if (floatimage=="yes") Float_Image();
	if (floatheading=="yes") Float_Heading();
	if (floatnavigationcontrols=="yes") Float_Controls();
	if (rememberscroll=="yes") window.scroll(0,scrollamountprevious)
	
	// Ensure the correct slideshow control text is shown if we came to this image
	// because the NEXT or PREV button was been pressed.  In this situation, the slideshow
	// should have been paused and the controls need to be consistent with this.  Not sure 
	// if this is still needed in the Imatch version.
	if (pause)
	{
		document.getElementById('both_stopp').style.display = 'none';
		document.getElementById('both_startt').style.display = 'block';
		pause = 1;
	}

	//preload next image, previously defined
	if ((loadNext.length > 0) && (loadNext.indexOf('<#') == -1))
	{
		nextimage.src = loadNexxt;
	}

	// For debugging purposes only
	// document.write('timeout = ' + timeout + ';  slideshow = ' + slideshow + ';  pause = ' + pause + ';  i = ' + i + ';  j = ' + j + ';  m = ' + m)

}
