// Preload waiting.
if (document.images) {
	waitingImg = new Image();
	waitingImg.src = "/images/activeWait.gif";
	navonImg = new Image();
	navonImg.src = "/images/newNavOn.gif";
	mastheadImg = new Image();
	mastheadImg.src= "/images/newAPSmastheadOver.png";
}

// Spacer for messages
var spacer = '<img src="/images/spacer.gif" width="1" height="6" border="0" /><br />';

// Change partner banner
function doPartnerBanner(whichCode) {
	document.getElementById('partnerBanner').src='/images/'+whichCode+'_banner_N.jpg';
}

// Disable submit when clicked.
function disableSubmit(buttonName,formName) {
	var whichForm=eval('document.' + formName);
	var whichButton=eval('document.' + formName + '.' + buttonName);
	whichButton.disabled=true;
	whichButton.className='greybutton';
	whichForm.submit();
}

function saveSearchNew() {
	if (document.saveSearchForm.searchName.value=='') {
		document.getElementById('saveInfo').innerHTML='<b>You must name your saved search.</b>';	
	} else {
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.open('POST','/savesearch.cfm',true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState==4) {
				var finalInfo = decodeURIComponent(xmlhttp.responseXML.getElementsByTagName('data')[0].firstChild.data);
				if (finalInfo==1) {
					document.getElementById("saveSearchDiv").innerHTML='<i><b>Search saved!</b></i> You can re-run it from "My Archive" above.</i>';
				} else {
					document.getElementById("saveSearchDiv").innerHTML='<i>You must log in to the left in order to save searches.</i>';
				}
			} else {
				document.getElementById("saveSearchDiv").innerHTML='<img src="/images/activeWait.gif" width="16" height="16" border="0" align="absmiddle" /> Saving...';	
			}
		}
		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xmlhttp.send('searchName='+encodeURIComponent(document.saveSearchForm.searchName.value)+'&fullSave='+encodeURIComponent(document.saveSearchForm.fullSave.value));
	}
}
function dosaveSearch() {
	document.getElementById('saveSearchOut').innerHTML='<p><div id="saveSearchDiv"></div></p>';
	switchDiv('saveSearchDiv');
}

function afterLogin() {
	if (document.getElementById('saveSearchOut')) {
		dosaveSearch();
	}
	window.location.href='/index.cfm';
}

function doTab(onTab,offTab) {
	document.getElementById(offTab+'Tab').className='hometab ltbluetab';
	document.getElementById(offTab+'Box').style.display='none';	
	document.getElementById(onTab+'Tab').className='hometab greytab';
	document.getElementById(onTab+'Box').style.display='block';	
}
function overTab(which) {
	if (which.className=='hometab ltbluetab') {
		which.className='hometab redtab';
	}
}
function offTab(which) {
	if (which.className=='hometab redtab') {
		which.className='hometab ltbluetab';
	}
}

// Save resources.
function saveResourceNew(whichFunction) {
	if (document.saveResourceForm.folderID[document.saveResourceForm.folderID.selectedIndex].value==0) {
		alert('You must choose a folder.');
	} else {
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.open('POST','/saveresource.cfm',true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState==4) {
				var finalInfo = decodeURIComponent(xmlhttp.responseXML.getElementsByTagName('data')[0].firstChild.data);
				if (finalInfo==1) {
					window.frames['folderFrame'].location.reload(true);
					//document.getElementById("saveResourceDiv").innerHTML='<i><b>Resource saved!</b></i> You can access it from <a href="/my/resources.cfm">My Saved Resources</a> above.';
				} else {
					document.getElementById("saveResourceDiv").innerHTML='<i>You must log in to the left in order to save resources.</i>';
				}
			} else {
				document.getElementById("saveResourceDiv").innerHTML='<img src="/images/activeWait.gif" width="16" height="16" border="0" align="absmiddle" />';	
			}
		}
		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xmlhttp.send('whichFunction='+whichFunction+'&folderID='+document.saveResourceForm.folderID[document.saveResourceForm.folderID.selectedIndex].value+'&submissionID='+document.saveResourceForm.submissionID.value+'&userdocID='+document.saveResourceForm.userdocID.value);
	}
}

