//
// core_validate.js - (C) 2007, 2008 The Whole Brain Group, LLC.
//

<!--

	
/*------------------------------------------------------------------------------
    form validation

    usage: <form ... onSubmit="return isFormComplete(this);">

    given an html form

    returns false if there is any problem (after displaying an alert message)
    returns true otherwise

    notes:
    - This takes advantage of the "user-defined parameters" feature allowed in
      IE5+ and NS6+ (e.g., the 'altname' here and 'req' in the validation functions).
      These do not work in earlier browsers. They are case-sensitive, so make sure
      the element.property used in the code matches the property="value" in the html
      (e.g., theElement.altname references altname="Gender" but not ALTname="Gender").

    - The validation functions can be modified to include any parameters necessary.
      For example, you could have a format parameter (format='date' or format='ssn')
      that forced an input element into a particular format.
*/

var theHostFileName = document.URL; //hostname and path to filename
var thePieces = theHostFileName.split('/'); // split into an array chuncked on '/'
var theHostNamePieces = new Array(); //create new var as hostname only
theHostNamePieces[0] = thePieces[0];
theHostNamePieces[1] = thePieces[1];
theHostNamePieces[2] = thePieces[2];
var theHost = theHostNamePieces.join('/');

/*NOTE - Make sure you define var siteFolder in  /scripts/nav.js */
  
function isFormComplete(theForm, theDataSource)
	{
	var theElement;
	var theGroup;
	var eType;
	var incr;
	var eMsg;
	var theDateFieldArray = new Array();

	//Trap for missing second argument to function. If it's empty, set the datasource to FMP.
	if (theDataSource == undefined)
		{
		theDataSource = 'FMPro7';
		}
	
	
	// traverse the form elements, invoking the appropriate validation function for each
	
	for (var i = 0; i < theForm.elements.length; i += incr)
		{
	    var theElement = theForm.elements[i];  // get the element and its type
		var eType = theElement.type;
		var incr = 1;  // assume a non-grouped element
		
	
		if (eType.indexOf('text') == 0 || eType.indexOf('password' ) == 0)  // text or textarea
			{
			var eMsg = validTextBox(theElement, theForm, theDataSource, theDateFieldArray);
			}

		else if (eType.indexOf('select') == 0)  // select-one or select-multiple
			{
			var eMsg = validSelectBox(theElement);
			}

		else if (eType.indexOf('file') == 0)  // select-one or select-multiple
			{
			var eMsg = LimitAttach(theElement.value);
			}

		else if (eType == 'radio')  // radio buttons (first element in the group)
			{
			var theGroup = theForm[theElement.name];  // grouped elements
			var eMsg = validRadioButtons( theElement, theGroup );
			incr = theGroup.length;  // skip past the group
			}

		else if (eType == 'checkbox')   // checkboxes (first element in the group)
			{
			var theGroup = theForm[theElement.name];// grouped elements     
			var eMsg = validCheckBoxes(theElement, theGroup);
			if(theGroup.length != undefined)//if there is more than one checkbox
				{
				incr = theGroup.length;   // skip past the group
				}
			}
	
		if (eMsg)  // we have an error message
			{
			var classN = theElement.className;
			var result = classN.split('|');
			var req = result[0];
			var altname = result[1];
			var minchars = result[2];
			var eName= altname;
	  
			//var eName = ( theElement.altname ) ? theElement.altname : theElement.name;
			if (altname)
				{
				//alert( altname + ': ' + eMsg );  // display the message (use altname if given)    
				alert( '"' + altname + '" ' + eMsg );  // display the message (use altname if given)    
				}
			else
				{
				alert(eMsg);
				}
 
			//alert ('req='+ req + '  altname='+ altname + '  minchars='+minchars);

			theElement.focus();  // go to the offending element
			return false;  // the form is NOT complete
			}
		}
	
	//alert(theDateFieldArray);
	//Process all of the date fields last - they have been collected in theDateFieldArray while looping through the text boxes above.
	for (var i = 0; i < theDateFieldArray.length; i++)
	{
		var eMsg = validDate(theForm, theDateFieldArray[i], theDataSource);
		if (eMsg)  // we have an error message
			{
			var theElementName = theDateFieldArray[i];
	  		var theElement = theForm[theElementName];
			var classN = theElement.className;
			var result = classN.split('|');
			var req = result[0];
			var altname = result[1];
			if(altname != undefined)
			{
			altname = altname.replace(/(<([^>]+)>)/ig,""); //strip HTML tags in altname
			}
			
			var minchars = result[2];
			var eName= altname;
			
			//var eName = ( theElement.altname ) ? theElement.altname : theElement.name;
			if (altname)
				{
				//alert( altname + ': ' + eMsg );  // display the message (use altname if given)    
				alert( '"' + altname + '" ' + eMsg );  // display the message (use altname if given)    
				}
			else
				{
				alert(eMsg);
				}
 
			//alert ('req='+ req + '  altname='+ altname + '  minchars='+minchars);

			theElement.focus();  // go to the offending element
			return false;  // the form is NOT complete
			}
	}
	
	return true;  // the form is complete
	}


