//------------------------------------------------------------------------------------------------------------------------
// governs the menu
function toggleMenu(menuCount, varItem) {

	for (i=1;i<=menuCount;i++) {
		objMain = $(String('main'+i));
		objSub = $(String('sub'+i));
		
		if (String(i) == String(varItem)) {
			objMain.className = "menuitem-on";
			toggleDisplay(String('sub'+i), true);
		} else {
			objMain.className = "menuitem";
			toggleDisplay(String('sub'+i), false);
		}
	}
}

//------------------------------------------------------------------------------------------------------------------------
// governs the home page tabs
function toggleTabs(varTab) {
	var TabList = new Array("Welcome","News");
	
	for (i=0; i<eval(TabList.length);i++) {
		objTab = $(String('tab'+TabList[i]));
		objBox = $(String('usap'+TabList[i]));
		
		if (String(TabList[i]) == String(varTab)) {
			objTab.className = "tabOn";
			objBox.style.display = "block";} 
		else {
			objTab.className = "tabOff";
			objBox.style.display = "none";
		}
	}
}

//------------------------------------------------------------------------------------------------------------------------
// shows or hides a designated DOM object
function toggleDisplay(varObj, varShow) {
	objDom = $(String(varObj));
	if (varShow) {objDom.style.display = "block";} else {objDom.style.display = "none";}
}

//------------------------------------------------------------------------------------------------------------------------
// loads a news item into the news section of the homepage (for non-Flash users)
function loadNewsItem(varItem) {
	$("usapFlashNews").innerHTML = "";
	var url = "/WebServices/getUsapNews.cfm?id="+varItem+"&="+Math.random()*1000000;
	var ajax = new Ajax.Updater('usapFlashNews', url, {method:'get'});
}

//------------------------------------------------------------------------------------------------------------------------
//refreshes the dates and times on the station times page
function refreshTimes() {
	
	var regionSelect = $("regionSelect");
	regionSelect.disabled = true;

	var url = "/components/TimeService.cfc";
	var params = 'method=returnAllDateTimes&View=Long&Display=DateTime';
	
	$("getTimes").innerHTML = "Retrieving Data...";
	$("getTimes").style.display = "block";
	$("antTimes").style.display = "none";
	$("usTimes").style.display = "none";
	$("nzTimes").style.display = "none";
	
	var ajax = new Ajax.Request(url,{method: 'get', parameters:params, onComplete:updateTimes});
}

//------------------------------------------------------------------------------------------------------------------------
// determines if a string passed to the function is a number
function isInteger(s) {

	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

//------------------------------------------------------------------------------------------------------------------------
// launches a new window with the desired properties
function newWindow(mypage, myname, w, h, scroll) {

	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',toolbar=no,status=no,scrollbars='+scroll+',resizable=no'
	win = window.open(mypage, myname, winprops)
	
	win.window.focus();
}

//------------------------------------------------------------------------------------------------------------------------
// correctly handle PNG transparency in Win IE 5.5 & 6.
function correctPNG() {

   var arVersion = navigator.appVersion.split("MSIE");
   var version = parseFloat(arVersion[1]);
   
   if ((version >= 5.5) && (version < 7) && (document.body.filters)) {
      for(var i=0;i<document.images.length;i++) {
         var img = document.images[i];
         var imgName = img.src.toUpperCase();
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" ;
            img.outerHTML = strNewHTML;
            i = i-1;
         }
      }
   }    
}

//----------------------------------------------------------------------------------------------------------------------------------------------
// SEARCH FUNCTIONS -

// ******************************************************
function displayResults(varFrameName) {

	resizeIframe(String(varFrameName));
	var objLoader = parent.document.getElementById("loader");
	objLoader.style.display = "none";
}

// ******************************************************
function resizeIframe(varFrameName) {
	if (parent.document.getElementById(varFrameName)) {
		var i = parent.document.getElementById(varFrameName);
		
		var x,y;
		var test1 = document.body.scrollHeight;
		var test2 = document.body.offsetHeight

		if (test1 > test2) {
			y = document.body.scrollHeight;
		} else {
			y = document.body.offsetHeight;
		}
		
		i.style.height = String(y + 5) + "px";
		return true;
	} else {
		return false;
	}
}