// Save resources.
function saveLinkNew(whichFunction) {
	if (document.saveLinkForm.folderID[document.saveLinkForm.folderID.selectedIndex].value==0) {
		alert('You must choose a folder.');
	} else {
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.open('POST','/my/saveLink.cfm',true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState==4) {
				var finalInfo = decodeURIComponent(xmlhttp.responseXML.getElementsByTagName('data')[0].firstChild.data);
				if (finalInfo==1) {
					window.frames['folderFrame'].location.reload(true);
					//document.getElementById("saveResourceDiv").innerHTML='<i><b>Resource saved!</b></i> You can access it from <a href="/my/resources.cfm">My Saved Resources</a> above.';
				} else {
					document.getElementById("saveLinkDiv").innerHTML='<i>You must log in to the left in order to save resources.</i>';
				}
			} else {
				document.getElementById("saveLinkDiv").innerHTML='<img src="/images/activeWait.gif" width="16" height="16" border="0" align="absmiddle" />';	
			}
		}
		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xmlhttp.send('whichFunction='+whichFunction+'&folderID='+document.saveLinkForm.folderID[document.saveLinkForm.folderID.selectedIndex].value+'&linkID='+document.saveLinkForm.linkID.value+'&userdocID='+document.saveLinkForm.userdocID.value);
	}
}

function delResource(userDocID) {
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open('POST','/saveresource.cfm',true);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState==4) {
			var finalInfo = decodeURIComponent(xmlhttp.responseXML.getElementsByTagName('data')[0].firstChild.data);
			if (finalInfo==1) {
				window.frames['folderFrame'].location.reload(true);
				//document.getElementById("saveResourceDiv").innerHTML='<i><b>Resource removed!</b></i> ';
			} else {
				document.getElementById("saveResourceDiv").innerHTML='<i>You must log in to the left in order to save resources.</i>';
			}
		} else {
			document.getElementById("saveResourceDiv").innerHTML='<img src="/images/activeWait.gif" width="16" height="16" border="0" align="absmiddle" />';	
		}
	}
	xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlhttp.send('whichFunction=4&folderID=0&submissionID=0&userdocID='+userDocID);
}

function delLink(userDocID) {
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open('POST','/my/saveLink.cfm',true);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState==4) {
			var finalInfo = decodeURIComponent(xmlhttp.responseXML.getElementsByTagName('data')[0].firstChild.data);
			if (finalInfo==1) {
				window.frames['folderFrame'].location.reload(true);
				//document.getElementById("saveResourceDiv").innerHTML='<i><b>Resource removed!</b></i> ';
			} else {
				document.getElementById("saveLinkDiv").innerHTML='<i>You must log in to the left in order to save resources.</i>';
			}
		} else {
			document.getElementById("saveLinkDiv").innerHTML='<img src="/images/activeWait.gif" width="16" height="16" border="0" align="absmiddle" />';	
		}
	}
	xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlhttp.send('whichFunction=4&folderID=0&linkID=0&userdocID='+userDocID);
}

// Process login form.
function doLogin() {
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open('POST','/verify.cfm',true);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState==4) {
			var finalInfo = decodeURIComponent(xmlhttp.responseXML.getElementsByTagName('data')[0].firstChild.data);
			switch(finalInfo) {
			case "1":
				document.getElementById("login2").innerHTML=spacer+'<i>More than one record exists for that e-mail.</i>';
				break
			case "2":
				afterLogin();
				break
			case "3":
				document.getElementById("login2").innerHTML=spacer+'<i>Incorrect password. Please try again or have your password <a href="javascript:sendPassword();">sent to the e-mail above</a>.</i>';
				break
			case "4":
				afterLogin();
				break
			case "5":
				document.getElementById("login2").innerHTML=spacer+'<i>Your password must be at least 8 characters.</i>';
				break
			case "6":
				document.getElementById("login2").innerHTML=spacer+'<i>Please use a valid full e-mail address.</i>';
				break
			}
		} else {
			document.getElementById("login2").innerHTML='<img src="/images/activeWait.gif" width="16" height="16" border="0" align="absmiddle" hspace="22" />';	
		}
	}
	xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlhttp.send('email='+encodeURIComponent(document.loginForm.email.value)+'&password='+encodeURIComponent(document.loginForm.password.value)+'&remember='+document.loginForm.remember.checked);
}
function sendPassword() {
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open('POST','/sendpassword.cfm',true);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState==4) {
			document.getElementById("login2").innerHTML=spacer+'Your password has been e-mailed to you.';
		} else {
			document.getElementById("login2").innerHTML='<img src="/images/activeWait.gif" width="16" height="16" border="0" align="absmiddle" hspace="22" />';	
		}
	}
	xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlhttp.send('email='+document.loginForm.email.value);
}

// Switch colors on results listings
function tabOn(which) {
	which.className='newtopbartabon';
}
function tabOff(which) {
	which.className='newtopbartab';
}
// Switch colors on results listings
function tabOnN(which) {
	document.getElementById(which).className='newtopbartabon';
}
function tabOffN(which) {
	document.getElementById(which).className='newtopbartab';
}