/*------------------------------------------------------------------------------
    text element validation

    given a text element (type is 'text' or 'textarea')

    returns a message string if
      the text is empty and the 'req' parameter is true
      the text length is not in the range of any specified 'minchars' and/or 'maxchars' parameters
      the word count is not in the range of any specified 'minwords' and/or 'maxwords' parameters
    returns null otherwise
*/

function validDate(theForm, theElementName, theDataSource)
	{
	var theElement = theForm[theElementName];
	var textVal = theElement.value;

	//alert(textVal);
	if (textVal !='')
		{
		var dateTest = new Date(textVal);
		var dateFloor = new Date('01/01/1900'); //min date allowed
		var dateCeiling = new Date('06/30/2020'); //max date allowed

		if (isNaN(dateTest)||textVal.length < 6)
			{
			return 'please enter a valid date in the format mm/dd/yyyy.';
			}
		else if (dateTest <= dateFloor)
			{
			return 'please enter a date after ' + dateFloor;
			}
		else if (dateTest >= dateCeiling)
			{
			return 'please enter a date before ' + dateCeiling;
			}
					
		var theSlashDate = theElement.value;
		var theDateParts = theSlashDate.split('/');
		
		var theMonth = parseFloat(theDateParts[0]);
		var theDay = parseFloat(theDateParts[1]);
		var theYear = parseFloat(theDateParts[2]);
		
		if(theDay < 10 && String(theDay).substring(0,1) != "0") 
			{
			theDay = "0" + theDay;
			}
		if(theMonth < 10 && String(theMonth).substring(0,1) != "0") 
			{
			theMonth = "0" + theMonth;
			}
		if(theYear < 1000)
			{
			theYear = theYear + 2000;
			}
	
		if (theDataSource == 'MySQL')
		{
		var theDateSep = '-';
		var theFormattedDate = theYear + theDateSep + theMonth + theDateSep + theDay;
		}
		else if(theDataSource == 'FMPro7')
		{
		var theDateSep = '/';
		var theFormattedDate = theMonth + theDateSep + theDay + theDateSep + theYear;
		}
		
		//alert(theFormattedDate);
		
		theElement.value = theFormattedDate;
		}

	}
	
function isWholeNumber(thisNumber)
	{
	var input = thisNumber.toString();
	for (var i = 0; i < input.length; i++)
		{
		var thisChar = input.charAt(i);
		if(thisChar < '0' || thisChar > '9') 
		return true;
		}
	return false;
	}


