/* ================================
    thunder::tech Setup JavaScript
   ================================ */

/* Detected and set from HTML */

var isIE6;
isIE6 = false;

/* Adds a contains function to Array
   Credit: http://www.roseindia.net/java/javascript-array/javascript-array-contains.shtml */

function arrayContains(thisArray, element)
{
	for (var i = 0; i < thisArray.length; i++)
	{
		if (thisArray[i] == element)
		{
			return true;
		}
	}
	return false;
};

/* Changes the src attribute of an element
   ex: <img onmouseover="srcTo(this, 'images/thundertech.gif')"
   onmouseout="srcTo(this, '')" /> */

function srcTo(target_element, new_src)
{
	target_element.src = new_src;
}

/* Preloads an image file given its URL */

var myImages = new Array;

function preloadImage(image)
{
	if(document.images)
	{
		var nImage = new Image;
		myImages[image] = nImage;
		nImage.src = image;
	}
}

/* Load a random image using the following properties of its settingsObject parameter:

   filenameStart - Location of the file up to the number, including any path specification
   filenameEnd - Location of the file after the number, including the extension
   lastImage - The number of the final image.  The first image is 1.
   imgTarget - The img DOM element to change the src of
   excludeList - Optional, an array of numbers to exclude.
   associateAHref - Optional, a reference to an anchor tag to change the href attribute of
   aHrefs - Use with associateHref, an array of strings to set the href attribute to
   asBackground - Apply to the background instead of the source

   randomImageByNumber({filenameStart: "images/random_", filenameEnd:".jpg", lastImage: 7, imgTarget: document.getElementById("testimg"), excludeList: [ 3, 4, 6 ] });
   randomImageByNumber({filenameStart: "images/random_", filenameEnd:".jpg", lastImage: 7, imgTarget: document.getElementById("testdiv"), excludeList: [ 3, 4, 6 ], asBackground: true });
   
   Would pick from the following:
   
   images/random_1.jpg
   images/random_2.jpg
   images/random_5.jpg
   images/random_7.jpg */

function randomImageByNumber(settingsObject)
{
	if(settingsObject.imgTarget)
	{
		var pickone
		var excludeList
		if(settingsObject.excludeList)
		{
			excludeList = settingsObject.excludeList;
		}
		else
		{
			excludeList = new Array;
		}
		do
		{
			pickone=Math.floor(Math.random()*settingsObject.lastImage)+1;
		}
		while(arrayContains(excludeList, pickone)!=false)
		if(settingsObject.associateAHref)
		{
			settingsObject.associateAHref.href = settingsObject.aHrefs[pickone - 1];
		}
		var selectedimgurl = settingsObject.filenameStart + pickone + settingsObject.filenameEnd;
		if(settingsObject.asBackground)
		{
			settingsObject.imgTarget.style.backgroundImage = "url("+selectedimgurl+")";
		}
		else
		{
			srcTo(settingsObject.imgTarget, selectedimgurl);
		}
	}
}