function overDoc(whichID) {
	if (document.getElementById('plus'+whichID).src.indexOf('plus')!=-1) {	
		document.getElementById('plus'+whichID).src='/images/minusicon.gif';
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.open('POST','/docMoreInfo.cfm',true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState==4) {
				var finalInfo = decodeURIComponent(xmlhttp.responseXML.getElementsByTagName('data')[0].firstChild.data);
				document.getElementById("moreInfo"+whichID).innerHTML='<hr noshade size="1">'+finalInfo+'<hr noshade size="1">';
			} else {
				document.getElementById("moreInfo"+whichID).innerHTML='<img src="/images/activeWait.gif" width="16" height="16" border="0" />';
			}
		}
		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xmlhttp.send('submissionID='+whichID);
	} else {
		offDoc(whichID);
	}
}
function offDoc(whichID) {
	document.getElementById('plus'+whichID).src='/images/plusicon.gif';
	document.getElementById("moreInfo"+whichID).innerHTML='';
}

// Open/Close div
function switchDiv(divID) {
	if (document.getElementById(divID).style.display=='none') {
		document.getElementById(divID).style.display='block';				   
	} else {
		document.getElementById(divID).style.display='none';
	}
}
function switchPlus(divID) {
	if (document.getElementById(divID).src.indexOf('plus')!=-1) {	
		document.getElementById(divID).src='/images/minusicon.gif';
	} else {
		document.getElementById(divID).src='/images/plusicon.gif';
	}
}

// Make sure keyword isn't blank on searches
function keywordCheck() {
	if (document.keywordSearch.keyword.value=='') {
		document.getElementById('keywordInfo').innerHTML='<b>You must enter something.</b>';
		return false;
	} else {
		document.getElementById('keywordInfo').innerHTML='<img src="/images/activeWait.gif" width="16" height="16" border="0" align="absmiddle"> Searching...';
		return true;
	}
}
function keywordCheckTop() {
	if (document.keywordSearchTop.keyword.value=='') {
		return false;
	} else {
		return true;
	}
}

// Disable save button
function disableSave() {
	document.getElementById('saveButton').disabled=true;
	document.getElementById('saveButton').className='greybutton';
	document.getElementById('saveButtonInfo').innerHTML='<img src="/images/activeWait.gif" width="16" height="16" border="0" align="absmiddle"> Saving...';
}

// Do waiting for advanced
function advancedCheck() {
	document.getElementById('advancedInfo').innerHTML='<img src="/images/activeWait.gif" width="16" height="16" border="0" align="absmiddle"> Searching...';
}

/**--------------------------
//* Validate Date Field script- By JavaScriptKit.com
//* For this script and 100s more, visit http://www.javascriptkit.com
//* This notice must stay intact for usage
---------------------------**/

function validDate(checkdate) {
var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval=false
//Detailed check for valid date ranges
var monthfield=checkdate.split("/")[0]
var dayfield=checkdate.split("/")[1]
var yearfield=checkdate.split("/")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
	returnval=false
else
	returnval=true
return returnval
}

// Cookie functions

function getCookie( name ) {
  var start = document.cookie.indexOf( name + "=" );
  var len = start + name.length + 1;
  if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
    return null;
  }
  if ( start == -1 ) return null;
  var end = document.cookie.indexOf( ";", len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, path, expires, domain, secure ) {
  var today = new Date();
  today.setTime( today.getTime() );
  if ( expires ) {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );
  document.cookie = name+"="+escape( value ) +
    ( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function deleteCookie( name, path, domain ) {
  if ( getCookie( name ) ) document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// Returns a handle to the named layer.
function getLayer(name) {
	if (document.layers) {
		return(document.layers[name]);
	}
	else {
		layer = document.getElementById(name);
		if (layer) {
			return(layer);
		} else {
			return(null);
		}
	}
}

// Hides the named layer.
function hideLayer(name) {
	var layer = getLayer(name);
	if (layer.style) {
		layer.style.visibility="hidden";	
	} else {
		layer.visibility="hide";
	}
}

// Shows the named layer.
function showLayer(name) {
	var layer = getLayer(name);
	if (layer.style) {
		layer.style.visibility="visible";	
	} else {
		layer.visibility="show";
	}
}

function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}
function Trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function LTrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function RTrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}
function validateURL(s) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(s);
}
function getInnerText(node,ignorewhitespace)
{
 var text = "";
 // if the node has children, loop through them
 if(node.hasChildNodes())
 {
  var children = node.childNodes;
  for(var i=0; i<children.length; i++)
  {
   // if node is a text node append it
   if(children[i].nodeName == "#text")
   {
    if(ignorewhitespace)
    {
     if(!/^\s+$/.test(children[i].nodeValue))
     {
      text = text.concat(children[i].nodeValue);
     }
    }
    else
    {
     text = text.concat(children[i].nodeValue);
    }
   }
   // if node is a line break append \n
   else if(children[i].nodeName == "BR")
   {
    text = text.concat("\n");
   }
   // otherwise call this function again to get the text
   else
   {
    text = text.concat(getInnerText(children[i]));
   }
  }
 }
 // it has no children, so get the text
 else
 {
  // if node is a text node append it
  if(node.nodeName == "#text")
  {
   text = text.concat(node.nodeValue);
  }
  // if node is a line break append \n
  else if(node.nodeName == "BR")
  {
   text = text.concat("\n");
  }
 }
 return text;
}