function validTextBox(theElement, theForm, theDataSource, theDateFieldArray)
	{
	var textVal = theElement.value;
	var nChars = textVal.length;
	var classN = theElement.className;
	var result = classN.split("|");
	var req = result[0];
	var altname = result[1];
	if(altname != undefined)
	{
		altname = altname.replace(/(<([^>]+)>)/ig,""); //strip HTML tags in altname
	}
	
	var inputtype= result[2];
  
	if (inputtype=='chars')
		{
		var minchars = parseInt(result[3]);
		var maxchars = parseInt(result[4]);
		}
  
	if (inputtype=='words')
		{
		var minwords = result[5];
		var maxwords = result[6];
		}

	if (inputtype=='num')
		{
		if (isNaN(textVal))
			{
			return 'must be a number.';
			}

		if (textVal < 0)
			{
			return 'must be a POSITIVE number.';
			}
	
		if (isWholeNumber(textVal))
			{
			return 'must not be a decimal number.';
			}   
		}
  
  	if (inputtype=='percent')
		{
		if (isNaN(textVal))
			{
			return 'must be a number.';
			}

		if (textVal < 0)
			{
			return 'must be a POSITIVE number.';
			} 
		}

  
	if (inputtype=='date')
		{
		theDateFieldArray[theDateFieldArray.length] = theElement.name; // save these for processing at the end
		//alert(theDateFieldArray.length);
		}
  
	if (inputtype=='phone')
		{     
		if(theElement.value !== '')
			{
			eMsg = formatPhone(theElement);
			return eMsg;
			}
		}
  
	if (inputtype=='email')
		{ 
		if(theElement.value !== '')
			{
			eMsg = emailCheck(theElement.value);
			return eMsg;
			}
		}
	if (req)  // req specified
		{
		if (req && nChars < 1)
			return  'must be specified. Enter "N/A" if not applicable.';
		}

	if (minchars || maxchars)   // minchars or maxchars specified
		{
		var rangeMsg = inRange( nChars, minchars, maxchars);
		if (rangeMsg)
			{
			return  'must have ' + rangeMsg + ' characters.';
			}
		}

	if (minwords || maxwords)   // minwords or maxwords specified
		{
		//alert('Maxwords: ' + maxwords);
		var nWords = textVal.split( /\s+/ ).length; // split on whitespace
		var rangeMsg = inRange(nWords, minwords, maxwords)
     
		if (rangeMsg)
			{
			return  'must have ' + rangeMsg + ' words.';
			}
		}
  
	if(inputtype == 'time' && req)
		{
		eMsg = validTime(theElement, theElement.value);
		return eMsg;
		}

	return null;   // no msg: element is ok
	}


function validTime( theElement, timeStr) 
	{
	var classN = theElement.className;
	var result = classN.split("|");
	var req = result[0];
	var altname = result[1];
	if(altname != undefined)
	{
		altname = altname.replace(/(<([^>]+)>)/ig,""); //strip HTML tags in altname
	}
	var inputtype= result[2];
	var unused = result[3];
	var unused2 = result[4];
	
	// Checks if time is in HH:MM:SS AM/PM format.
	// The seconds and AM/PM are optional.
		
	var timeStr = theElement.value;
	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
	
	var matchArray = timeStr.match(timePat);
	var ampm = matchArray[6];
	if (ampm=="") { ampm = null }
		
	if( req )
		{
		if (matchArray == null || ampm == null) 
			return 'Time is not in a valid format. Be sure to include AM/PM';
		}
	return null;
	}


/*------------------------------------------------------------------------------
    select element validation

    given a select element (type is 'select-one' or 'select-multiple')

    returns a message string if
      the 'req' parameter is true and the first option is selected
    returns null otherwise

    note: This could be more robust. It assumes the first option is a "default" option that, if
    selected, means the user didn't select a "real" option.
*/

function validSelectBox( theElement )
	{
	var classN = theElement.className;
	var result = classN.split("|");
	var req = result[0];
	var altname = result[1];
	if(altname != undefined)
	{
		altname = altname.replace(/(<([^>]+)>)/ig,""); //strip HTML tags in altname
	}
	var inputtype= result[2];
	var unused = result[3];
	var unused2 = result[4];

	if ( req )                     // req specified
		{
		if ( req && theElement.selectedIndex < 1 )
			return  'must be selected.';
		}
	return  null;                            // no msg: element is ok
	}


/*------------------------------------------------------------------------------
    radio button group validation

    given a radio button element (type is 'radio') and the group it's a member of

    returns a message string if
      none of the radio buttons is checked and the 'req' parameter is true
    returns null otherwise
*/