//***********************************************
function pageNav(formString) {
	var varForm = eval("document."+formString);
	varForm.submit();
}

//***********************************************
function pageSelector() {
	var varForm = eval(document.pageSelect);
	var varOptions = varForm.pageList[varForm.pageList.selectedIndex].value;
	var varArray = varOptions.split("!");
	
	varForm.startRec.value = varArray[0];
	varForm.page.value = varArray[1];
	varForm.submit();
}

//***********************************************
function validateSearch() {

	var searchTerm = document.search.searchString.value;
	var TermArray = searchTerm.split(" ");
	var ignoreList = "";
	
	//array that defines the list of disallowed terms or characters
	var InvalidList = new Array("(",")","@","#","<",">","~","'","\\","/","*","^","%","+");
	var InvalidString =  "()@#<>~'\"*/^%+";
	
	//validate the search term
	if (searchTerm != "") {
		for (i=0;i<eval(InvalidList.length);i++) {
			for (x=0;x<eval(TermArray.length);x++) {
				if (String(TermArray[x]).indexOf(String(InvalidList[i])) > -1) {
					if (String(ignoreList) == "") {ignoreList = String(InvalidList[i]);} else {ignoreList = ignoreList + ", " + String(InvalidList[i]);}
				}
			}
		}
		
		if (String(ignoreList) != "") {
			alert("The following words or characters are invalid search terms.\n\n"+ignoreList+"\n\nPlease rephrase your search or enter a more specific search term.");
			document.search.searchString.focus();
			return false;
		}

		document.search.searchString.value = stripCharsInBag(document.search.searchString.value, InvalidString);
	} else {
		alert("You must enter one or more keywords in order to perform a search.");
		document.search.searchString.focus();
		return false;
	}
	
	if (validateSearch) {
		document.search.submit();
		return true;
	} else {
		return false;
	}
}

