// Global Declarations
var mInterval = 3500;				// Milliseconds of delay between slides in automatic mode
var random_display = 0;				// Random display is disabled.
var mImageDir = "images/";			// Folder or directory where images reside
var mRowClassName = "galleryrow";	// Class name for row divs in the gallery HTML page. Change to reflect a different CSS classname.
var mImageNum = 0;					// The current index to the image path array
var mImageArray = new Array();	 	// Array of relative file paths for the images on a gallery page
var mTotalImages = 0;				// Count of file paths in the array
var mDivArray = document.getElementsByTagName(mRowClassName);
var mImageIndex = 0;				// Current index to the file path array
var mLastImage = 0;					// Ordinal number of the last image path in the array
var mImageId = "slideImg";			// CSS identifier for the slideshow image element. Change to reflect a different
									// name in the slideshow HTML page.
var kSHOWWIDTH = 640;	// Display area width
var kSHOWHEIGHT = 640;	// Display area height
var mPreImages = new Array();		// Array of preloaded images to enable resizing
var mLoaded = new Array(),i,covered,timerID;
var mCurrCount = 0;

	function getElementsByClassName(searchClass, oElem, strTagName)
    {
      	var arrReturnElements = new Array();
      	if (oElem == null) { oElem = document; }
      	if (strTagName == null) { strTagName = '*'; }
		var arrElements = oElem.getElementsByTagName(strTagName);
		var oRegExp = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
		for (var i=0, j=0; i<arrElements.length; i++) {
			if (oRegExp.test(arrElements[i].className)) {
				arrReturnElements[j] = arrElements[i];
				j++;
			}
		}
		return arrReturnElements;
	}
	
	function loadImagesFromTags() 
	{
		mDivArray = getElementsByClassName(mRowClassName, document);
		mImageNum = 0; // initialize index before enumeration 
		// For each row division, get its anchor elements
		for(j=0;j<mDivArray.length;j++)
		{
			var oDiv = mDivArray[j];
			var anchorArray = oDiv.getElementsByTagName("a");
			// for each anchor element, parse its href attribute to get file path
			for(i=0;i<anchorArray.length;i++) 
			{
				var hrefattrib = anchorArray[i].href;		// Get anchor tag's href attribute
				var getit = new Array();
				var getit=hrefattrib.split(mImageDir);		// Split off front-end junk and folder
				var fname = getit[1];						// Get filename with junky tail ("filename.ext')")
				var nIdx = fname.lastIndexOf("'");			// Find the start of junky tail
				if (nIdx>0) {								// If that worked,
					filename = fname.substring(0, nIdx);	//   extract all but the junky tail.
					var filepath = mImageDir+filename;		// Rebuild the whole path
					mImageArray[mImageNum] = filepath; 		// Store path in next array member
					mImageNum++;							// Bump the array index
				} else {
					// Here we have an errant anchor element that for some reason 
					// is not parseable. Throw up an alert and continue on. This
					// results from either an HTML encoder error or a damaged page.
					alert("ERROR: Unable to parse " + fname );	// show the junk we couldn't parse
				}
			}
		}
		mTotalImages = mImageArray.length;
		mLastImage = mTotalImages - 1;
		return true;
	}

	function filenameFromObject(oImage)
	{
		var len=oImage.length-4;
		var string=oImage.slice(0,len);		
		var x1=string.split(mImageDir);
		var x2=x1[1];
		var fname_ext=x2.split(",");
		var filename=mImageDir + fname_ext[0] + "." + fname_ext[1];
		return filename;
	}
	function openwindow(url) {
		/* Get the index to the image just clicked */
		
		var x=window.open("sshow1.htm",'gal_window','toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=no, resizable=yes, width=860, height=800');
		for(i=0;i<mImageArray.length;i++) {
			// Get the index to the image just clicked
			filename = mImageArray[i];
			if( filename == url ) {
				mImageIndex = i;
				x.focus();
				return;
			}
		}
		x.focus();
	}

	function imageItem(image_location) {
		this.image_item = new Image();
		this.image_item.src = image_location;
	}
	function get_ImageItemLocation(imageObj) {
		return(imageObj.image_item.src)
	}
	function randNum(x, y) {
		var range = y - x + 1;
		return Math.floor(Math.random() * range) + x;
	}
	function getNextImage() {
		if (random_display) {
			mImageNum = randNum(0, mLastImage);
		}
		else {
			if(mImageNum == mTotalImages)
				mImageNum = 0;
			else
				mImageNum = (mImageNum+1) % mTotalImages;
		}
//	 	var new_image = mImageArray[mImageNum];
	 	var new_image = mPreImages[mImageNum];
		return(new_image);
	}
	function getPrevImage() {
		if(mImageNum == 0)
			mImageNum = mTotalImages;
		mImageNum = (mImageNum-1) % mTotalImages;
//		var new_image = mImageArray[mImageNum];
		var new_image = mPreImages[mImageNum];
		return(new_image);
	}
	function prevImage(place) {
		var new_image = getPrevImage();
		document[place].src = new_image;
		adjustImageSize(place, new_image);
	}
	function switchImage(place) {
		var imgsrc = getNextImage();   // this is the full file url
		document[place].src = imgsrc;
		adjustImageSize(place, imgsrc);
		var recur_call = "switchImage('"+place+"')";
		timerID = setTimeout(recur_call, mInterval);
		setShowCount();
    }
	/*
	 *  Called from switchImage() and prevImage() functions to expand
	 *		or contract the image to fit inside a kSHOWWIDTH by kSHOWHEIGHT box.
	 *	If portrait format, centers the image with CSS padding style.
	 *	If landscape format, pushes the image to bottom of box with CSS padding style.
	 *  Preserves proportions in all cases.
	 *  Inputs:
	 *     place - the HTML id for the display division element
	 * 	   imgsrc - the full image url
	*/
	function adjustImageSize(place, adjImage)
	{
		var elem = document[place];
		elem.src = adjImage.src;
		var oldht = adjImage.height;		// get original image width
		var oldwd = adjImage.width;			// get original image height
		var isPortrait = oldht > oldwd ? true : false;
		var ht = 0;
		var wd = 0;
		if( oldht > kSHOWHEIGHT && oldwd > kSHOWWIDTH)		// HEIGHT AND WIDTH TOO BIG
		{
			if (isPortrait) {						// portrait
				ht = kSHOWHEIGHT;					// squeeze down height to limit
				wd = kSHOWWIDTH * (oldwd/oldht);	// limit times portrait ratio
			} else {								// landscape
				wd = kSHOWWIDTH;					// squeeze down width to limit
				ht = kSHOWHEIGHT * (oldht/oldwd);	// limit times landscape ratio
			}
		}
		else if (oldht > kSHOWHEIGHT && oldwd <= kSHOWWIDTH)	
		{											// HEIGHT TOO BIG, WIDTH FITS == portrait
			ht = kSHOWHEIGHT;						// squeeze down height to limit
			wd = oldwd * (kSHOWHEIGHT/oldht);		// adjust old width by height contraction factor
		}
		else if (oldht <= kSHOWHEIGHT && oldwd > kSHOWWIDTH)	
		{											// HEIGHT FITS, WIDTH TOO BIG == landscape
			wd = kSHOWWIDTH;						// squeeze down width to limit
			ht = oldht * (kSHOWWIDTH/oldwd); 		// adjust old height by width contraction factor
		}
		else {										// HEIGHT AND WIDTH TOO SMALL
			if (isPortrait) {						// portrait
				ht = kSHOWHEIGHT;					// expand height to limit
				wd = oldwd * (kSHOWHEIGHT/oldht);	// adjust old width by height expansion factor
			} else {								// landscape
				wd = kSHOWWIDTH;					// squeeze down width to limit
				ht = oldht * (kSHOWHEIGHT/oldwd);// adjust old height by width expansion factor
			}		
		}
		elem.style.width = wd + "px";
		elem.style.height = ht + "px";
		elem.style.paddingLeft = 0;
		elem.style.paddingTop = 0;
		if ( isPortrait && adjImage.width < kSHOWWIDTH ) 
			elem.style.paddingLeft = (kSHOWWIDTH-wd)/2 + "px";
		if ( !isPortrait && adjImage.height < kSHOWHEIGHT )
			elem.style.paddingTop = (kSHOWHEIGHT-ht) + "px";
	}

	function setShowCount() {
		document.ctrls.count.value = mImageNum+1 + " / " + mTotalImages;
	}
	
	function get_title()
	{
		var x = opener.document.getElementsByTagName('title');
		var obj = document.getElementById('heading');
		obj.innerHTML = x[0].innerHTML;
	}
	function setSpeed()
	{
		var oSel = document.ctrls.speed;
		var selected_index = oSel.selectedIndex;
		
		if(selected_index >= 0) {
			mInterval = oSel.options[selected_index].value;
		} else {
			alert('Please select a speed from the drop down list');
		}
	}
	function loadShow() {
		for(i=0; i<opener.mImageArray.length; i++)
		{
			mImageArray[i] = opener.mImageArray[i];
			mPreImages[i] = new Image();
			mPreImages[i].src = mImageArray[i];
		}
		for(i=0; i<mPreImages.length; i++)	{
			mLoaded[i] = false;
		}
		mTotalImages = mImageArray.length; 
		get_title();
		mImageNum = opener.mImageIndex - 1;
		checkLoad();
		document.onkeyup = checkKey;	// don't set keyup event handler until now
	}

	/*
	 *  Responds to an onKeyUp event, set at the close of function loadShow().
	 *  Evaluates keystrokes for navigation between slideshow images.
	 *  Allows user to use arrow keys, home/end, and pgup/pgdn keys,
	 *  as well as left mouse clicks over the two nav image buttons.
	*/
	function checkKey(evt)
	{
		evt = (evt) ? evt : ((window.event) ? event : null);
		if (evt) {
			switch (evt.keyCode)
			{
				case 37:	// left arrow 
				case 38: 	//  up arrow
				{ 										// get previous image
					prevImage(mImageId); 				
					setShowCount(); 
					clearTimeout(timerID);
					break;
				}
				case 39:	// right arrow
				case 40:	// down arrow
				{ 										// get next image
					switchImage(mImageId); 			
					clearTimeout(timerID); 
					break;
				}
				case 33:	// page up 
				case 36:	// home 
				{										// move to first image
					mImageNum = -1;			// switchImage will bump this to 0
					switchImage(mImageId);			
					clearTimeout(timerID); 
					break;
				}
				case 34: 	// page down 
				case 35: 	// End key 
				{										// move to last image
					mImageNum = mTotalImages-2; // switchImage will bump this
					switchImage(mImageId);
					clearTimeout(timerID); 
					break;
				}
			}
		}
	}
	function checkLoad() {
		if (mCurrCount == mPreImages.length) { 
			return;
		}
		for (i = 0; i <= mPreImages.length; i++) {
			if (mLoaded[i] == false && mPreImages[i].complete) {
				mLoaded[i] = true;
				mCurrCount++;
			}
		}
		timerID = setTimeout("checkLoad()",10) ;
	}
