// JavaScript Document

var normalBackgroundColor = "#FFFFF0";

// provides an on-page log of debugging messages
function Loggit(msg) {
	return;
	// fix this to dynamically add the traceLog textarea field to pages that don't already have it defined.
	document.forms[0].traceLog.value += "\n" + msg;
}

//hides status bar
function hidestatus(){
window.status=''
return true
}

// returns true if the named form field is found to be present in the named form
function ThisFormFieldIsPresent(form, fieldName) {
	for (var i=0; i < form.elements.length; i++) {
		if ( form.elements[i].name == fieldName )		
			return true;
	}
	return false;
}

var errorMessages = ""
var errMessageCount = 0
function RegisterErrorMessage(argMsg) {
	LogMessage("RegisterErrorMessage: entered.")
	if (errorMessages.length > 0) {
		errorMessages += "\n---------------------------------------------------------------------------------------------------------------------\n"
	}
	errorMessages += argMsg
	errMessageCount++
	LogMessage("RegisterErrorMessage: finished.  " + errMessageCount + " messages queued.")
	//alert("errorMessages is " + errorMessages.length + " long and contains " + errorMessages)
} //RegisterErrorMessage

function DisplayErrorMessages() {
	LogMessage("DisplayErrorMessages: We have " + errMessageCount  + " messages queued.")
	LogMessage("DisplayErrorMessages:------- start of message ------- \n" + errorMessages )
	LogMessage("DisplayErrorMessages:------- end of message ------- ")
	if (errorMessages.length > 0) { 
		LogMessage("DisplayErrorMessages: now displaying the alert window.")
		alert(errorMessages)
		LogMessage("DisplayErrorMessages: user just dismissed the alert window.")
		errorMessages = ""
		errMessageCount = 0
	}
} //DisplayErrorMessages

function DisplayErrorMessagesAsynchronously() {
	setTimeout('DisplayErrorMessages()', 10)
} //DisplayErrorMessagesAsynchronously


function PrettyDate(MM, DD, YYYY) {
	var Months = new Array("", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") ;
	return Months[MM] + " " + DD + ", " + YYYY ;
}


var ValidationIsUnneeded = 1
var ValidationIsPending    = 2
var ValidationIsComplete  = 3
var ValidationHasFailed    = 4

function GetValue(fldName) {
	return eval("document.mainForm." + fldName + ".value")
}

function SetBackgroundColor(fldName, color) {
	eval("document.mainForm." + fldName + ".style.backgroundColor='" + color + "'")	
}

function SetRowValidationStatusToUnneeded(rowNumber, strCaller) {
	//alert("Setting row " + rowNumber + "'s validation status to Unneeded from " + strCaller)
	eval( "document.mainForm.ValidatedStatus" + rowNumber + ".value = ValidationIsUnneeded" )
}
function SetRowValidationStatusToPending(rowNumber, strCaller) {
	//alert("Setting row " + rowNumber + "'s validation status to Pending from " + strCaller)
	eval( "document.mainForm.ValidatedStatus" + rowNumber + ".value = ValidationIsPending" )
}
function SetRowValidationStatusToComplete(rowNumber, strCaller) {
	//alert("Setting row " + rowNumber + "'s validation status to Complete from " + strCaller)
	eval( "document.mainForm.ValidatedStatus" + rowNumber + ".value = ValidationIsComplete" )
}
function SetRowValidationStatusToHasFailed(rowNumber, strCaller) {
	//alert("Setting row " + rowNumber + "'s validation status to HasFailed from " + strCaller)
	eval( "document.mainForm.ValidatedStatus" + rowNumber + ".value = ValidationHasFailed" )
}



function SetRowValidationStatus(strStatusFlag) {
	LogMessage("in SetRowValidationStatus for row " + this.rowNumber + "(" + strStatusFlag + ")")
	eval( "document.mainForm.ValidatedStatus" + this.rowNumber + ".value = '" + strStatusFlag + "'" )
}

function ValidationCheckIsStartingForThisRow() {
	eval( "document.mainForm.ValidationCheck" + this.rowNumber + ".value = 'starting' " )
}

function ValidationCheckIsCompleteForThisRow() {
	eval( "document.mainForm.ValidationCheck" + this.rowNumber + ".value = 'complete' " )
}



var StartDateObject = new Date() 
var StartingTime = StartDateObject.getTime()
function GetCurrentTimestamp() {
	var nowDateObject = new Date()
	return nowDateObject.getTime()
}

var log = "Starting at " + parseInt(GetCurrentTimestamp()) - parseInt(StartingTime)
function logTime(eventName) {
	log += "\n" + eventName + " :: " + parseInt(GetCurrentTimestamp()) - parseInt(StartingTime)
	alert(log)
}


if (document.layers)
document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT)