function validRadioButtons( theElement, theGroup )
	{
	var classN = theElement.className;
	var result = classN.split("|");
	var req = result[0];
	var altname = result[1];
	if(altname != undefined)
	{
		altname = altname.replace(/(<([^>]+)>)/ig,""); //strip HTML tags in altname
	}
	var inputtype= result[2];
	var unused = result[3];
	var unused2 = result[4];

	if ( req )                     // req specified
		{
		if ( req && numChecked( theGroup ) < 1 )
			return  'must be specified.';
		}
	return  null;                            // no msg: element is ok
	}


/*------------------------------------------------------------------------------
    checkbox group validation

    given a checkbox element (type is 'checkbox') and the group it's a member of

    returns a message string if
      the number of checked checkboxes is not in the range of the specified 'minchecked' and/or 'maxchecked' parameters
    returns null otherwise
*/

function validCheckBoxes( theElement, theGroup )
	{
	var classN = theElement.className;
	var result = classN.split("|");
	var req = result[0];
	var altname = result[1];
	if(altname != undefined)
		{
		altname = altname.replace(/(<([^>]+)>)/ig,""); //strip HTML tags in altname
		}
	var inputtype= result[2];
	var minchecked = result[3];
	var maxchecked = result[4];
	if ( req || maxchecked )   // minchecked or maxchecked specified
		{
		var rangeMsg = inRange( theElement, numChecked( theGroup ), minchecked, maxchecked );
		if ( rangeMsg )
			{
			return  'must have ' + rangeMsg + ' checked.';
			}
		}
	
	return  null;                            // no msg: element is ok
	}


/*------------------------------------------------------------------------------
    generate a phrase for a numeric range checking error message

    given a numeric value and min and/or max limits

    returns a message string if
      the numeric value is not in the range of the specified min and max limits
    returns null otherwise
*/

function inRange(theValue, minValue, maxValue )
	{
	//alert('MinValue:'+minValue+'\nMaxValue:'+maxValue+'\ntheValue:'+theValue);

	if ( minValue )                // min specified
		{
		if ( maxValue )                // both min and max specified
			{
			if ( theValue < minValue || theValue > maxValue )
				{
				if ( minValue == maxValue )
					return  'exactly ' + minValue;
				else
					return  'between ' + minValue + ' and ' + maxValue;
				}
			}
		else                           // only min specified
			{
			if ( theValue < minValue )
				return  'at least ' + minValue;
			}
		}
	else
		if ( maxValue )                // only max specified
			{
			if ( theValue > maxValue )
				return  'at most ' + maxValue;
			}
	return  null;
	}


/*------------------------------------------------------------------------------
    count checked checkboxes (or radio buttons)

    given a group of checkboxes with the same name

    returns the number that are checked

    note: also works for a group of radio buttons (returns 0 or 1)
*/

function numChecked( theGroup )
	{
	var n = 0;
	for ( var j = 0; j < theGroup.length; j++ )
		{
		if ( theGroup[j].checked )  n++;
		}
		return  n;
	}


/*------------------------------------------------------------------------------
    select element branching function

    usage: <select name="isStudent" ... onchange="branchTo(this, 1, Advisor, Color);">

    given a select element to test, a yes-option index, a yes-element to move
    to if the yes-option is selected, and a no-element to move to if not

    if yes-option is selected, set the yes-element req=true and move there
    otherwise, set the yes-element req=false and move to the no-element

    note: this is not part of the form validation process: it is invoked by an
    onChange event for an element, not the onSubmit event for the form.
*/

function branchTo( theElement, yesIndex, yesElement, noElement )
	{
	if ( theElement.selectedIndex == yesIndex )
		{
		yesElement.req = 'true';
		yesElement.focus();
		}
	else
		{
		yesElement.req = 'false';
		noElement.focus();
		}
	}

function amIaDate(theField)
	{
	if (theField != "")
		{
		var theWorkingDate = new Date(theField);
		alert(theWorkingDate);
		var theFlag = true;
		
		if (isNaN(theWorkingDate)||length(theWorkingDate)<5)
			{
			return true;
			}
		else
			{
			var theMonth = theWorkingDate.getMonth() + 1;
			var theDay = theWorkingDate.getDate();
			var theYear = theWorkingDate.getFullYear();

			if (theYear < 2000)
				{
				theYear = theYear + 100;
				}
			var fancyDate = theMonth + '/' + theDay + '/' + theYear;
			theField = fancyDate
			return true;
			}
		}
	}
 