/* Replaces the innerHTML of a container with a thumbnail image gallery using the following properties of its settingsObject parameter:

   filenameStart, filenameEnd, lastImage, and excludeList are the same as in randomImageByNumber
   thumbFilenameStart and thumbFilenameEnd are filenameStart and filenameEnd for the thumbnails
   aAttributes, imgAttributes - Optional, additional attributes to place in the a and img tags.
   thumbColumns - The number of columns (div-based)
   columnClass - The class of column divs if thumbColumns >= 1
   galleryName - Affects the IDs of the images.  Necessary to set if there is more than one gallery on a page; default is thunderGallery
   popupAreaID - The ID string of the area that receives the images
   containerTarget - the DOM element to replace the innerHTML of, preferably a DIV tag.
   autoShowFirst - Optional, specify True to automatically populates the container specified with popupAreaID with the first image
   previousLink - Optional, text or HTML code that makes a previous link.  Default hides the link.
   nextLink - Optional, text or HTML code that makes a next link.  Default hides the link.
   useThickBox - Optional, specify True to set the class to thickbox, uses galleryName for the previous-next feature if available, and
      disregards popupAreaID.  Apply thickbox separately in order for this feature to work.
	  Initialize with TB_init after calling generateThumbGallery; doing so before will fail to add the correct javascript event to
	  elements of class "thickbox."  Makes the following properties irrelevent: nextLink, previousLink, autoShowFirst, popupAreaID.
	  Don't apply a class to the a tag using aAttributes because the a tag's class is thickbox.

   You cannot exclude 1 or the last number in the list or the previous/next will fail to work.
   
   Full Example using popupAreaID:
   generateThumbGallery({nextLink:"Next &gt;", previousLink:"&lt; Previous", autoShowFirst: true, popupAreaID: "test3", galleryName: "myGallery", filenameStart: "test/p", filenameEnd:".jpg", thumbFilenameStart: "test/sm_p", thumbFilenameEnd:"_t.jpg", lastImage: 4, containerTarget: document.getElementById("test2"), thumbColumns: 2, columnClass: "proof3", imgAttributes: " class=\"proof1\"", aAttributes: " class=\"proof2\"", excludeList: [2] });

   Simple Example using popupAreaID:
   generateThumbGallery({popupAreaID: "test3", filenameStart: "test/p", filenameEnd:".jpg", thumbFilenameStart: "test/sm_p", thumbFilenameEnd:"_t.jpg", lastImage: 4, containerTarget: document.getElementById("test2") });

   Example using thickbox:
   generateThumbGallery({useThickBox: true, galleryName: "myGallery", filenameStart: "test/p", filenameEnd:".jpg", thumbFilenameStart: "test/sm_p", thumbFilenameEnd:"_t.jpg", lastImage: 4, containerTarget: document.getElementById("test2"), thumbColumns: 2, columnClass: "proof3", excludeList: [2] });
   
   */

function generateThumbGallery(settingsObject)
{
	if(settingsObject.containerTarget)
	{
		var excludeList;
		var finalInnerHTML = "";
		var imgCounter;
		var currentImgURL;
		var colCount = 0;
		var colMax;
		var colClass;
		if(settingsObject.excludeList)
		{
			excludeList = settingsObject.excludeList;
		}
		else
		{
			excludeList = new Array;
		}
		if(settingsObject.aAttributes)
		{
			settingsObject.aAttributes = " " + settingsObject.aAttributes;
		} else settingsObject.aAttributes = "";
		if(!(settingsObject.galleryName))
		{
			settingsObject.galleryName = "thunderGallery";
		}
		if(settingsObject.useThickBox)
		{
			settingsObject.aAttributes = settingsObject.aAttributes + " rel=\"" + settingsObject.galleryName + "\"";
		}
		if(settingsObject.imgAttributes)
		{
			settingsObject.imgAttributes = " " + settingsObject.imgAttributes;
		}
		if(!(settingsObject.previousLink))
		{
			settingsObject.previousLink = "";
		}
		if(!(settingsObject.nextLink))
		{
			settingsObject.nextLink = "";
		}
		if(settingsObject.thumbColumns)
		{
			colMax = settingsObject.thumbColumns;
			if(settingsObject.columnClass)
			{
				colClass = " class=\""+settingsObject.columnClass+"\"";
			}
			else
			{
				colClass = "";
			}
			finalInnerHTML = "<div"+colClass+">"
		}
		for(imgCounter = 1; imgCounter <= settingsObject.lastImage; imgCounter++)
		{
			if(arrayContains(excludeList, imgCounter)==false)
			{
				if(settingsObject.autoShowFirst == true)
				{
					settingsObject.autoShowFirst = false;
					popupGalleryImage(imgCounter, settingsObject.lastImage, settingsObject.excludeList, settingsObject.filenameStart, settingsObject.filenameEnd, settingsObject.previousLink, settingsObject.nextLink, settingsObject.popupAreaID);
				}
				currentImgURL = settingsObject.thumbFilenameStart + imgCounter + settingsObject.thumbFilenameEnd;
				if(settingsObject.useThickBox)
				{
					finalInnerHTML = finalInnerHTML + "<a href=\"" + settingsObject.filenameStart + imgCounter + settingsObject.filenameEnd + "\"" + settingsObject.aAttributes + " class=\"thickbox\" "+"><img src=\""+currentImgURL+"\""+settingsObject.imgAttributes+" id=\""+settingsObject.galleryName+imgCounter+"\" /></a>";
				}
				else
				{
					finalInnerHTML = finalInnerHTML + "<a"+settingsObject.aAttributes+" "+genPopupHref(settingsObject, imgCounter)+"><img src=\""+currentImgURL+"\""+settingsObject.imgAttributes+" id=\""+settingsObject.galleryName+imgCounter+"\" /></a>";
				}
				if(colMax > 0)
				{
					colCount ++;
					if((colCount >= colMax)&&(imgCounter<settingsObject.lastImage))
					{
						colCount = 0;
						finalInnerHTML = finalInnerHTML + "</div><div"+colClass+">";
					}
				}
			}
		}
		if(colMax > 0)
		{
			finalInnerHTML = finalInnerHTML + "</div>"
		}
		settingsObject.containerTarget.innerHTML = finalInnerHTML;
	}
}