document.onmouseover=hidestatus
document.onmouseout=hidestatus

function toHex(dec) {
	hexChars = "0123456789ABCDEF"
	if (dec > 255) {
		return null;
	}
	var i = dec % 16
	var j = (dec - i) / 16
	result = "0X"
	result += hexChars.charAt(j)
	result += hexChars.charAt(i)
	return result
}

var LetterArray = [ "A", "B", "C", "D", "E", "F","G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
var LetterArrayUpperBound = 25

var constSystemType_JRE_Standalone = 1

// Validates the argument to be alphabetic characters, plus a few punctuation chars
var letters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.-,\n* ";
var lettersNumberPlusPunctuation="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'’`!@#$%^&*()_+=.-,\t\n?/\\{}[]<>|:; " + '"';
function isAlpha(c) {
	// is c a String or a character?
	if(c.length>1) {
	  for(j=0;j<c.length;j++) {
			// call isAlpha recursively for each character
			alpha=isAlpha(c.substring(j,j+1));
			if(!alpha) return alpha;
	  }
	  return alpha;
	}
	else {
		// if c is alpha return true
	  if(letters.indexOf(c)>=0) return true;
	  return false;
	}
}

var LettersOnly="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
function isPureAlpha(c) {
	// is c a String or a character?
	if(c.length>1) {
	  for(j=0;j<c.length;j++) {
			// call isAlpha recursively for each character
			alpha=isPureAlpha(c.substring(j,j+1));
			if(!alpha) return alpha;
	  }
	  return alpha;
	}
	else {
		// if c is alpha return true
	  if(LettersOnly.indexOf(c)>=0) return true;
	  return false;
	}
}

var HexDigits="0123456789ABCDEFabcdef";
function isHexDigit(c) {
	// is c a String or a character?
	if(c.length>1) {
	  for(j=0;j<c.length;j++) {
			// call isAlpha recursively for each character
			alpha=isHexDigit(c.substring(j,j+1));
			if(!alpha) return alpha;
	  }
	  return alpha;
	}
	else {
		// if c is hex return true
	  if(HexDigits.indexOf(c)>=0) return true;
	  return false;
	}
}

function Mid(str, start, len)
/***
				IN: str - the string we are LEFTing
						start - our string's starting position (0 based!!)
						len - how many characters from start we want to get

				RETVAL: The substring from start to start+len
***/
{
				// Make sure start and len are within proper bounds
				if (start < 0 || len < 0) return "";

				var iEnd, iLen = String(str).length;
				if (start + len > iLen)
								iEnd = iLen;
				else
								iEnd = start + len;

				return String(str).substring(start,iEnd);
}

function InStr(strSearch, strSearchFor)
/*
InStr(strSearch, strSearchFor) : Returns the first location a substring (SearchForStr)
                           was found in the string str.  (If the search string is not
                           found, -1 is returned.)
*/
{
	alert("Searching for the string\n\n" + strSearchFor + " \n\nin the string\n\n" + strSearch + "\n\n\n" +
				"In InStr, string to search length is " + String(strSearch).length + " and search arg length is " + String(strSearchFor).length)
	
	strSearch.indexOf(strSearchFor)
	
	for (i=0; i <= String(strSearch).length - String(strSearchFor).length; i++)
	{
	    if (strSearchFor == Mid(strSearch, i, String(strSearchFor).length))
	    {
			return i;
	    }
	}
	return -1;
}

function isCharacter(c) {
	// is c a String or a character?
	if(c.length>1) {
	  for(j=0;j<c.length;j++) {
			// call isAlpha recursively for each character
			character=isCharacter(c.substring(j,j+1));
			if(!character) return character;
	  }
	  return character;
	}
	else {
		// if c is character return true
		//alert("processing the character '" + c + "', or in decimal, " + c.charCodeAt())
		if(lettersNumberPlusPunctuation.indexOf(c)>=0) return true;
		if (c.charCodeAt() == 13 || c.charCodeAt() == 10) return true;
		//alert("choking on a " + c.charCodeAt())
	  return false;
	}
}

var EmailBadCharsMsgs, EmailAddressIsGood;
// Validates a string to contain valid email characters.
var ValidEmailAddressCharacters="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@$-.";
function CheckStringForValidEmailAddressCharacters(c) {
	// is c a String or a character?
	if(c.length>1) {
	  for(j=0;j<c.length;j++) {
		// call isAlphaEmail recursively for each character
		valid = CheckStringForValidEmailAddressCharacters( c.substring(j,j+1) );
		if (EmailAddressIsGood && !valid) {
			EmailAddressIsGood = false;
		}
	  }
	  return EmailAddressIsGood;
	}
	else {
	  // if c is valid return true
	  if( ValidEmailAddressCharacters.indexOf(c) >= 0 ) {
	  	return true;
	  }
	  else {
	  	if (EmailBadCharsMsgs.length > 0) {
	  	  EmailBadCharsMsgs += ', '
		}
		if (c == ' ') {
		  EmailBadCharsMsgs += 'a space';
		}
	    else { 
		  EmailBadCharsMsgs +=  c;
		}
	     return false;
      }
	}
}

function isEmailAddressValid(c, addressType) {
	var posAtSign, posLastDot, allCharactersAreValid;
	EmailAddressIsGood = true; //optimistically assume the best
	
	var strC = new String(c);
	var probstringLength = valProblems.length;
	EmailBadCharsMsgs = '';
	posAtSign = strC.indexOf('@');
	posLastDot = -1;
	if (posAtSign >= 0) {
		posLastDot=strC.indexOf('.', posAtSign)
	}
	
    allCharactersAreValid = CheckStringForValidEmailAddressCharacters(c);
	if ( !allCharactersAreValid || posAtSign<0 || posLastDot<0 ) {
		valProblems += "\n\nThe " + addressType + " email address '" + c + "' is invalid.";
		if ( !allCharactersAreValid ) {
			valProblems +=  "\n >>>  The following illegal character";
			if ( EmailBadCharsMsgs.length > 1)
				valProblems += "s were found: ";
			else
				valProblems += " was found: " ;
			valProblems +=  EmailBadCharsMsgs;
		}
		if ( posAtSign < 0 ) 
			valProblems += "\n >>>  The '@' character is missing.";
		else
			if ( posLastDot < 0)
				valProblems += "\n >>>  There is no period following the '@', as in '.com' or '.army.mil'";
		if (probstringLength < valProblems.length) {
			valProblems += '\n';
		}
		return false;
	}
	else
		return true;
}

// Validates a string to contain valid decimal numeric characters.
var Numbers="0123456789";
function isNumeric(c) { 
	// is c a String or a character?
	if(c.length>1) {
	  for(j=0;j<c.length;j++) {
		// call isNumeric recursively for each character
		numeric=isNumeric(c.substring(j,j+1));
		if(!numeric) return numeric;
	  }
	  return numeric;
	}
	else {
	  // if c is numeric return true
	  if(Numbers.indexOf(c)>=0) return true;
	  return false;
	}
}


// Validates a string to contain valid zipcode characters.
var NumbersPlusDash="0123456789-";
function isZipCode(c) {
	// is c a String or a character?
	if(c.length>1) {
	  for(j=0;j<c.length;j++) {
		// call isNumeric recursively for each character
		numeric=isZipCode(c.substring(j,j+1));
		if(!numeric) return numeric;
	  }
	  return numeric;
	}
	else {
	  // if c is numeric or a dash return true
	  if(NumbersPlusDash.indexOf(c)>=0) return true;
	  return false;
	}
}

function RemoveThisClassFromObject(strClassToRemove, objObject) {
//alert("got to RemoveThisClassFromObjectByID(" + strClassToRemove + ", " + strID + ")");
	var lengthOfClassToRemove = strClassToRemove.length;
	var lengthOfOriginalClassString = objObject.className.length;
  var posOfClassToRemove =  objObject.className.indexOf(strClassToRemove);

//alert("1\n\nClass to remove: '" + strClassToRemove + "'" +
//	   "\nClass string from which to remove it: '" + document.getElementById(strID).className +"'" +
//	   "\nlengthOfClassToRemove = " + lengthOfClassToRemove +
 //      "\nlengthOfOriginalClassString = " + lengthOfOriginalClassString +
//	   "\nposOfClassToRemove = " + posOfClassToRemove);
	var strNewClassSet;
	if (posOfClassToRemove == -1) {
		//alert('1');

		//alert('The resulting Class setting for object of ID=' + strID + ' is now\n' +
//"'" + document.getElementById(strID).className + "', whose length is now " + 
//document.getElementById(strID).className.length); 

		return;  //not there, so we can't remove it.
	}
	if ( posOfClassToRemove == 0 ) {		
		//the class name we wish to remove resides at the beginning of the class string
		//Maybe the one we want to remove is the only one there. If so, just null the
		//string
		//alert('2');
		if (objObject.className == strClassToRemove) {
			//alert('3');
			objObject.className = "";
			//alert('4');
			return;
		}
		else {
			//alert('5');
			//it's the first class name in there, but not the only one, so
			//reset the string to it's present content with the undesired 
			//class name trimmed off.
			objObject.className = objObject.className.substr(lengthOfClassToRemove+1);
			//alert('6');
			return;
		}	
	}
	
	//So, the class name isn't at the front of the string.  Build up a string 
	//thoat omits it from the current class, then assign that back in.
	//This gets the part before the one to be omitted.
//alert('7');
	strNewClassSet =  objObject.className.substr(0, posOfClassToRemove-1);
//alert('8');
	if ( posOfClassToRemove + lengthOfClassToRemove - 1 == lengthOfOriginalClassString) {
//alert('9');
		//if true, the class to remove is at the end of the string, so the new
		//class set is just everything up to, and not including the one to be
		//removed.
		strNewClassSet =  objObject.className.substr(0, posOfClassToRemove-1);
//alert('10');
	}
	else {
		//there's more stuff following the part we're removing, so we have to
		//join together the part before it and the part after it.
		//This gets the part before:
//alert('11');
		strNewClassSet =  objObject.className.substr(0, posOfClassToRemove-1);
		//This gets the part after:
//alert('12');
		strNewClassSet += " " +
			objObject.className.substr(
			   posOfClassToRemove+lengthOfClassToRemove, 
			   lengthOfOriginalClassString-(posOfClassToRemove+lengthOfClassToRemove) );
	}
	//alert("class string before mod was:" + document.getElementById(strID).className + "\nand after, it will be:" + strNewClassSet);
	objObject.className = strNewClassSet;
//alert('13 - made it all the way through');
}

function AddThisClassToObject(strClassToAdd, objObject) { 
	//alert('Entered AddThisClassToObject')
	var identity
	identity = objObject
	if ( identity.className.indexOf(strClassToAdd) == -1 ) {
		if (identity.className.length == 0) {
	    //if it's the first class name in the string, don't include 
			//separator space.
			//alert('determined that ' + strClassToAdd +' wasn\'t there already' + '\nthe classname length is ' + identity.className.length);
			identity.className += strClassToAdd;
		}
		else {
			//if other classes are present, include a space before the 
			//additional class name
			identity.className += " " + strClassToAdd;
		}
	}
	//alert('The resulting Class setting is now\n' + "'" + identity.className + "', whose length is now " + identity.className.length); 
}


function AddThisClassToObjectByID(strClassToAdd, strID) { 
	var identity
	identity = document.getElementById(strID);
	AddThisClassToObject( strClassToAdd, identity );
}

function AddThisClassToObjectByName(strClassToAdd, strName) { 
	//alert("Entered AddThisClassToObjectByName('" + strClassToAdd + "', '" + strName + "')")
	var identity
	identity = eval("document.mainForm." + strName );
	AddThisClassToObject( strClassToAdd, identity );
}

function RemoveThisClassFromObjectByID(strClassToAdd, strID) { 
	var identity
	identity = document.getElementById(strID);
	RemoveThisClassFromObject( strClassToAdd, identity );
}

function RemoveThisClassFromObjectByName(strClassToAdd, strName) { 
	var identity
	identity = eval( "document.mainForm." + strName );
	RemoveThisClassFromObject( strClassToAdd, identity );
}

function MarkAsIncorrectByID(strID) {
	AddThisClassToObjectByID( "InError", strID );
}
function MarkAsIncorrectByName(strName) {
	//alert("Entered MarkAsIncorrectByName('" + strName + "')")
	AddThisClassToObjectByName( "InError", strName );
}

function MarkAsCorrectByID(strID) {
	RemoveThisClassFromObjectByID( "InError", strID );
}
function MarkAsCorrectByName(strName) {
	RemoveThisClassFromObjectByName( "InError", strName );
}
				
function HighlightInYellow(strID) {
	//alert("in HighlightInYellow for ID '" + strID +"'")
	AddThisClassToObjectByID( "InError", strID );
}

function RemoveHighlight(strID) {
	//alert("in RemoveHighlight for ID '" + strID +"'")
	RemoveThisClassFromObjectByID( "InError", strID );
}

function setRowBackgroundClasses(ID_OfTableToProcess) {
	var msg = '' ;
	var visibleRowCount = 0;
	var table = document.getElementById(ID_OfTableToProcess) ;
	// enumerate the rows of this table
	for (var i=0; i<table.rows.length; i++) {
		var row = table.rows[i] ;
		if ( row.style.display != 'none' && row.style.visibility != 'hidden' ) {
			visibleRowCount++ ; 
			RemoveThisClassFromObject('RowEven', row) ;
			RemoveThisClassFromObject('RowOdd', row) ;
			if ( visibleRowCount%2 == 1) {
				AddThisClassToObject('RowOdd', row)
			}
			else {
				AddThisClassToObject('RowEven', row)
			}
		}
	}
}		


function verifyNotEmpty(argNameOfField, argErrorMsg) {//alert('in verifyNotEmpty for ' + argNameOfField );
	var objField = eval( 'document.mainForm.' + argNameOfField);
	if ( objField.value.length == 0 ) {
		valProblems += "\n" + argErrorMsg;
		MarkAsIncorrectByName( argNameOfField );
		return false;
	}
	else {
		MarkAsCorrectByName( argNameOfField );
		return true;
	}
}

function verifyDropDownSelected(argNameOfField, argErrorMsg) {//alert('in verifyDropDownSelectedfor ' + argNameOfField);
	var objField = eval( 'document.mainForm.' + argNameOfField);
	if ( objField.value == 0 ) {
		valProblems += "\n" + argErrorMsg;
		MarkAsIncorrectByName( argNameOfField );
		return false;
	}
	else {
		MarkAsCorrectByName( argNameOfField );
		return true;
	}
}


function manageJRE_ClientRunsRemotelyFields() {
	if (document.mainForm.bClientRunningOnServer[0].checked )
	{ 
		document.getElementById('RemoteClientRow1').style.display = 'none';
		document.getElementById('RemoteClientRow2').style.display = 'none';
		document.getElementById('RemoteClientRow3').style.display = 'none';
		document.mainForm.ClientComputerType_ID.value = '0';
		document.mainForm.UserSuppliedClientComputerCPU.value = '';
		document.mainForm.UserSuppliedClientComputerRAM.value = '';
		
	}
	else
	{
		document.getElementById('RemoteClientRow1').style.display = '';  //table-row';
		document.mainForm.ClientComputerType_ID.focus();
	}
} // end of manageJRE_ClientRunsRemotelyFields

function manageJRE_ClientOtherHardwareRows() {
	if (document.mainForm.ClientComputerType_ID.value == 3  )
	{ 
		document.getElementById('RemoteClientRow2').style.display = '';  //table-row';
		document.getElementById('RemoteClientRow3').style.display = '';  //table-row';
		document.mainForm.UserSuppliedClientComputerCPU.focus();
	}
	else
	{ 
		document.getElementById('RemoteClientRow2').style.display = 'none';
		document.getElementById('RemoteClientRow3').style.display = 'none';
		document.mainForm.UserSuppliedClientComputerCPU.value = '';
		document.mainForm.UserSuppliedClientComputerRAM.value = '';
	}
} // end of manageJRE_ClientOtherHardwareRows

function manageJRE_DeployTypeSerialNumberRow() {
	if (document.mainForm.JRE_DeploymentType_ID[0].checked ) //JRE alone
	{ 
			document.getElementById('DeploymentSerialNumberRow').style.display = 'none';
			document.mainForm.DeploymentSerialNumber.value = '';
	}
	else
	{ 
		if (document.mainForm.JRE_DeploymentType_ID[1].checked ) 
		{
			document.getElementById('DeploySerialNumLabel').innerHTML = 'JTEP Serial Number';
		}
		else if (document.mainForm.JRE_DeploymentType_ID[2].checked ) 
    {
			document.getElementById('DeploySerialNumLabel').innerHTML  = 'ACEP Serial Number';
		}
		document.getElementById('DeploymentSerialNumberRow').style.display = '';  //table-row';
		document.mainForm.DeploymentSerialNumber.focus();
	}

} // end of manageJRE_DeployTypeSerialNumberRow

function manageAdditionalResourcesField() {
	if (document.mainForm.bProblemEscalated[1].checked )
	{ 
		document.getElementById('AdditionalResourcesRow').style.display = '';  //table-row';
		document.mainForm.AdditionalResources.focus();
	}
	else
	{ 
		document.getElementById('AdditionalResourcesRow').style.display = 'none';
		document.mainForm.AdditionalResources.value = '';
	}
} // end of manageAdditionalResourcesField

function leftTrim(sString) {
	while (sString.substring(0,1) == ' ') 	{
		sString = sString.substring(1, sString.length);
	}
	return sString;
}

function rightTrim(sString) {
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function trimAll(sString) {
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

