var thisStyle1;
var thisStyle2;
var thatStyle1;
var thatStyle2;

// Determine browser type
var sNavName = "";
var iNavVersion = 0;
if (navigator.appName.indexOf("Netscape") >= 0) {
   sNavName = "Netscape";
} else if (navigator.appName.indexOf("Microsoft") >= 0) {
   sNavName = "Microsoft";
}
iNavVersion = parseInt(navigator.appVersion);

function getElementFunction() {
// Return the text string of the document's Get Element function, or null if none.

if (document.getElementById) return "getElementById"
if (document.all) return "all";
return "";
}

function getStyle(element, styleName) {
  var sGetElement = getElementFunction();
  var styleValue = "";

  if (sGetElement != "") {
    eval("styleValue = document." + sGetElement + "(element).style." + styleName);
  }
  return styleValue;

}

function setStyle(element, styleName, styleValue) { 
  var sGetElement = getElementFunction();

  if (sGetElement != "") {
    eval("document." + sGetElement + "(element).style." + styleName + " = '" + styleValue + "'");
  }

}

function setStyleInWindow(sWindow, element, styleName, styleValue) { 
  var sGetElement = getElementFunction();

  if (sGetElement != "") {
    eval(sWindow + ".document." + sGetElement + "(element).style." + styleName + " = '" + styleValue + "'");
  }

}