/* Internal:
   Generates a href="" with a javascript function call to popupGalleryImage for:
   - the Previous/Next links generated by popupGalleryImage
   - the images generated by generateThumbGallery
   Requires an image index and either generateThumbGallery's settingsObject or a scaled down version
   with at least previousLink, nextLink, lastImage, excludeList, filenameStart, filenameEnd, and popupAreaID.
*/

function genPopupHref(settingsObject, imgCounter)
{
	var thisHTMLCode = "href=\"javascript:popupGalleryImage("+imgCounter+", " + settingsObject.lastImage+", ";
	thisHTMLCode = thisHTMLCode + "[" + settingsObject.excludeList.toString() + "], ";
	thisHTMLCode = thisHTMLCode + "'" + settingsObject.filenameStart + "', ";
	thisHTMLCode = thisHTMLCode + "'" + settingsObject.filenameEnd + "', ";
	thisHTMLCode = thisHTMLCode + "'" + settingsObject.previousLink + "', ";
	thisHTMLCode = thisHTMLCode + "'" + settingsObject.nextLink + "', ";
	thisHTMLCode = thisHTMLCode + "'" + settingsObject.popupAreaID+"');\"";
	return thisHTMLCode;
}


/* Internal:
   Shows a popup image from a link generated by either itself or generateThumbGallery.
*/
function popupGalleryImage(imgCounter, lastImage, excludeList, filenameStart, filenameEnd, previousLink, nextLink, myAreaID)
{
	var myURL = filenameStart + imgCounter + filenameEnd;
	var finalInnerHTML = "<img src=\"" + myURL + "\" />";
	var prevInt = exclusiveIntSearch(imgCounter, -1, excludeList, lastImage, 1, lastImage);
	var nextInt = exclusiveIntSearch(imgCounter, 1, excludeList, lastImage, 1, 1);
	if(previousLink!="")
	{
		finalInnerHTML = finalInnerHTML + "<a style=\"float: left; clear: left;\" " + genPopupHref({previousLink: previousLink, nextLink:nextLink, filenameStart: filenameStart, filenameEnd: filenameEnd, popupAreaID: myAreaID, excludeList: excludeList, lastImage: lastImage}, prevInt) + ">"+previousLink+"</a>";
	}
	if(nextLink!="")
	{
		finalInnerHTML = finalInnerHTML + "<a style=\"float: right; clear: right;\" " + genPopupHref({previousLink: previousLink, nextLink:nextLink, filenameStart: filenameStart, filenameEnd: filenameEnd, popupAreaID: myAreaID, excludeList: excludeList, lastImage: lastImage}, nextInt) + ">"+nextLink+"</a>";
	}
	document.getElementById(myAreaID).innerHTML = finalInnerHTML;
}

/* Internal:
   Searches for an integer by an interval with a minimum, maximum, and exlude list.  Returns fail if minimum or maximum are reached.
   Used in popupGalleryImage to get the next and previous images in the gallery.
*/

function exclusiveIntSearch(presentInt, incInt, excludeList, maxInt, minInt, failInt)
{
	var thisInt = presentInt;
	do
	{
		thisInt = thisInt + incInt;
		if((thisInt > maxInt)||(thisInt < minInt))
		{
			//alert("failed and returned "+ failInt);
			return failInt;
		}
	}
	while(arrayContains(excludeList, thisInt)!=false)
	//alert("succeeded and returned "+ failInt);
	return thisInt;
}