function formatPhone(fieldName)
	{
	// pass theElement.name
	var re = /\D/;

	// test for this format: (xxx)xxx-xxxx
	var re2 = /^\({1}\d{3}\)\d{3}-\d{4}/; 

	// test for this format: xxx-xxx-xxxx
	//var re2 = /^\d{3}-\d{3}-\d{4}/;

	var num=fieldName.value;
	//alert(num);
	var newNum;

	if (num != "" && re2.test(num)!=true)
		{
		if (num != "")
			{
			while (re.test(num))
				{
				num = num.replace(re,"");
				}
			}
 
		if (num.length != 10)
			{
			return ('Please enter a 10 digit phone number');
			fieldName.select();
			fieldName.focus();
			//return false;
			}
		else
			{
			// for format (xxx) xxx-xxxx
			newNum = '(' + num.substring(0,3) + ') ' + num.substring(3,6) + '-' + num.substring(6,10);
			// for format xxx-xxx-xxxx
			// newNum = num.substring(0,3) + '-' + num.substring(3,6) + '-' + num.substring(6,10);
			fieldName.value=newNum;
			}
		}
	return null;
	}




/* 1.1.4: Fixed a bug where upper ASCII characters (i.e. accented letters
international characters) were allowed.

1.1.3: Added the restriction to only accept addresses ending in two
letters (interpreted to be a country code) or one of the known
TLDs (com, net, org, edu, int, mil, gov, arpa), including the
new ones (biz, aero, name, coop, info, pro, museum).  One can
easily update the list (if ICANN adds even more TLDs in the
future) by updating the knownDomsPat variable near the
top of the function.  Also, I added a variable at the top
of the function that determines whether or not TLDs should be
checked at all.  This is good if you are using this function
internally (i.e. intranet site) where hostnames don't have to 
conform to W3C standards and thus internal organization e-mail
addresses don't have to either.
Changed some of the logic so that the function will work properly
with Netscape 6.

1.1.2: Fixed a bug where trailing . in e-mail address was passing
(the bug is actually in the weak regexp engine of the browser; I
simplified the regexps to make it work).

1.1.1: Removed restriction that countries must be preceded by a domain,
so abc@host.uk is now legal.  However, there's still the 
restriction that an address must end in a two or three letter
word.

1.1: Rewrote most of the function to conform more closely to RFC 822.

1.0: Original  */
// -->