function setText(element, sText) {
  var sGetElement = getElementFunction();

  if (sGetElement != "") {
    sText = sText.replace(/\'/g, "\\'");
    sText = sText.replace(/[\f\n\r]/g, ""); // required by Netscape 7.2 (and others?)
    eval("document." + sGetElement + "(element).innerHTML = '" + sText + "'");
  }

}

function getTextInWindow(sWindow, element) {
  var sGetElement = getElementFunction();

  if (sGetElement != "") {
    return eval(sWindow + ".document." + sGetElement + "(element).innerHTML");
  }

}

function setTextInWindow(sWindow, element, sText) {
  var sGetElement = getElementFunction();

  if (sGetElement != "") {
    sText = sText.replace(/\'/g, "\\'");
    sText = sText.replace(/[\f\n\r]/g, ""); // required by Netscape 7.2 (and others?)
    eval(sWindow + ".document." + sGetElement + "(element).innerHTML = '" + sText + "'");
  }

}

function stylizeURL(el) {
  var sGetElement = getElementFunction();
  var thisElement;
  var thatElement;

  if (sGetElement != "") {
    thisElement = el.id;
    thatElement = thisElement.replace(/a/, "b");
    thisStyle1 = getStyle(thisElement, "fontWeight");
    setStyle(thisElement, "fontWeight", "bold");
    thisStyle2 = getStyle(thisElement, "color");
    setStyle(thisElement, "color", "#990033");
    thatStyle1 = getStyle(thatElement, "fontWeight");
    setStyle(thatElement, "fontWeight", "bold");
  }

}

function stylizeButton(el) {
  var sGetElement = getElementFunction();
  var thisElement;

  if (sGetElement != "") {
    thisElement = el.id;
    thisStyle1 = getStyle(thisElement, "color");
    setStyle(thisElement, "color", "blue");
  }

}

function revertURL(el) {
  var sGetElement = getElementFunction();
  var thisElement;
  var thatElement;

  if (sGetElement != "") {
    thisElement = el.id;
    thatElement = thisElement.replace(/a/, "b");
    setStyle(thisElement, "fontWeight", thisStyle1);
    setStyle(thisElement, "color", thisStyle2);
    setStyle(thatElement, "fontWeight", thatStyle1);
  }

}

function revertButton(el) {
  var sGetElement = getElementFunction();
  var thisElement;

  if (sGetElement != "") {
    thisElement = el.id;
    setStyle(thisElement, "color", thisStyle1);
  }

}

function appendQS(sURL, sQS) {
// This function appends the sQS query string to sURL, preceding it with either a ? or &.
var sChar = sURL.indexOf("?")<0?"?":"&";
var iHash = sURL.indexOf("#");

if (iHash>0) {
	return sURL.replace(/#/, sChar + sQS + "#");
} else {
	return sURL + sChar + sQS;
}
}

function openHelp1(url) {
// This function opens the help1 window. The window is positioned at the top right of the screen.
var iSW = screen.availWidth;
var iW = (iSW <= 800 ? 280 : 360);
var iH = screen.availHeight - (iSW <= 800 ? 120 : 150);
var iLeft = iSW - iW + 1;
window.open(appendQS(url, "Width="+iW+"&Height="+iH), "NRDBHelp1", "height=" + iH + ",width=" + iW + ",screenX=" + iLeft + ",left=" + iLeft + ",screenY=1,top=1,scrollbars,resizable=yes").focus();
return false;
} 

function openHelp2(url) {
// This function opens the help2 window. The window is positioned at the bottom right of the screen.
var iSW = screen.availWidth;
var iW = (iSW <= 800 ? 280 : 360);
var iH = (iSW <= 800 ? 120 : 150);
var iLeft = iSW - iW + 1;
var iTop = screen.availHeight - iH + 1;
window.open(appendQS(url, "Width="+iW+"&Height="+iH), "NRDBHelp2", "height=" + iH + ",width=" + iW + ",screenX=" + iLeft + ",left=" + iLeft + ",screenY=" + iTop + ",top=" + iTop + ",scrollbars,resizable=yes").focus();
return false;
} 

function onLoadEHForHelp(iWidth, iHeight, sVertex) {
// This function is the onLoad event handler for help windows.
// It resizes the window to iWidth x iHeight, and then repositions
// it to the sVertex, where sVertex is NW, NE, SE, SW.
// The window is resized and repositioned only if iWidth > 0 and
// this is the first new page loaded.
if (iWidth > 0 && history.length <= (sNavName=="Netscape"?1:0)) {
	window.resizeTo(iWidth,iHeight);
	switch (sVertex) {
		case "NW": // top left
			window.moveTo(1,1);
			break;
		case "NE": // top right
			window.moveTo(screen.availWidth-iWidth+1,1);
			break;
		case "SE": // bottom right
			window.moveTo(screen.availWidth-iWidth+1,screen.availHeight-iHeight+1);
			break;
		case "SW": // bottom left
			window.moveTo(1,screen.availHeight-iHeight+1);
			break;
	}
	// Netscape needs to reload the page after the window has been resized in order
	// to position the hash anchor at the top of the window.
	location.replace(document.URL.replace(/Width=\d*/i, "Width=0"));
}
}

function restoreQuery(oForm, sGBLCookieVersion) {
// This function restores the search criteria from the document's cookies.
// The savedCounty and savedManager cookies, which represent extensions of the search criteria,
//   are also restored.
// The gblCookieVersion variable is used to control whether the cookie applies to this version of code.

var version = getCookie("NRDB_version");
var querystring = getCookie("NRDB_querystring");
var oDate = new Date;
if (version == sGBLCookieVersion) {
   if (querystring != "") {
	  reconstructFormFields(oForm, querystring);
	  oDate.setFullYear(oDate.getFullYear() + 1); // Expiration date is 1 year from now
	  setCookie("NRDB_County", getCookie("NRDB_savedCounty"), oDate.toGMTString());
	  setCookie("NRDB_Manager", getCookie("NRDB_savedManager"), oDate.toGMTString());
   	  oForm.submit();
   } else {
      alert("There is no saved search. You may use the Advanced Search form to save a search.");
      location.replace(document.URL.replace(/SavedSearch=Y/i, "SavedSearch=N"))
   }
} else {
   alert("Your saved search is no longer valid. You may use the Advanced Search form to save a new search.");
   location.replace(document.URL.replace(/SavedSearch=Y/i, "SavedSearch=N"))
}

return false;
}

function reconstructFormFields(oForm, sQS) {
// This function reconstructs oForm from the sQS query string.
// sQS is an escaped querystring.

var aQueryString, aNameValue, i;

if (typeof oForm == "undefined") return;

clearForm(oForm);
oForm.PageHeader.value = "Saved Search";
sQS = sQS.replace(/\+/g, "%20");
aQueryString = unescape(sQS).split(/&/);
for (i = 0; i < aQueryString.length; i++) {
	aNameValue = aQueryString[i].split(/=/);
	if (typeof aNameValue[1] == "undefined") { // name1=&name2=&name3=&...
		continue;
	}
	aNameValue[0] = unescape(aNameValue[0]);
	aNameValue[1] = unescape(aNameValue[1]);
//	alert("oForm." + aNameValue[0] + ".value = \"" + aNameValue[1] + "\"");
	if (typeof eval("oForm." + aNameValue[0]) == "undefined") {
//		alert("oForm." + aNameValue[0] + " is undefined");
	} else if (aNameValue[0] == "SpeciesCategory") {
		oForm.SpeciesCategory.value += (oForm.SpeciesCategory.value ? ", " : "") + aNameValue[1];
	} else if (aNameValue[0] == "Preserves") {
		oForm.Preserves.value += (oForm.Preserves.value ? ", " : "") + aNameValue[1];
	} else if (aNameValue[0].indexOf("T_C") == 0) {
		eval("oForm." + aNameValue[0] + ".value += (oForm." + aNameValue[0] + ".value ? \", \" : \"\") + \"" + aNameValue[1] + "\"");
	} else {
		eval("oForm." + aNameValue[0] + ".value = \"" + aNameValue[1] + "\"");
	}
}
}

function r(jsArray) {
   var i;
   var ans=t[jsArray[0]];
   for (i=1;i<jsArray.length;i++) {
      if (typeof jsArray[i] =="object") { // recurse?
         jsArray[i]=r(jsArray[i]);
      }
      ans=ans.replace(m,jsArray[i]);
   }
   return ans;
}
function w(jsArray) {
   document.write(jsArray);
}

function validateMatchingText(s) {
// This function validates s, the matching text string for searches.
// s must be at least 2 characters in length and have at least 1 non-wildcard
// character.
// The function returns true if s is valid.

var aMatch;
var sMsg = "Please enter at least 2 non-* characters for the \"Matching\" field.";

if (s.length < 2) {
	alert(sMsg);
	return false;
} else {
	aMatch = s.match(/[^\*]/g);
	if (aMatch == null) {
		alert(sMsg);
		return false;
	} else if (aMatch.length < 2) {
		alert(sMsg);
		return false;
	}
}

return true;
}

function HighlightSelectedForm(oForm) {
// This function highlights all "selected" elements of oForm. This is required because
// some browsers don't highlight them properly.
var i;
if (typeof oForm != "undefined") {
	for (i = 0; i < oForm.length; i++) {
		HighlightSelectedElement(oForm.elements[i]);
	}
}
}

function HighlightSelectedElement(oElement) {
var i;
if (oElement.type.toLowerCase().indexOf("select") == 0) {
	for (i = 0; i < oElement.length; i++) {
		if (oElement.options[i].selected == true) {
			oElement.options[i].selected = true;
		}
	}
}
}

function reSort(oForm, i, s, sFieldName) {
// This function updates the ith sort order value, clears the RSKey, and submits the form.
// If i is negative, it is assumed the OrderAD field has no indices, and that RSKey is not used,
// but the sFieldName argument is used.
if (i < 0) {
	oForm.OrderAD.value = s;
	oForm.Order.value = sFieldName;
} else {
	eval("oForm.OrderAD" + (i + 1) + ".value=\"" + s + "\";");
	oForm.RSKey.value = "";
}
oForm.action = location.pathname;
oForm.submit();
}

function changeSubset(sType, sValue, iFormCount) {
// This function changes the sType subset to sValue and reloads the page.
// To clear a subset value, sValue should be the empty string.
var oDate = new Date;
if (iFormCount > 0 && getCookie("NRDB_Repost") == "") {
	alert("Sometimes when changing the County or Manager designation, you will be asked to approve resending information. To complete the change, you should always ALLOW information to be resent.");
	setCookie("NRDB_Repost", "1");
}
oDate.setFullYear(oDate.getFullYear() + 1); // Expiration date is 1 year from now
setCookie(sType, sValue, oDate.toGMTString());
location.reload(true);
}

function getCookie(sName) {
// This function returns the value of the cookie corresponding to case-insensitive sName.

var cookie = document.cookie;
if (eval("cookie.search(/(^|;\\s*)" + encode(sName) + "=([^;]*)/i)") >=0) {
   return decode(RegExp.$2);
}
return "";

}

function setCookie(sName, sValue) {
// This function sets the cookie named sName to sValue.
// The 3rd optional argument contains the Expires attribute.

document.cookie = encode(sName) + "=" + encode(sValue) + "; path=/" +
	(arguments.length == 3 ? "; expires=" + arguments[2] : "");
}

function encode(s) {
// This function behaves like the IIS Server.URLEncode.
var aIn =  new Array("%",   "`",   "~",   "!",   "@",   "#",   "$",   "^",   "&",   "*",   "(",   ")",   "_",   "+",   "-",   "=",   "[",   "]",   "\\",   "{",   "}",   "|",   ";",   "'",   ":",   "\"",   ",",   ".",   "/",   "<",   ">",   "?",   "\f",   " ");
var aOut = new Array("\\f", "%60", "%7E", "%21", "%40", "%23", "%24", "%5E", "%26", "%2A", "%28", "%29", "%5F", "%2B", "%2D", "%3D", "%5B", "%5D", "%5C",  "%7B", "%7D", "%7C", "%3B", "%27", "%3A", "%22",  "%2C", "%2E", "%2F", "%3C", "%3E", "%3F", "%25", "+");
var i;

s = s + ""; // Convert to string
for (i = 0; i < aIn.length; i++) {
	eval("s = s.replace(/\\" + aIn[i] + "/g, \"" + aOut[i] + "\")");
}
return s;
}

function decode(s) {
// This function behaves like the IIS Server.URLDecode would behave, if there were one.

var aIn =  new Array("%60", "%7E", "%21", "%40", "%23", "%24", "%5E", "%26", "%2A", "%28", "%29", "%5F", "%2B", "%2D", "%3D", "%5B", "%5D", "%5C",  "%7B", "%7D", "%7C", "%3B", "%27", "%3A", "%22",  "%2C", "%2E", "%2F", "%3C", "%3E", "%3F", "%25", "\\+");
var aOut = new Array("`",   "~",   "!",   "@",   "#",   "$",   "^",   "&",   "*",   "(",   ")",   "_",   "+",   "-",   "=",   "[",   "]",   "\\\\", "{",   "}",   "|",   ";",   "'",   ":",   "\\\"", ",",   ".",   "/",   "<",   ">",   "?",   "%",   " ");
var i;

s = s + ""; // Convert to string
for (i = 0; i < aIn.length; i++) {
	eval("s = s.replace(/" + aIn[i] + "/g, \"" + aOut[i] + "\")");
}
return s;
}

function searchArray(a, s) {
// This function searches the a array for an entry matching s.
// It returns the 0-relative index of s, or -1 if no entries match.

var i;

for (i = 0; i < a.length; i++) {
	if (a[i] == s) return i;
}
return -1;
}

function isRadioChecked(oRadio) {
// This function returns true if any item of the oRadio element is checked.

if (typeof oRadio.checked == "undefined") {
	for (var i = 0; i < oRadio.length; i++) {
		if (oRadio[i].checked) return true;
	}
	return false;
} else {
	return oRadio.checked;
}
}
function expandContractAbbrevs(oElement, sFieldName, iRecordCount) {
/*
	Expand (if oElement.value == "+") or contract the string of abbreviations.
	If expanding, replace abbrevs with their corresponding names.
	If contracting, do the reverse.

	Internet Explorer v6 does not properly repaint the window under certain
	conditions. This causes the hanging menu buttons to appear in the wrong
	position on the screen, and unless the window has scroll bars, there is
	no easy way to correct it. The conditions are:
		1. You + from a window without vertical scroll bars into a window
			with vertrical scroll bars AND
		2. You scroll down AND
		3. You - back.
	To circumvent this problem, when doing a -, we resize the window smaller
	to force it to have vertical scroll bars, then perform the - operation,
	then scroll the window by 1 pixel to force the menu buttons to reposition
	themeselves, then scroll the window back to where it was, then resize
	the window back to its original size.

	We perform this circumvention regardless of the browser type since it
	has minimal affect.

	Since there is no way to detect whether a window has scroll bars, it is
	problematic to force it to have them by resizing it smaller, i.e. this
	workaround is not foolproof.
*/

var i, j, s, a;

if (oElement.value == "+") {
	for (i = 1; i <= iRecordCount; i++) {
		s = getTextInWindow("window", sFieldName + i);
		s = s.replace(/\s+/g, " "); // remove newlines seen by Navigator
		eval("a" + sFieldName + "AbbrevStrings[i] = s");
		s = s.replace(/<\/*b>/ig, "");
		a = s.split(", ");
		for (j = 0; j < a.length; j++) {
			a[j] = eval("a" + sFieldName + "Names[searchArray(a" + sFieldName + "Abbrevs, a[j])]");
		}
		s = a.join("<br>");
		setText(sFieldName + i, s);
	}
	oElement.value = "--";
} else {
	window.resizeBy(0,-100);
	for (i = 1; i <= iRecordCount; i++) {
		setText(sFieldName + i, eval("a" + sFieldName + "AbbrevStrings[i]"));
	}
	oElement.value = "+";
	window.scrollBy(0, 1);
	window.scrollBy(0, -1);
	window.resizeBy(0,100);
}
}
function plot(oForm, sPreserveAbbrev, sRSKey) {
// Submit these search results to Map Search.

if (sPreserveAbbrev != "" && sPreserveAbbrev != "All") {
	oForm.P.value = sPreserveAbbrev;
}
if (sRSKey != "") oForm.RSKey.value = sRSKey;
oForm.action = document.URL_mapsearch.action;
oForm.submit();
}

function csv(oForm, sPreserveAbbrev, sRSKey, sAction) {
// Create a csv file from these search results.
var sPriorAction = oForm.action;

if (sPreserveAbbrev != "" && sPreserveAbbrev != "All") {
	oForm.P.value = sPreserveAbbrev;
}
if (sRSKey != "") oForm.RSKey.value = sRSKey;
oForm.action = sAction;
oForm.submit();
oForm.action = sPriorAction;
}

function getOptionsValue(oElement) {
// Return the value of the selected option of oElement
// If no option is selected, return null

if (oElement.selectedIndex < 0) return "";
return oElement.options[oElement.selectedIndex].value;
}

function clearForm(oForm) {
// Clear all elements of oForm
for (var i = 0; i < oForm.elements.length; i++) oForm.elements[i].value = "";
}

// Stop hiding from old browsers -->