var thunderPopup;

function openPopup(wURL, wWidth, wHeight)
{
thunderPopup = window.open (wURL, "wThunderPopup", "location=0,status=0,toolbar=0,scrollbars=0,resizable=0,menubar=0,directories=0,copyhistory=0,width="+wWidth+",height="+wHeight);
}

function openPopupAt(wURL, wWidth, wHeight, wX, wY)
{
thunderPopup = window.open (wURL, "wThunderPopup", "location=0,status=0,toolbar=0,scrollbars=0,resizable=0,copyhistory=0,menubar=0,directories=0,width="+wWidth+",height="+wHeight);
thunderPopup.moveTo(wX,wY);
}

function closePopup()
{
thunderPopup.close();
}

/* Makes a default text for an input text field
   settingsObject properties:
   inputTarget - an input tag text field element
   defaultValue - the value
   onStyle (styleTo number) - Optional.  The style of the input field when text is entered
   offStyle (styleTo number) - Optional.  The style of the input field when defaultValue is shown
   isPassword (Boolean) - Optional.  Makes a password box.
   
   The function will not work in IE if isPassword is set to true because IE does not support
   dynamically changing the input tag type property
*/

function makeDefaultingInputText(settingsObject)
{
	var skipThisFn;
	skipThisFn = ((navigator.appName=="Microsoft Internet Explorer")&&(settingsObject.isPassword))
	if(!skipThisFn)
	{
		settingsObject.inputTarget.value = settingsObject.defaultValue;
		if(settingsObject.offStyle) { styleTo(settingsObject.inputTarget, settingsObject.offStyle); }
		if(settingsObject.isPassword) { settingsObject.inputTarget.type = "text"; }
		settingsObject.inputTarget.onblur = function()
		{
			if(settingsObject.inputTarget.value=="")
			{
				if(settingsObject.offStyle) { styleTo(settingsObject.inputTarget, settingsObject.offStyle); }
				settingsObject.inputTarget.value = settingsObject.defaultValue;
				if(settingsObject.isPassword) { settingsObject.inputTarget.type = "text"; }
			}
		};
		settingsObject.inputTarget.onfocus = function()
		{
			if(settingsObject.inputTarget.value==settingsObject.defaultValue)
			{
				settingsObject.inputTarget.value = "";
				if(settingsObject.onStyle) { styleTo(settingsObject.inputTarget, settingsObject.onStyle); }
				if(settingsObject.isPassword) { settingsObject.inputTarget.type = "password"; }
			}
		};
	}
}

/* Dynamically set the action of a form before sending.  Form by ID. */

function sendIdTo(thisId, thisURL)
{
	document.getElementById(thisId).action = thisURL;
	document.getElementById(thisId).submit();
}

/* Boolean for whether a unicode keycode (keypress event.keyCode) is a common navigation key */

function aNavKey(p)
{
	// Arrows
	if((p>=38)&&(p<=40)) { return true; }
	// Home, end, pgup, pgdn
	if((p>=33)&&(p<=36)) { return true; }
	// Shift, Alt
	if((p==16)||(p<=18)) { return true; }
	// Command, Escape
	if((p==224)||(p==27)) { return true; }
	return false;
}

/* Returns a rollover button. */

function rollButton(upImg, overImg, hrefAttr, altAttr)
{
	return "<a href=\""+hrefAttr+"\"><img src=\""+upImg+"\" alt=\""+altAttr+"\" onmouseover=\"this.src='"+overImg + "';\" onmouseout=\"this.src='"+upImg+"';\" /></a>";
}

/* Cuts text off.  Simplest use is with the HTML onchange or onkeypress attributes */

function limitText(theField, theLimit)
{
	var limitedText;
	limitedText = "";
	var i;
	for(i=0; i< theLimit; i++)
	{
		limitedText=limitedText+theField.value.substr(i, 1);
	}
	theField.value = limitedText;
}

/* Replace all occurances in a string instead of just the first one */

function replaceAll(originalString, lookString, replacementString)
{
	do
	{
		originalString=originalString.replace(lookString, replacementString);
	}
	while(originalString.search(lookString)>0)
	return originalString;
}