function emailCheck (emailStr)
	{
	
	/* The following variable tells the rest of the function whether or not
	to verify that the address ends in a two-letter country or well-known
	TLD.  1 means check it, 0 means don't. */
	
	var checkTLD = 1;
	
	/* The following is the list of known TLDs that an e-mail address must end with. */
	
	var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	
	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
	from the domain. */
	
	var emailPat = /^(.+)@(.+)$/;
	
	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address. 
	These characters include ( ) < > @ ,; : \ " . [ ] */
	
	var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	
	/* The following string represents the range of characters allowed in a 
	username or domainname.  It really states which chars aren't allowed.*/
	
	var validChars = "\[^\\s" + specialChars + "\]";
	
	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */
	
	var quotedUser = "(\"[^\"]*\")";
	
	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */
	
	var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	
	/* The following string represents an atom (basically a series of non-special characters.) */
	
	var atom = validChars + '+';
	
	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */
	
	var word = "(" + atom + "|" + quotedUser + ")";
	
	// The following pattern describes the structure of the user
	
	var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
	
	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */
	
	var domainPat = new RegExp("^" + atom + "(\\." + atom +")*$");
	
	/* Finally, let's start trying to figure out if the supplied address is valid. */
	
	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */
	
	var matchArray = emailStr.match(emailPat);
	
	if (matchArray == null)
		{
		/* Too many/few @'s or something; basically, this address doesn't
		even fit the general mould of a valid e-mail address. */
		
		return ("Email address seems incorrect (check @ and .'s)");
		//return false;
		}
		
	var user=matchArray[1];
	var domain=matchArray[2];
	
	// Start by checking that only basic ASCII characters are in the strings (0-127).
	
	for (i = 0; i < user.length; i++)
		{
		if (user.charCodeAt(i)>127)
			{
			return("Ths username contains invalid characters.");
			//return false;
			}
		}
		
	for (i = 0; i < domain.length; i++)
		{
		if (domain.charCodeAt(i)>127)
			{
			return("Ths domain name contains invalid characters.");
			//return false;
			}
		}
	
	// See if "user" is valid 
	if (user.match(userPat) == null)
		{
		// user is not valid
	
		return ("The username doesn't seem to be valid.");
		//return false;
		}
	
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */
	
	var IPArray = domain.match(ipDomainPat);
	if (IPArray != null)
		{
		// this is an IP address
		
		for (var i = 1; i <= 4; i++)
			{
			if (IPArray[i] > 255)
				{
				return ("Destination IP address is invalid!");
				//return false;
				}
			}
		return null;
		}
	
	// Domain is symbolic name.  Check if it's valid.
	 
	var atomPat = new RegExp("^" + atom + "$");
	var domArr = domain.split(".");
	var len = domArr.length;
	for (i = 0; i < len; i++)
		{
		if (domArr[i].search(atomPat) == -1)
			{
			return ("The domain name does not seem to be valid.");
			//return false;
			}
		}
	
	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding 
	the domain or country. */
	
	if (checkTLD && domArr[domArr.length-1].length != 2 && domArr[domArr.length-1].search(knownDomsPat) == -1)
		{
		return ("The address must end in a well-known domain or two letter " + "country.");
		//return false;
		}
	
	// Make sure there's a host name preceding the domain.
	if (len<2)
		{
		return ("This address is missing a hostname!");
		//return false;
		}
	
	// If we've gotten this far, everything's valid!
	return null;
	}







function LimitAttach(file) {
extArray = new Array(".pdf");
allowSubmit = false;
if (!file) return;
while (file.indexOf("\\") != -1)
file = file.slice(file.indexOf("\\") + 1);
ext = file.slice(file.indexOf(".")).toLowerCase();

for (var i = 0; i < extArray.length; i++) {
//alert(extArray[i]);
if (extArray[i] == ext) { 

return null;
}
else
{
return ("Please only upload files that end in types:  " + (extArray.join("  ")) + "\nPlease select a new "
+ "file to upload and submit again.\n If your document is in PDF format, it must be named with a .pdf extension");
}

}
}

//function for displaying/hiding elements
function loopHelp() { 
theDivs = document.getElementsByTagName('div'); 
for( var i = 0; i < theDivs.length; i++ ) 
	{ 
	
	if( theDivs[i].id == 'help' ) 
	{
	 var target= theDivs[i];
	 if ((target!= null)) 
      // Toggle visibility between none and inline 
      if ((target.style.display == 'none')) 
      { 
       target.style.display = 'table';
	   
         
      } else { 
        target.style.display = 'none'; 
         
      } 
	}
	} 
}

function show_row(trigger,target){ 
    // Make sure the element exists before calling it's properties 
    if ((document.getElementById(target) != null)) 
      // Toggle visibility between none and inline 
      if ((document.getElementById(target).style.display == 'none')) 
      { 
        document.getElementById(target).style.display = 'inline'; 
         
      } else { 
        document.getElementById(target).style.display = 'none'; 
         
      } 
  } 


/*****************************************************************************/
/*                                                                           */
/* CurrencyFormatted() formats a number to two decimal places                */
/*                                                                           */
/*****************************************************************************/
function CurrencyFormatted(amount)
	{
	var theNum = parseFloat(amount);
	if(isNaN(theNum))
		{
		theNum = 0.00;
		}
	var minus = '';
	if(theNum < 0)
		{
		minus = '-';
		}
	theNum = Math.abs(theNum);
	theNum = parseInt((theNum + .005) * 100);
	theNum = theNum / 100;
	theString = new String(theNum);
	if(theString.indexOf('.') < 0)
		{
		theString += '.00';
		}
	if(theString.indexOf('.') == (theString.length - 2))
		{
		theString += '0';
		}
	theString = minus + theString;
	return theString;
	}