function Asc(String) {
	return String.charCodeAt(0);
}

function Chr(AsciiNum) {
	return String.fromCharCode(AsciiNum);
}

function validEmail(email) {
	if (email.indexOf("@")>=0 && email.indexOf(".")>=0 && email.indexOf("..")<0 && email.indexOf(" ")<0 && email.indexOf("@.")<0 && email.indexOf(Chr(96))<0 && Right(email,1)!=Chr(39) && email.indexOf(Chr(35))<0 && email.indexOf("&")<0 && email.indexOf("<")<0 && email.indexOf(">")<0 && email.indexOf(",")<0 && email.indexOf(";")<0 && email.indexOf("/")<0 && email.indexOf("\\")<0 && email.indexOf(")")<0 && email.indexOf("(")<0 && email.indexOf("[")<0 && email.indexOf("]")<0 && email.indexOf("{")<0 && email.indexOf("}")<0) {
		return true;
	} else {
		return false;
	}
}

function doSwitch(whichDo) {
	if (document.getElementById('rows'+whichDo).style.display=='none') {
		setCookie('rows'+whichDo+'Status',1,'/',365);
	} else {
		setCookie('rows'+whichDo+'Status',0,'/',365);
	}
	switchDiv('rows'+whichDo);
	switchPlus('plus'+whichDo);
}
function divStart(whichDo) {
	if (getCookie('rows'+whichDo+'Status')!=1) {
		doSwitch(whichDo);
	}
}

function doRating(whichID,ratingID,which) {
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open('POST','/saverating.cfm',true);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState==4) {
			var finalInfo = decodeURIComponent(xmlhttp.responseXML.getElementsByTagName('data')[0].firstChild.data);
			if (finalInfo!='X') {
				document.getElementById("RatingI").src='/images/spacer.gif';
				if (finalInfo=='0|0') {
					document.getElementById("ratingDiv").innerHTML='<i>This has not been rated. Be the first to add your rating!</i>';
					document.getElementById("ratingBar").style.display='none';
				} else {
					finalSplit=finalInfo.split("|");
					finalAvg=new Number(finalSplit[0]);
					finalTotal=finalSplit[1];
					finalWidth=(finalAvg/5)*166;
					if (finalTotal>1) {
						finalString=finalAvg.toFixed(1)+' out of 5 stars from '+finalTotal+' ratings.';
					} else {
						finalString=finalAvg.toFixed(1)+' out of 5 stars from '+finalTotal+' rating.';
					}					
					document.getElementById("ratingDiv").innerHTML=finalString;
					document.getElementById("ratingBar").style.display='inline';
					document.getElementById("ratingGreen").width=finalWidth;
				}
			}
		} else {
			document.getElementById("RatingI").src='/images/activeWait.gif';	
		}
	}
	xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlhttp.send('whichID='+whichID+'&ratingID='+ratingID+'&which='+which);
}

/*
function hideKeywords() {
	if (document.getElementById('collKeywords').offsetHeight>30) {
		collKeywordsHeight=document.getElementById('collKeywords').offsetHeight;
		document.getElementById('collKeywords').style.height='30px';
		document.getElementById('collKeywordsMore').style.display='block';
	}
}
function showKeywords() {
	document.getElementById('collKeywords').style.height=collKeywordsHeight+'px';
	document.getElementById('collKeywordsMore').style.display='none';
}
*/
function showPeds() {
	document.getElementById('collPeds').style.display='block';
	document.getElementById('collPedsMore').style.display='none';
}
function showKeywords() {
	document.getElementById('collKeywords').style.display='block';
	document.getElementById('collKeywordsMore').style.display='none';
}

function doWidth() {
	if (isNaN(document.embedForm.frameWidth.value)) {
		document.embedForm.frameWidth.value=250;
	}
	if (document.embedForm.frameWidth.value>400) {
		document.embedForm.frameWidth.value=400;
	}
	if (document.embedForm.frameWidth.value<210) {
		document.embedForm.frameWidth.value=210;
	}
	document.getElementById('apsFrame').width=document.embedForm.frameWidth.value;
	getCode();
}
function doHeight() {
	if (isNaN(document.embedForm.frameHeight.value)) {
		document.embedForm.frameHeight.value=400;
	}
	document.getElementById('apsFrame').height=document.embedForm.frameHeight.value;
	document.getElementById('apsFrame').contentWindow.resizeIt();
	getCode();
}
