// filename: javascipt.js
// initial: 2006-12-21 Scott Warren (warren@nscl.msu.edu)
// function: This file contains all the javascipt for the whole site
////////////////////////////////////////////////////////////////////////////////

var info;
var replace;

function ajaxRequest(strURL,strReplace){
	replace = strReplace;
	// get the xmlhttp object
	info = GetXmlHttpObject();
	
	// check to see if the object has been defined
	if(info == null){
		return false;
	}
	
	//document.getElementById(replace).innerHTML = "Loading...";
	
	// set the information
	info.onreadystatechange=ajaxRequestStateChange;
	info.open("GET", strURL, true);
	info.send(null);
	
	return true;
}

function ajaxRequestStateChange(){
	if(info.readyState == 4){
		document.getElementById(replace).innerHTML = info.responseText;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Function: confirmLink
////////////////////////////////////////////////////////////////////////////////
// Description: This function asks the user if they would like to perform the 
// 	 a certain action
// 
// Arguments:
//	theLink: the link that it should go to
//	theSqlQuery: The sql that will be performed (??? I think ???)
// 
// Returns:
//	true: if the action is confirmed
//	false: otherwise
var confirmMsg  = 'Do you really want to ';
function confirmLink(theLink, theSqlQuery)
{
    // Confirmation is not required in the configuration file
    // or browser is Opera (crappy js implementation)
    if (confirmMsg == '' || typeof(window.opera) != 'undefined') {
        return true;
    }

    var is_confirmed = confirm(theSqlQuery);
    if (is_confirmed) {
        theLink.href += '&confirmed=1';
    }

    return is_confirmed;
} // end of the 'confirmLink()' function



////////////////////////////////////////////////////////////////////////////////
// Function: checkAll
////////////////////////////////////////////////////////////////////////////////
// Description: This function checks every checkbox in a field
// 
// Arguments: 
//	field: the checkboxes
// 
// Returns: nothing
function checkAll(field)
{
for (i = 0; i < field.length; i++)
	field[i].checked = true ;
	
return false;
}

////////////////////////////////////////////////////////////////////////////////
// Function: uncheckAll
////////////////////////////////////////////////////////////////////////////////
// Description: This function unchecks all the checkboxes with a name
// 
// Arguments:
//	field: the checkboxes
// 
// Returns:
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
	field[i].checked = false ;
	
return false;
}

////////////////////////////////////////////////////////////////////////////////
// Function: changeStyle
////////////////////////////////////////////////////////////////////////////////
// Description: This function changes the style of an object
// 
// Arguments:
//	objObject: the object
//	strStyle: the new classname
// 
// Returns: nothing
function changeStyle(objObject, strStyle)
{
	objObject.className = strStyle;
}

////////////////////////////////////////////////////////////////////////////////
// Function: toggleDisplay
////////////////////////////////////////////////////////////////////////////////
// Description: This function toggles if an element is being displayed or not
// 
// Arguments:
//	strObjectName: the name of the object to toggle
// 
// Returns:
function toggleDisplay(strObjectName)
{
	// get the object
	var objObject = document.getElementById(strObjectName);
			
	if(objObject){
		// change the display style based on the current display
		if((objObject.style.display=="none") || (objObject.style.display == "")){
			objObject.style.display="block";
		}
		else {
			objObject.style.display="none";
		}
	}
	
	return false;
}

function showObject(strObjectName){
	// get the object
	var objObject = document.getElementById(strObjectName);
	
	// check to see if the object exist
	if(typeof(objObject) == 'undefined'){
		alert("error");
	}
	
	objObject.style.display="block";
	
}

////////////////////////////////////////////////////////////////////////////////
// Function: openPage
////////////////////////////////////////////////////////////////////////////////
// Description: This function causes the users browser to redirect them to a
//	certain page.
// 
// Arguments:
//	strLocation: the URL of the new location
// 
// Returns: nothing
function openPage(strLocation)
{
	if(strLocation != 'undefined'){
		document.location = strLocation;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Function: openPageBackground
////////////////////////////////////////////////////////////////////////////////
// Description: This function causes the users browser to open a page in the 
//	background
// 
// Arguments:
//	strLocation: the URL of the new location
// 
// Returns: nothing
function openPageBackground(strLocation){
	if(strLocation != 'undefined'){
		var objFrame = document.getElementById('hiddenframe');
		
		objFrame.src = strLocation;
		
		return false;
	}
	
	return true;
}

function updateDetailsGraph(strCalled){
	// get the graph image
	var objGraph = document.getElementById('detailsGraphImage');
	
	// get the link to view the larger graph
	var objLink = document.getElementById("detailsGraphLink");
	
	// get the link to save the graph
	var objSave = document.getElementById("detailsSaveLink");
	
	// get the form
	var objForm = document.getElementById('updateGraphForm');
	
	// get the count
	var intCount = objForm.count.value;
	
	var strArgs = "";
	
	var count = 0;
	
	// loop through all the values
	for(value = 0; value < intCount; value++){
		if(objForm.elements["ver"+value].checked){
			strArgs += "rateindex" + count + "=" + objForm.elements["ver"+value].value + "&ver" + count + "=" + value + "&label"+count+"=" + urlencode(objForm.elements["label"+value].value) + "&";
			count++;
		}
	}
	
	// add the number of elements
	strArgs += "count=" + count;
	
	// loop through the points to display
	intCount = objForm.elements["pointsCount"].value;
	for(intI = 0; intI<intCount; intI++){
		// add the X and Y points
		strArgs += "&Xpoint" + intI + "=" + objForm.elements["X"+intI].value;
		strArgs += "&Ypoint" + intI + "=" + objForm.elements["Y"+intI].value;
	}
	
	// add the count of datapoints
	strArgs += "&pointsCount=" + intCount;
	
	// check to see if we need to toggle the value of where the legend is display
	if(objForm.showLegend.checked && strCalled=="showLegendSide"){
		objForm.showLegend.checked = false;
	}
	
	// check to see if the value of where the legend is displayed should be changed
	if(objForm.showLegendSide.checked && strCalled=="showLegend"){
		objForm.showLegendSide.checked = false;
	}
	
	// check to see if the comparison graph should be displayed/updated
	if(objForm.count.value>1){
		document.getElementById("detailsGraphRatePlot").src="graphSetRelative.php?" + strArgs + "&width=320&rateindex=" + objForm.rateindex.value;
		document.getElementById("detailsGraphLinkPlot").href="graphSetRelative.php?" + strArgs + "&width=640&height=480&rateindex=" + objForm.rateindex.value;
	} else {
		document.getElementById("detailsGraphLinkPlot").style.display="none";
	}
	
	// check to see if the inline legend should be displayed
	if(objForm.showLegend.checked){
		strArgs += "&showLegend=1"
	}
	
	// check to see if the side legend should be displayed
	if(objForm.showLegendSide.checked){
		strArgs += "&showLegendSide=1"
	}
	
	// update the image
	objGraph.src="graphSet.php?" + strArgs + "&width=320";
	
	// update the link
	objLink.href = "graphSet.php?" + strArgs + "&width=640&height=480";
	
	var now = new Date();
	
	strFilename = "";
	// add the year
	strFilename += (1900+now.getYear())
	
	// add the month and pad it
	if((now.getMonth()+1)<10){
		strFilename += "0" + (now.getMonth()+1);
	}else{
		strFilename += (now.getMonth()+1);
	}
	
	// add the date and pad it
	if((now.getDate())<10){
		strFilename += "0" + (now.getDate());
	}else{
		strFilename += (now.getDate());
	}
	
	// add the hours and pad it
	if((now.getHours())<10){
		strFilename += "0" + (now.getHours());
	}else{
		strFilename += (now.getHours());
	}
	
	// add the minutess and pad it
	if((now.getMinutes())<10){
		strFilename += "0" + (now.getMinutes());
	}else{
		strFilename += (now.getMinutes());
	}
	
	// add the minutess and pad it
	if((now.getSeconds())<10){
		strFilename += "0" + (now.getSeconds());
	}else{
		strFilename += (now.getSeconds());
	}
	
	// check to make sure objSave is defined
	if(objSave){
		// update the save link
		objSave.href="graphSet.php?" + strArgs + "&width=320&filename="+strFilename;
	}
	
	return true;
}

function updateDisableClick(objElement, strMode, strLoginID, strURL){
	objElement.href="http://www.google.com";
	return false;
}

function updateStatusReaction(){
	// get the form
	var objForm = document.getElementById('reactionAdd');
	
	//get the reaction
	var strRect = objForm.reactionName.value;
	
	var arrA = new Array(6);
	
	arrA[0] = "";
	arrA[1] = "";
	arrA[2] = "";
	arrA[3] = "";
	arrA[4] = "";
	arrA[5] = "";
	
	// use regex to parse it
	var arrParse = /^<sup>0*(\d+)<\/sup>([^\(]+)\(([&\#\w\;]+),([&\#\w\;]+)\)<sup>0*(\d+)<\/sup>(.+)$/.exec(strRect);
	
	// check to see if there was a match
	if(arrParse){
		var str1 = arrParse[2] + '' + arrParse[1];
		var str2 = arrParse[6] + '' + arrParse[5];
		var part1 = arrParse[3];
		var part2 = arrParse[4];
		
		var intCount = 0;
		
		if(part1 == "p"){
			arrA[intCount++] = "p";
			arrA[intCount++] = str1;
		} else if(part1 == "n"){
			arrA[intCount++] = "n";
			arrA[intCount++] = str1;
		} else if ((part1 == "&alpha;") || (part1 == "&#945;")){
			arrA[intCount++] = "he4";
			arrA[intCount++] = str1;
		} else if((part1 == "&gamma;") || (part1 == "&#947;")){
			arrA[intCount++] = str1;
		} else if(part1 == "d"){
			arrA[intCount++] = 'h2';
			arrA[intCount++] = str1;
		} else {
			alert('Unknown part: ' + part1);
		}
		
		//alert(part2);
		
		if(part2 == "p"){
			arrA[intCount++] = "p";
			arrA[intCount++] = str2;
		} else if(part2 == "n"){
			arrA[intCount++] = "nn";
			arrA[intCount++] = str2;
		} else if((part2 == "&alpha;") || (part2 == "&#945;")){
			arrA[intCount++] = "he4";
			arrA[intCount++] = str2;
		} else if ((part2 == "&gamma;") || (part2 == "&#947;")){
			arrA[intCount++] = str2;
		} else if(part1 == "d"){
			arrA[intCount++] = 'h2';
			arrA[intCount++] = str1;
		} else {
			alert('Unknown part: ' + part2);
		}
		
	} else {
		return;
	}
	
	objForm.a1.value = arrA[0];
	objForm.a2.value = arrA[1];
	objForm.a3.value = arrA[2];
	objForm.a4.value = arrA[3];
	objForm.a5.value = arrA[4];
	objForm.a6.value = arrA[5];
	
	updateStatusReactionList();
}

function updateStatusReactionList(){
	var objTemp = document.getElementById('rateSelection');
	objTemp.innerHTML = "Loading...";
	
	var objForm = document.getElementById('reactionAdd');
	
	ajaxRequest('statusadmin.php?action=displayrates&a0='+objForm.a1.value+'&a1='+objForm.a2.value+'&a2='+objForm.a3.value+'&a3='+objForm.a4.value+'&a4='+objForm.a5.value+'&a5='+objForm.a6.value+'&reactionRate='+objForm.rateTemp.value,'rateSelection');
}

function updateNuclideChart(intSearchID){
	document.getElementById('loadingDisplay').style.display="block";
	
	document.getElementById('nuclideChart').src='nuclideChart.php?searchID='+intSearchID+'&rateall=1&' + Math.random() + '&'+(document.NuclideForm.rateType?document.NuclideForm.rateType.value:'')+'&file='+document.NuclideForm.dataFile.value+document.NuclideForm.chapter.value+document.NuclideForm.label.value+document.NuclideForm.library.value;
	
}

function updatePermissionBackground(objInfo, strLocation)
{
	if(objInfo.innerHTML == "Updated"){
		return false;
	}

	if(strLocation != 'undefined'){
	
		// get the frame
		var objFrame = document.getElementById('hiddenframe');
		
		//alert(objInfo.innerHTML);
		objInfo.innerHTML = "Updated";
		objInfo.href="";
		
		//objInfo.parentNode.innerHTML = "Updated...";
		
		if(objInfo.parentNode.className == "permissionGranted"){
			objInfo.parentNode.className = "permissionDenied";
		} else {
			objInfo.parentNode.className = "permissionGranted";
		}
	
		objFrame.src = strLocation;
		return false;
	}
	
	return true;
}

////////////////////////////////////////////////////////////////////////////////
// Function: checkLoginForm
////////////////////////////////////////////////////////////////////////////////
// Description: This function checks to make sure all the input boxes of the
//	login form are set.
// 
// Arguments: nothing
// 
// Returns:
//	true: if everything is ready to go
//	false: otherwise
function checkLoginForm(){
	// get the form
	objForm = document.getElementById("loginForm");
	
	// this variable keeps track to see if there was success
	var bSuccess = true;
	
	
	// check to see if the username field has been entered
	if(objForm.loginid.value.length < 1){
		// indicate that there was a problem with the input
		bSuccess = false;
		
		// show the error 
		objLogin = document.getElementById("errorLoginID");
		objLogin.style.display="block";	
	}
	else{
		// clear the error
		objLogin = document.getElementById("errorLoginID");
		objLogin.style.display="none";	
	}
	
	// check to see if the password field has been entered
	if(objForm.password.value.length < 1){
		// indicate that there was a problem with the input
		bSuccess = false;
		
		// show the error 
		objPassword = document.getElementById("errorPassword");
		objPassword.style.display="block";
	}
	else{
		// clear the error 
		objPassword = document.getElementById("errorPassword");
		objPassword.style.display="none";
	}
	
	return bSuccess;
}

////////////////////////////////////////////////////////////////////////////////
// Function: checkAdvSearch()
////////////////////////////////////////////////////////////////////////////////
// Description: This function checks the advanced search form to see if all the
//	fields are filled out with acceptable data.
// 
// Arguments: nothing
// 
// Returns: 
//	true: if all the fields values are acceptable
//	false: otherwise
function checkAdvSearch(){
	var bReturn = true;
	var strError = "";
	
	// get the form 
	var objForm = document.getElementById("advsearchform");
	
	// regular expressions
	var regExpInt = /^\d+$/;
	var regExpDate = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
	
	// then low a
	// check to see if there is a value
	if(objForm.lowm0.value.length>0){
		// check to see if it fails the regular expression
		if(!regExpInt.test(objForm.lowm0.value)){
			strError += "Low a values must be an integer\n";
		}else{
			// check to see if there is a value
			if(objForm.lowm1.value.length>0){
				// check to see if it fails the regular expression
				if(!regExpInt.test(objForm.lowm1.value)){
					strError += "Low a values must be an integer\n";
				} else {
					// check to see if there is a value
					if(objForm.lowm2.value.length>0){
						// check to see if it fails the regular expression
						if(!regExpInt.test(objForm.lowm2.value)){
							strError += "Low a values must be an integer\n";
						} else {
							// check to see if there is a value
							if(objForm.lowm3.value.length>0){
								// check to see if it fails the regular expression
								if(!regExpInt.test(objForm.lowm3.value)){
									strError += "Low a values must be an integer\n";
								} else {
									// check to see if there is a value
									if(objForm.lowm3.value.length>0){
										// check to see if it fails the regular expression
										if(!regExpInt.test(objForm.lowm3.value)){
											strError += "Low a values must be an integer\n";
										} else {
											// check to see if there is a value
											if(objForm.lowm4.value.length>0){
												// check to see if it fails the regular expression
												if(!regExpInt.test(objForm.lowm4.value)){
													strError += "Low a values must be an integer\n";
												} else {
													// check to see if there is a value
													if(objForm.lowm5.value.length>0){
														// check to see if it fails the regular expression
														if(!regExpInt.test(objForm.lowm5.value)){
															strError += "Low a values must be an integer\n";
														}
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	
	// lastly high a
	// check to see if there is a value
	if(objForm.highm0.value.length>0){
		// check to see if it fails the regular expression
		if(!regExpInt.test(objForm.highm0.value)){
			strError += "High a values must be an integer\n";
		}else{
			// check to see if there is a value
			if(objForm.highm1.value.length>0){
				// check to see if it fails the regular expression
				if(!regExpInt.test(objForm.highm1.value)){
					strError += "High a values must be an integer\n";
				} else {
					// check to see if there is a value
					if(objForm.highm2.value.length>0){
						// check to see if it fails the regular expression
						if(!regExpInt.test(objForm.highm2.value)){
							strError += "High a values must be an integer\n";
						} else {
							// check to see if there is a value
							if(objForm.highm3.value.length>0){
								// check to see if it fails the regular expression
								if(!regExpInt.test(objForm.highm3.value)){
									strError += "High a values must be an integer\n";
								} else {
									// check to see if there is a value
									if(objForm.highm3.value.length>0){
										// check to see if it fails the regular expression
										if(!regExpInt.test(objForm.highm3.value)){
											strError += "High a values must be an integer\n";
										} else {
											// check to see if there is a value
											if(objForm.highm4.value.length>0){
												// check to see if it fails the regular expression
												if(!regExpInt.test(objForm.highm4.value)){
													strError += "High a values must be an integer\n";
												} else {
													// check to see if there is a value
													if(objForm.highm5.value.length>0){
														// check to see if it fails the regular expression
														if(!regExpInt.test(objForm.highm5.value)){
															strError += "High a values must be an integer\n";
														}
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	
	// check to make sure any dates are in the correct format
	if(objForm.startdate.value.length >0){
		if(!regExpDate.test(objForm.startdate.value)){
			strError += "The start date must be in the format mm/dd/yyyy.\n"
		}
	}
	
	// check to make sure any dates are in the correct format
	if(objForm.enddate.value.length >0){
		if(!regExpDate.test(objForm.enddate.value)){
			strError += "The end date must be in the format mm/dd/yyyy.\n"
		}
	}
	
	if(strError.length >0){
		bReturn = false;
		alert(strError);
	}
	
	return bReturn;
}

function hideSidebar(){
	document.getElementById("helpSidebarInfo").style.display="none";
	document.getElementById("tohidehelpsidebar").style.display="none";
	
	document.getElementById("hidehelpsidebar").innerHTML = '<a href="#" onClick="return showSidebar()">[Show]</a>';

	// set a cookie so this isn't displayed anymore
	setCookie("sidedisplayed","false",90);
	return false;
}

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function showSidebar(){
	document.getElementById("helpSidebarInfo").style.display="none";
	document.getElementById("tohidehelpsidebar").style.display="block";
	
	document.getElementById("hidehelpsidebar").innerHTML = '<a href="#" onClick="return hideSidebar()">[Hide]</a>';
	
	// set a cookie so this is displayed 
	setCookie("sidedisplayed","true",90);

	return false;
}

////////////////////////////////////////////////////////////////////////////////
// Function: MM_jumpMenu
////////////////////////////////////////////////////////////////////////////////
// Description: ??? This appears to have been taken from Dreamweaver but I don't
// know what it does
// 
// Arguments:???
// 
// Returns:???
function MM_jumpMenu(targ,selObj,restore){ //v3.0
	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	if (restore) selObj.selectedIndex=0;
}

function typeChange(selObj, strArea) {
	// get the display object
	var objArea = document.getElementById(strArea);
	
	// check to see if the value is higher
	if(selObj.options[selObj.selectedIndex].value != -50){
		objArea.style.display = "none";
	} else {
		objArea.style.display = "";
	}
	
}

function checkPostForm()
{
	// get the form 
	objForm = document.getElementById("postMessageForm");
	
	// this keeps track of any error state
	bSuccess = true;
	error = "";
	
	// check to make sure there is a name
	if(objForm.messageName.value.length<=0){
		bSuccess = false;
		error = error + "Name is a required value.\n";
	}
	
	// check to make sure there is an e-mail address
	if(objForm.messageEmail.value.length<=0){
		bSuccess = false;
		error = error + "Email is a required value.\n";
	}
	
	// check to make sure there is a post
	if(objForm.messagePost.value.length<=0){
		bSuccess = false;
		error = error + "The message is a required value.\n";
	}
	
	// if there is an error string report the error to the user
	if(error.length>0){
		alert(error);
	}
	
	return bSuccess;
	
}

////////////////////////////////////////////////////////////////////////////////
// Function: checkAddNewsItem()
////////////////////////////////////////////////////////////////////////////////
// Description: This checks to make sure that all the fields in the form that 
//	allows a user to create a new news item are filled out correctly.
// 
// Arguments: none
// 
// Returns:
//	true: all the form's fields are filled our correctly
// 	flase: otherwise
function checkAddNewsItem(){
	// get the form 
	objForm = document.getElementById("addNewsItem");
	
	bSuccess = true;
	strErrors = "";
	
	// check to see if there is a title
	if(objForm.newsTitle.value.length<1){
		strErrors = strErrors + "The title is a required value\n";
		bSuccess = false;
	}
	
	// check to see if there is information
	if(objForm.newsInfo.value.length<1){
		strErrors = strErrors + "The information is a required value\n";
		bSuccess = false;
	}
	
	// check to see if there were any errors
	if(strErrors.length>0){
		alert(strErrors);
	}
	
	return bSuccess;
}

////////////////////////////////////////////////////////////////////////////////
// Function: checkAddUserForm
////////////////////////////////////////////////////////////////////////////////
// Description: This function is called when the user attempts to submit a new
// user account information.
// 
// Arguments: none
// 
// Returns: nothing
function checkAddUserForm(){
	// get the form
	var objForm = document.getElementById('newUserForm');
	
	var bSuccess = true;
	var strError = "";
	
	var strEmailReg = /^.+@[^\.].*\.[a-z]{2,}$/;
	
	// check to make sure the user has entered a requested username
	if(objForm.username.value == ""){
		bSuccess = false;
		strError = strError + "Enter a username.\n";
	}
	
	// check to make sure the first name is entered
	if(objForm.first.value == ""){
		bSuccess = false;
		strError = strError + "Enter your first name.\n";
	}
	
	// check to make sure the last name is entered
	if(objForm.last.value == ""){
		bSuccess = false;
		strError = strError + "Enter your last name.\n";
	}

	// check to see if the emails have been filled out
	if (objForm.email1.value == "" || objForm.email2.value == "") {
		bSuccess = false;
		strError = strError + "Enter both e-mail addresses.\n";
	} else {
		// check to see if the e-mail address is a valid e-mail address
		if (!strEmailReg.test(objForm.email1.value)) {
			bSuccess = false;
			strError = strError + "Enter a valid e-mail address.\n";
		} else {
			// check to see if the e-mail address's match
			if(objForm.email1.value != objForm.email2.value){
				bSuccess = false;
				strError = strError + "The e-mail address are different.\n";
			}
		}
	}
	
	// check to make sure the password is entered
	if(objForm.password1.value == "" || objForm.password2.value == ""){
		bSuccess = false;
		strError = strError + "Enter both passwords.\n";
	} else {
		// check to make sure the password match up
		if(objForm.password1.value != objForm.password2.value){
			bSuccess = false;
			strError = strError + "The passwords are different.\n";
		}
	}
	
	
	// check to see if there was an error
	if(strError != ""){
		alert(strError);
	}
	
	return bSuccess;
}

////////////////////////////////////////////////////////////////////////////////
// Function: switchMenu
////////////////////////////////////////////////////////////////////////////////
// Description: This function is called when the user clicks on a sub item in 
//	the main menu.  It hides all the menus and then displays the one that was
// clicked
// 
// Arguments:
//	strObjectName: This is the name of the object that should be displayed.
// 
// Returns: nothing
function switchMenu(strObjectName){

	// set all the subs to hidden
	for(var i=1;i<5;i++){
		// get the current sub
		var objObjectHide = document.getElementById("sub" + i);
		
		// check to make sure it was retrieved
		if(objObjectHide){
			// hide it
			objObjectHide.style.display="none";
		}
		
		
	}

	// show the selected object
	toggleDisplay(strObjectName);
	
	// set a cookie to tell what is displayed
	document.cookie = "displayed=" + strObjectName;
}

////////////////////////////////////////////////////////////////////////////////
// Function: checkNewPasswordForm
////////////////////////////////////////////////////////////////////////////////
// Description: This function checks to make sure the values for the new
//	password are filled out correctly.
// 
// Arguments: nothing
// 
// Returns:
//	true: all the forms fields are filled out correctly
//	false: otherwise
function checkNewPasswordForm(){
	var strErrors = "";
	var bSuccess = true;
	
	// get the form 
	var objForm = document.getElementById("newPasswordForm");
	
	// check to see if the new password has enough characters
	if(objForm.newpass1.value.length<6){
		strErrors += "Your new password must be at least six characters long.\n"
	}
	
	// check to make sure the old password and the new password are the same
	if(objForm.newpass1.value != objForm.newpass2.value){
		strErrors += "Your new password and the confirming value are different.\n";
	}
	
	if(strErrors.length>0){
		alert(strErrors);
		bSuccess= false;
	}
	
	return bSuccess;
}



function checkAddLabelBox(){
	// the list of errors
	strErrors = "";
	
	// get the form
	var objForm = document.getElementById("addLabelBox");
	
	// check to see if we are okayed to submit
	if(objForm.checked.value==0){		  	 
		strErrors = document.getElementById("labelCheckText").innerHTML;
	}
	
	if(strErrors.length > 0){
		alert(strErrors);
		return false;
	}
	
	return true;
}

////////////////////////////////////////////////////////////////////////////////
// Function: checkForm
////////////////////////////////////////////////////////////////////////////////
// Description: This function checks to see that all the values in the form are valid
// 
// Arguments: 
// 	objForm: the form to check
// 
// Returns: nothing
var regExpDate = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
var regExpNuc = /([A-Za-z]{1,2}|\d{1,3})/;
function checkForm(objForm){	
	// a listing of the errors
	var strErrors = "";
	
	// a listing of the elements that have been checked
	// this is used to keep track of arrays that all wrong
	var strDone = "";
	
	// loop through all the child elements
	for(i = 0; i<objForm.elements.length; i++){
		// check to see if the class name has been defined
		if(objForm.elements[i].className != '') {
			// get the value
			var strValue = objForm.elements[i].value;
			
			// check to see if the element has a value
			if(strValue.length > 0){
				// get the name of the class
				var strName = objForm.elements[i].className;
				
				// the check to see if there was an error
				var bErr = false;
				
				// check to see what this element is
				if(strName == ""){
					// ignore this case
				} else if(strName == "dateInput"){
					// check to see if this is a valid date
					if(!regExpDate.test(strValue)) {
						bErr = true;
					}
				} else if(strName == "nucInput"){
					// check to see if this is a valid nuc
					if(!regExpNuc.test(strValue)) {
						bErr = true;
					}
				} else if(strName == "intInput") {
					// check to see if this is a valid integer
					if(!/\d+/.test(strValue)){
						bErr = true;
					}
				} else {
					strErrors += "Unhandled class: " + strName + "\n";
				}

				// check to see if there was a problem with this entry and if it should be displayed
				if((bErr) && (strDone.indexOf(objForm.elements[i].name)<0)){
					// get the error and add it to the listing
					strErrors += getInnerHTML(objForm.elements[i].name + 'errorText') + '\n';
					
					// remember that we have already checked this element
					strDone += " " + objForm.elements[i].name;
				}
				
			}
		}
	}
	
	// check to see if there were any errors
	if(strErrors != ""){
		// display the alerts
		alert(strErrors);
		return false;
	}	
	
	// allow the script to return
	return true;
}

////////////////////////////////////////////////////////////////////////////////
// Function: checkLabel
////////////////////////////////////////////////////////////////////////////////
// Description: This function use AJAX to check to see if the label is unique
// 
// Arguments: 
// 	strValue: this performs a query to check to see if the first 4 characters are unique.
// 
// Returns: nothing
var xmlHttp;
function checkLabel(strValue){
	xmlHttp = GetXmlHttpObject();
	if(xmlHttp == null){
		document.getElementById("labelCheck").innerHTML="<div id=labelCheckText>AJAX not supported</div> <input type=hidden name=checked value=0>";
		return;
	}
	
	var strUrl = "checkLabel.php?label="+strValue;
	xmlHttp.onreadystatechange=checkLabelUpdated;
	xmlHttp.open("GET",strUrl, true);
	xmlHttp.send(null);	
}

function checkLabelUpdated(){
	if(xmlHttp.readyState==4){
		document.getElementById("labelCheck").innerHTML=xmlHttp.responseText;
	}
}

// taken from w3schools.com
function GetXmlHttpObject()
{
  var xmlHttp=null;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
  return xmlHttp;
}

function viewHelpTopic(intID){
	xmlHttp = GetXmlHttpObject();
	
	showObject("helpSidebarInfo");
	
	// check to see if the xmlHttp object was shown
	if(xmlHttp == null){
		document.getElementById("helpSidebarText").innerHTML="Your browser does not support AJAX";
		return false;
	}
	
	// show that the document is loading
	document.getElementById("helpSidebarText").innerHTML="Loading...";
	
	// create the query
	var strUrl = "help.php?action=sidebar&topicID=" + intID;
	
	// perform the query
	xmlHttp.onreadystatechange = viewHelpTopicUpdate;
	xmlHttp.open("GET", strUrl, true);
	xmlHttp.send(null);
	
	return false;
}

function viewHelpTopicUpdate(){
	if(xmlHttp.readyState==4){	
		document.getElementById("helpSidebarText").innerHTML=xmlHttp.responseText;
	}
}

function fixEmailAddr(objText){
	var strEmail = objText.innerHTML;
	
	// get just the email field
	strEmail = strEmail.replace(/ \(.+\)/,"")

	var strTemp = "";
	// loop through the values
	for(i = strEmail.length-1; i>=0; i--){
		strTemp += strEmail.charAt(i);
	}
	
	strEmail = strTemp.replace(/ at /i,'@').replace(/ dot /gi, '.');
	
	objText.innerHTML = '<a href="mailto:' + strEmail + '">' + strEmail + '</a>'
}

function generateTextFile(strAction){
	// get the form
	var objForm = document.getElementById("textFileGenForm");
	
	// check to see if 9 and 10 values should be displayed
	if(objForm.no910.checked){
		var no910=1;
	} else {
		var no910=0;
	}
	
	// open the window
	window.open('difout.php?action='+strAction+'&searchID='+objForm.searchID.value+'&no910='+no910,'test','left=20,top=20,width=500,height=50,toolbar=0,resizable=0');
	
	return false;
}

function openwindow(strUrl, strOptions){
	window.open(strUrl,'test',strOptions);
}


function urlencode(strValue){
	strValue = strValue.replace(/\+/g, "%2B");
	strValue = strValue.replace(/\//g, "%2F");
	strValue = strValue.replace(/:/g, "%3A");
	strValue = strValue.replace(/&/g, "%26");
	strValue = strValue.replace(/\'/g, "%27");
	strValue = strValue.replace(/\"/g, "%22");
	strValue = strValue.replace(/,/g, "%2C");
	strValue = strValue.replace(/[\r\f\n]/g, "%0D");
	return strValue;
}

////////////////////////////////////////////////////////////////////////////////
// Function: getInnerHTML
////////////////////////////////////////////////////////////////////////////////
// Description: This function gets the inner HTML from an object
// 
// Arguments: 
// 	strID: The id of the object to get the information from 
// 
// Returns: the inner html of the object
function getInnerHTML(strID){
	// get the object
	var objObject = document.getElementById(strID);
	
	// check to see if something was returned
	if(objObject == undefined){
		return 'Unable to find '+strID+'.';
	}
	
	return objObject.innerHTML;
}