/*****************************************************************************/
/*                                                                           */
/* valForm() validates form elements according to their class parameters,    */
/*           and calls ajax or post accordingly. It takes three arguments:   */
/*           theForm = the form object to validate                           */
/*           theDataSource is either 'FMPro7' or 'MySQL'                     */
/*           theSubmitType is either 'ajax' or 'post'                        */
/*                                                                           */
/*****************************************************************************/

function valForm(theForm, theDataSource, theSubmitType)
	{
	//Trap for missing second argument to function. If it's empty, set the datasource to FMP.
	//Choices are 'FMPro7' or 'MySQL'
	if (theDataSource == undefined)
		{
		theDataSource = 'FMPro7';
		}
	
	//Trap for missing third argument to function. If it's empty, set the submitType to ajax.
	//Choices are 'ajax' or 'post'.
	if (theSubmitType == undefined)
		{
		theSubmitType = 'ajax';
		}

	if (isFormComplete(theForm, theDataSource))
		{
		var theLoc = theForm['loc'].value;
		var theAct = theForm['act'].value;
		
		updateStatus(theAct);

		if (theSubmitType == 'ajax')
			{
			var theParams = makeFormElementsParam(theForm);
			var theURL = theHost + siteFolder + 'ajax_' + theLoc.toLowerCase() + '.php';
			hideSwooshBox(theAct);
			callAJAX(theLoc, theAct, theParams, theURL);
			return false;
			}
		else
			{
			theForm.submit();
			hideSwooshBox(theAct);
			return true;
			}
		}
	}



/*****************************************************************************/
/*                                                                           */
/* valSearch() validates form elements in a search box to make sure we can't */
/*           submit a blank search form. It takes three paramaters:          */
/*           theForm = the form object to validate                           */
/*           theDataSource is either 'FMPro7' or 'MySQL'                     */
/*           theSubmitType is either 'ajax' or 'post'                        */
/*                                                                           */
/*****************************************************************************/
function valSearch(theForm, theDataSource, theSubmitType)
	{
	//Trap for missing second argument to function. If it's empty, set the datasource to FMP.
	if (theDataSource == undefined)
		{
		theDataSource = 'FMPro7';
		}
	if (theSubmitType == undefined)
		{
		theSubmitType = 'ajax';
		}
		
	var formLength = theForm.length;
	var stopSubmit = true;
	
	for (var x = 0; x < formLength; x++)
		{
		if (theForm[x].type != 'hidden')
			{
			if (theForm[x].type == 'checkbox' || theForm[x].type == 'radio')
				{
				if (theForm[x].checked)
					{
					stopSubmit = false;
					}
				}
			else if (theForm[x].value != '')
				{
				stopSubmit = false;
				}
			}
		}
		
	if (stopSubmit)
		{
		alert ('You have not entered any search criteria.');
		return false;
		}
	else
		{
		valForm(theForm, theDataSource, theSubmitType);
		}
	}




/*****************************************************************************/
/*                                                                           */
/* goSideBarFromList() bounces from list view to detail view with a sidebar  */
/*                     theRecID = the record ID of the selected item         */
/*                     theAct   = the act value to pass to the next page     */
/*                     theFormName = the hidden form beneath drawList() to   */
/*                                   harvest for sort info and submit        */
/*                                                                           */
/*****************************************************************************/
function goSideBarFromList(theRecID, theAct, theFormName)
	{
	var theForm = document[theFormName];
	//var theLoc = 'News';
	
	theForm['act'].value = theAct;
	
	if(theForm['recID'] == undefined)
		{
		theForm.innerHTML += '<input type="hidden" name="recID" value="' + theRecID + '">';
		}
	else
		{
		theForm['recID'].value = theRecID;
		}	
	theForm.submit();	
	}







function trim(stringToTrim)
	{
	return stringToTrim.replace(/^\s+|\s+$/g,"");
	}


function ltrim(stringToTrim)
	{
	return stringToTrim.replace(/^\s+/,"");
	}


function rtrim(stringToTrim)
	{
	return stringToTrim.replace(/\s+$/,"");
	}