//***********************************************
function validateAdvancedSearch() {

	//define the user-inputted string values 
	var searchTerm = document.advsearch.searchString.value;
	var searchAuthor = document.advsearch.docAuthor.value;
	var searchSubject = document.advsearch.docSubject.value;
	var searchFileName = document.advsearch.docFileName.value;
	
	//generate arrays of search terms 
	var TermArray = searchTerm.split(" ");
	var AuthorArray = searchAuthor.split(" ");
	var SubjectArray = searchSubject.split(" ");
	var FileNameArray = searchFileName.split(" ");
	
	var ignoreList = "";
	var selected = "";
	
	//array that defines the list of disallowed terms or characters
	var InvalidList = new Array("(",")","@","#","<",">","~","'","\\","/","*","^","%","+");
	var InvalidString =  "()@#<>~'\"*/^%+";
	
	//validate the search term
	if (searchTerm != "") {
		for (i=0;i<eval(InvalidList.length);i++) {
			for (x=0;x<eval(TermArray.length);x++) {
				if (String(TermArray[x]).indexOf(String(InvalidList[i])) > -1) {
					if (String(ignoreList) == "") {ignoreList = String(InvalidList[i]);} else {ignoreList = ignoreList + ", " + String(InvalidList[i]);}
				}
			}
		}
		
		if (String(ignoreList) != "") {
			alert("The following words or characters are invalid search terms.\n\n"+ignoreList+"\n\nPlease rephrase your search or enter a more specific search term.");
			document.advsearch.searchString.focus();
			return false;
		}
		
		document.advsearch.searchString.value = stripCharsInBag(document.advsearch.searchString.value, InvalidString);
	} else {
		alert("You must enter one or more keywords in order to perform a search.");
		document.advsearch.searchString.focus();
		return false;
	}
	
	//validate the search fields
	for (x=0;x<eval(document.advsearch.docFields.length);x++) {
		if (document.advsearch.docFields[x].checked) {selected = x;}
	}
	
	if (String(selected) == "") {
		alert("You must select one or more search fields to use in your search.");
		document.advsearch.docFields[0].focus();
		return false;
	}
	
	//validate the document types
	selected = ""; 
	for (x=0;x<eval(document.advsearch.docType.length);x++) {
		if (document.advsearch.docType[x].checked) {selected = x;}
	}
	
	if (String(selected) == "") {
		alert("You must select one or more document types to use in your search.");
		document.advsearch.docType[0].focus();
		return false;
	}
		
	//validate the author
	ignoreList = "";
	if (searchAuthor != "") {
		for (i=0;i<eval(InvalidList.length);i++) {
			for (x=0;x<eval(AuthorArray.length);x++) {
				if (String(AuthorArray[x]).indexOf(String(InvalidList[i])) > -1) {if (String(ignoreList) == "") {ignoreList = String(InvalidList[i]);} else {ignoreList = ignoreList + ", " + String(InvalidList[i]);}}
			}
		}
		
		if (String(ignoreList) != "") {
			alert("The following words or characters are invalid search terms.\n\n"+ignoreList+"\n\nPlease rephrase your search or enter a more specific search term.");
			document.advsearch.docAuthor.select();
			document.advsearch.docAuthor.focus();
			return false;
		}
		
		document.advsearch.docAuthor.value = stripCharsInBag(document.advsearch.docAuthor.value, InvalidString);
	}
	
	//validate the subject
	ignoreList = "";
	if (searchSubject != "") {
		for (i=0;i<eval(InvalidList.length);i++) {
			for (x=0;x<eval(SubjectArray.length);x++) {
				if (String(SubjectArray[x]).indexOf(String(InvalidList[i])) > -1) {if (String(ignoreList) == "") {ignoreList = String(InvalidList[i]);} else {ignoreList = ignoreList + ", " + String(InvalidList[i]);}}
			}
		}
		
		if (String(ignoreList) != "") {
			alert("The following words or characters are invalid search terms.\n\n"+ignoreList+"\n\nPlease rephrase your search or enter a more specific search term.");
			document.advsearch.docSubject.select();
			document.advsearch.docSubject.focus();
			return false;
		}
		
		document.advsearch.docSubject.value = stripCharsInBag(document.advsearch.docSubject.value, InvalidString);
	}
	
	//validate the filename
	ignoreList = "";
	if (searchFileName != "") {
		for (i=0;i<eval(InvalidList.length);i++) {
			for (x=0;x<eval(FileNameArray.length);x++) {
				if (String(FileNameArray[x]).indexOf(String(InvalidList[i])) > -1) {if (String(ignoreList) == "") {ignoreList = String(InvalidList[i]);} else {ignoreList = ignoreList + ", " + String(InvalidList[i]);}}
			}
		}
		
		if (String(ignoreList) != "") {
			alert("The following words or characters are invalid search terms.\n\n"+ignoreList+"\n\nPlease rephrase your search or enter a more specific search term.");
			document.advsearch.docFileName.select();
			document.advsearch.docFileName.focus();
			return false;
		}
		
		document.advsearch.docFileName.value = stripCharsInBag(document.advsearch.docFileName.value, InvalidString);
	}
	
	if (validateAdvancedSearch) {
		document.advsearch.submit();
		return true;
	} else {
		return false;
	}
}

// ******************************************************
function stripCharsInBag(s, bag) {
	var i;
    var returnString = "";

    for (i=0;i<eval(s.length);i++) {   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) {returnString += c;}
    }
    return returnString;
}

// *****************************************************
function GetObject(n) {
	var x,t; 
	
	if ((n.indexOf("?")) > 0 && parent.frames.length) {
		t = n.split("?");
		x=eval("parent.frames['"+t[1]+"'].document.getElementById('"+t[0]+"')");
	} else {
		x=document.getElementById(n)
	}
	return x;
}

//----------------------------------------------------------------------------------------------------------------------------------------------
// functions for swapping font styles
function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

window.onload = function(e) {
  var cookie = readCookie("style");
  var title = cookie ? cookie : getPreferredStyleSheet();
  setActiveStyleSheet(title);
}

window.onunload = function(e) {
  var title = getActiveStyleSheet();
  createCookie("style", title, 365);
}

var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);

//----------------------------------------------------------------------------------------------------------------------------------------------
// run time code 
window.attachEvent("onload", correctPNG);

// --------------------------------------------------------------------------------------------------//
// POP-UP SCRIPT // 
function PopupPic(sPicURL,sPageTitle) { 
window.open( "/global/popup.cfm?"+sPicURL+"&pageTitle="+sPageTitle, "", 
"resizable=1,HEIGHT=200,WIDTH=200"); 
} 
