<!--

/* <%--
//
//	File: 		validate/header.js
//	Purpose:	Header function for all validation JavaScript operations
//  Usage:    This file contains the header information for doing JavaScript
//            validation of forms.  Other files contain routines for various
//            types of validation.  They can be separately included or just
//            include the file everything.js which also includes this file.
//
//            If the validation code is not contained in the current page
//            (like in a parent frame) then the variable $VALIDATION should be
//            set.
//

// ------ PUBLIC FUNCTION INDEX
//
// --- message functions
//
// VAL_Initialize()
// VAL_ErrorPending()
// VAL_WarningMessageGet()
// VAL_WarningIsPending()
// VAL_WarningMessageSet ( msg )
// VAL_SubmitForm( form[, checkMsg] )
// VAL_CheckRequired ( fieldRef, desc, postfix )
// VAL_CheckRequiredDependent ( fieldRef, fieldLabel, dependentFieldRef, dependentFieldLabel )
// VAL_CheckMinLen ( fieldRef, desc, minLength )
// VAL_CheckRequiredMinLen ( fieldRef, desc, minLength )
// VAL_CheckMaxLen ( fieldRef, desc, maxLength )
// VAL_AppendRequired ( fieldname, field, postfix )
// VAL_CheckMustBeBlank ( fieldRef, desc, postfix )
// VAL_AppendMustBeBlank ( desc, fieldRef, postfix )
// VAL_AppendReqCore ( desc, fieldRef, message, postfix )
// VAL_AppendError( msg, field )
// VAL_CheckError( cond, msg, field )
// VAL_GetFieldArrayRef ( parentForm, fieldBase, index )
//
// --- whitespace and char functions
//
// VAL_IsEmpty( str )
// VAL_IsBlank( val )
// VAL_HasAlphaNumericChar( val )
// VAL_StripWhitespace( str )
// VAL_StripOuterWhitespace( str )
// VAL_StripLeadingWhitespace( str )
// VAL_StripTrailingWhitespace( str )
// VAL_StripCharsInBag( str, bag )
// VAL_StripNonAlphaNumeric ( str )
// VAL_StripNonNumeric ( str )
// VAL_StripLeadingZeros ( str )

// VAL_NVL ( val, def )
//
// --- string functions, prolly should be moved to a diff include
//
// STR_Instr ( stringValue, charVal, startIndex )
//

// function VAL_SetFocusOnField ( fieldRef )

// function VAL_ShadowFieldExists ( form, fieldName )

//EXAMPLE JAVASCRIPT
function SubmitForm()
{
	// re-initialize for every validation cycle
	VALLOC.VAL_Initialize();

	var form = document.forms[0];
	var StartDate = VALLOC.VAL_DateAllOrNothing (form.FromDay, form.FromMonth, form.FromYear);
	var EndDate = VALLOC.VAL_DateAllOrNothing (form.ToDay, form.ToMonth, form.ToYear);

	if (StartDate == -1) VALLOC.VAL_AppendError ("Please fill in all the From Date fields or make them all blank.", form.FromDay);
	if (EndDate == -1) VALLOC.VAL_AppendError ("Please fill in all the To Date fields or make them all blank.", form.ToDay);

	if (! VALLOC.VAL_ErrorPending() ) {
		form.PriorActivityViewQuery_StartDate.value = StartDate;
		form.PriorActivityViewQuery_EndDate.value = EndDate;
	}
	VALLOC.VAL_SubmitForm( form );
}

--%> */

// ------ GLOBAL PREFERENCES

// whitespace characters can be set by changing this JS variable
// be sure to escape backslashes in HTML++ value
var VAL_whitespace = new String( " \t\n\r" );
var VAL_zero = new String("0");

// the message that comes up when a validation problem occurs can be changed
// this var is located in js_constants.jsp
// var VAL_failmessage = new String( "The following problems have been identified:\n" );


// Used by VAL_AppendError(), must be global for functions to modify
// You *MUST* reinitialize these every validation cycle! (which should be done
// by calling VAL_Initialize())
// Some vars are located in js_constants.jsp for language translation purposes
VAL_errMessage = ""; // use as arg VAL_ErrorAlert(errorMsg, *)
VAL_errField = null; // use as arg VAL_ErrorAlert(*, focusobj)
VAL_WarningMessage = "";

// functions to init and get values
function VAL_Initialize () { VAL_errMessage = ""; VAL_errField = null; VAL_WarningMessage = ""; }
function VAL_GetErrMessage () { return VAL_errMessage; }
function VAL_GetErrField () { return VAL_errField; }
function VAL_WarningMessageGet () { return VAL_WarningMessage; }

// this is needed because Firefox browsers return an empty arg as null instead of empty string
function getExecParam( aMatch, paramNum )
{
	return (aMatch[paramNum] != null ? aMatch[paramNum] : '');
}

function sprintf()
{
/*
======================================================================
 sprintf()
======================================================================
 Purpose : format a string
----------------------------------------------------------------------
 Parameters :
 you may figure this one out yourself (hint: www.php.net/sprintf)
----------------------------------------------------------------------
 Returns : a formatted string
======================================================================
*/
	var iCount, iPadLength, aMatch, iMatchIndex = 1;
	var bAlignLeft, sPad, iWidth, iPrecision, sType;
	
	
	var aArgs = sprintf.arguments;
	if (aArgs.length < 2) return '';
	
	var sFormat = aArgs[0];
	var re = /%(-)?(0| |'.)?(\d+)?(\.\d*)?([bcdfosxX]{1})/; //'
	while (re.test(sFormat))
	{
		aMatch = re.exec(sFormat);
		bAlignLeft = (aMatch[1] == '-');
		sPad = (getExecParam( aMatch, 2 ) == '' ? ' ' : getExecParam( aMatch, 2 ));
		if (sPad.substring(0, 1) == "'") sPad = sPad.substring(1);
		iWidth = (aMatch[3] > 0 ? parseInt(aMatch[3]) : 0);
		iPrecision = (getExecParam( aMatch, 4 ).length > 1 ? parseInt(getExecParam( aMatch, 4 ).substring(1)) : 6);
		sType = getExecParam( aMatch, 5 );
		mArgument = (aArgs[iMatchIndex] != null ? aArgs[iMatchIndex] : '');
		++iMatchIndex;
		if (mArgument.toString().length)
		{
			if ('fbcdoxX'.indexOf(sType) != -1 && isNaN(mArgument)) mArgument = 0;
			switch (sType)
			{
				case 'f':	// floats
					var iPower = Math.pow(10, iPrecision);
					mArgument = (Math.round(parseFloat(mArgument) * iPower) / iPower).toString();
					var aFloatParts = mArgument.split('.');
					if (iPrecision > 0)
					{
						if (aFloatParts.length == 1) aFloatParts[1] = '';
						// pad with zeroes to precision
						for (iCount = aFloatParts[1].length; iCount < iPrecision; iCount++)
							aFloatParts[1] += '0';
						mArgument = aFloatParts[0] + '.' + aFloatParts[1];
					}
					else mArgument = aFloatParts[0];
					
					iPadLength = aFloatParts[0].length;
					break;
				case 'b':	// binary
					mArgument = parseInt(mArgument).toString(2);
					iPadLength = mArgument.length;
					break;
				case 'c':	// character
					mArgument = String.fromCharCode(parseInt(mArgument));
					break;
				case 'd':	// decimal
					mArgument = mArgument.toString();
					iPadLength = mArgument.length;
					break;
				case 'o':	// octal
					mArgument = parseInt(mArgument).toString(8);
					iPadLength = mArgument.length;
					break;
				case 'x':	// hexadecimal (lowercase)
					mArgument = parseInt(mArgument).toString(16);
					iPadLength = mArgument.length;
					break;
				case 'X':	// hexadecimal (uppercase)
					mArgument = parseInt(mArgument).toString(16).toUpperCase();
					iPadLength = mArgument.length;
					break;
				default:	// strings
					mArgument = mArgument.toString();
					iPadLength = mArgument.length;
			}
			
			if ('fbdoxX'.indexOf(sType) != -1)
			{
				// pad with padding-char to width
				if (bAlignLeft)
					for (iCount = iPadLength; iCount < iWidth; iCount++)
						mArgument += sPad;
				else
					for (iCount = iPadLength; iCount < iWidth; iCount++)
						mArgument = sPad + mArgument;
			}
		}
		sFormat = sFormat.replace(re, mArgument);
	}
	return sFormat;
}

// ------------------------------------------------------------------------ //
// Indicates whether an error has been appended
//
function VAL_ErrorPending()
{
	return ( VAL_GetErrMessage() != "" );
}


// ------------------------------------------------------------------------ //
// Indicates whether a warning message is in effect
//
function VAL_WarningIsPending()
{
	return ( VAL_WarningMessageGet() != "" );
}


// ------------------------------------------------------------------------ //
// Sets the warning message
//
function VAL_WarningMessageSet ( msg )
{
	VAL_WarningMessage = msg;
}


// ------------------------------------------------------------------------ //
// Submits a form if valid or displays the error message otherwise.
// Returns true if the form was submitted or false otherwise

function VAL_SubmitForm (
	form	     // form object to submit
	// checkMsg - OPTIONAL a message to check with the user if the form is OK
)
{
	if ( VAL_ErrorPending() ) {
		VAL_ErrorAlert (VAL_GetErrMessage(), VAL_GetErrField());
		return false;
	} else {
		if ( VAL_WarningIsPending() && ! confirm ( VAL_WarningMessageGet() ) )
			return false;

		if ((arguments.length >= 2) && (arguments[1] != "")) {
			if (!confirm( arguments[1] )) {
				return false;
			}
		}
		form.submit();
		return true;
	}
}


// ------------------------------------------------------------------------ //
// Supplied field is required, builds appropriate error message if blank.
// Returns true if filled in, false otherwise.

function VAL_CheckRequired ( fieldRef, desc, postfix )
{
	if ( fieldRef != null && VAL_IsBlank ( FV_FormValueGet ( fieldRef ) ) ) {
		if ( FV_ElementIsRadioGroup ( fieldRef ) ) fieldRef = fieldRef[0];
		VAL_AppendRequired ( desc, fieldRef, postfix );
		return false;
	} else
		return true;
}

// ------------------------------------------------------------------------ //
// DependentField is required if MasterField is present, builds appropriate error message if blank.
// Returns true if filled in, false otherwise.
function VAL_CheckRequiredDependent ( fieldRef, fieldLabel, dependentFieldRef, dependentFieldLabel )
{
	if ( fieldRef != null && dependentFieldRef != null ) {
		if ( FV_ElementIsRadioGroup ( fieldRef ) ) fieldRef = fieldRef[0];
		if ( FV_ElementIsRadioGroup ( dependentFieldRef ) ) dependentFieldRef = dependentFieldRef[0];
		if ( !VAL_IsBlank ( FV_FormValueGet ( fieldRef ) ) && VAL_IsBlank ( FV_FormValueGet ( dependentFieldRef ) ) ) {
		VAL_AppendRequired ( dependentFieldLabel, dependentFieldRef, sprintf( VAL_checkReqDependentMsg, fieldLabel ));
		return false;
		}
	}
	return true;
}

// ------------------------------------------------------------------------ //
// Supplied field may be blank or must be filled in with minimum length.
// Returns true if blank or length ok, false if non-blank with too few chars

function VAL_CheckMinLen ( fieldRef, desc, minLength )
{
	var val = VAL_StripOuterWhitespace( FV_FormValueGet ( fieldRef ) );
	VAL_StripOuterWhitespace
	if ( ! VAL_IsBlank ( val ) && val.length < minLength ) {
		VAL_AppendError ( sprintf( VAL_checkMinLenMsg, desc, minLength ), fieldRef );
		return false;
	} else
		return true;
}


// ------------------------------------------------------------------------ //
// Supplied field is required, builds appropriate error message if blank.
// Returns true if filled in with minimum length, false otherwise.

function VAL_CheckRequiredMinLen ( fieldRef, desc, minLength )
{
	if ( VAL_CheckRequired ( fieldRef, desc ) )
		return VAL_CheckMinLen ( fieldRef, desc, minLength );
	else
		return false;
}

// ------------------------------------------------------------------------ //
// Supplied field may only be maximum length.
// Returns true length ok, false if too many chars

function VAL_CheckMaxLen ( fieldRef, desc, maxLength )
{
	var val = VAL_StripOuterWhitespace( FV_FormValueGet ( fieldRef ) );
	if ( val.length > maxLength ) {
		VAL_AppendError ( sprintf( VAL_checkMaxLenMsg, desc, maxLength ), fieldRef );
		return false;
	} else
		return true;
}

// ------------------------------------------------------------------------ //
// Use to alert about required fields
// Also see VAL_AppendError

function VAL_AppendRequired (
	fieldName,	// new error string to append, corresponds to VAL_ErrorAlert().errorMsg
	field,	// reference to new bad field, corresponds to VAL_ErrorAlert().focusobj
	postfix // extra text to add at end
)
{
	VAL_AppendReqCore ( fieldName, field, VAL_reqMsg, postfix );
}


// ------------------------------------------------------------------------ //
function VAL_CheckMustBeBlank ( fieldRef, desc, postfix )
{
	if ( fieldRef != null && ! VAL_IsBlank ( FV_FormValueGet ( fieldRef ) ) ) {
		if ( FV_ElementIsRadioGroup ( fieldRef ) ) fieldRef = fieldRef[0];
		VAL_AppendMustBeBlank ( desc, fieldRef, postfix );
		return false;
	} else
		return true;
}


// ------------------------------------------------------------------------ //
function VAL_AppendMustBeBlank ( desc, fieldRef, postfix )
{
	VAL_AppendReqCore ( desc, fieldRef, VAL_mustBeBlankMsg, postfix );
}


// ------------------------------------------------------------------------ //
function VAL_AppendReqCore ( desc, fieldRef, message, postfix )
{
	if (postfix == null) postfix = "";
	VAL_AppendError ( desc + message + postfix + ".", fieldRef );
}


// ------------------------------------------------------------------------ //
// Use in conjunction with VAL_ErrorAlert().
// Appends an error message to an ever-growing string, you do NOT need to
// supply the "/n".
// Also assigns a reference to the *first* bad field.

function VAL_AppendError (
	msg,	// new error string to append, corresponds to VAL_ErrorAlert().errorMsg
	field	// reference to new bad field, corresponds to VAL_ErrorAlert().focusobj
)
{
	VAL_errMessage = VAL_errMessage + msg + "\n";
	if (VAL_errField == null) VAL_errField = field;
}

// ------------------------------------------------------------------------ //
// Checks a condition to see if an error occurred.  If so then the function
// VAL_AppendError is called.  It also returns the value of the condition.

function VAL_CheckError (
  cond, // a boolean condition, usually a function result, indicating if
	      //   a validation error occurred
	msg,	// new error string to append
	field	// reference to new bad field
)
{
	if (!cond) {
		VAL_AppendError( msg, field );
	}
	return cond;
}

// ------------------------------------------------------------------------ //
// Opens an alert with an error msg and sets focus to a form object. Each
// problem should be listed with a trailing return being built with the
// VAL_AppendError function.
// ex. VAL_ErrorAlert("City needs to be filled in.\n", form.City);

function VAL_ErrorAlert(
	errorMsg, // message to display
	focusobj  // object to set focus to
)
{
	alert(VAL_failmessage + errorMsg);
	if(focusobj != null && focusobj.type != "hidden") focusobj.focus();
}



// ------------------------------------------------------------------------ //
// Returns a reference to the indexed field in an HTML++ style "array".
// The field name ends up looking like TABLE_FIELD_INDEX.

function VAL_GetFieldArrayRef
	(parentForm,	// fully qualified "path" for form element in which field resides
	fieldBase,		// base name for field "array"
	index)				// index of field, base "suffix"
{
	var fieldName = fieldBase;
	if ( index >= 0 ) fieldName += "_" + index;
	return parentForm.elements[fieldName];
}



// ------------------------------------------------------------------------ //
// Checks whether string s is empty.

function VAL_IsEmpty(
	str  // a string value
)
{
	return ((str == null) || (str.length == 0));
}

// ------------------------------------------------------------------------ //
// Boolean function that determines if a value is blank or empty

function VAL_IsBlank(val)
{
	var aCharExists = false;
	// is the value empty?
	if (!VAL_IsEmpty( val ))
		// nope, but is at all blanks?
		for (var i = 0; i < val.length; i++)
			if (val.charAt(i) != " ")
			{
				// nope, it's not all blank
				aCharExists = true;
				break; // we're done
			}
	return ! aCharExists;
}

// Checks whether string s has alphanumeric character.

function VAL_HasAlphaNumericChar (inStr)
{
	var retVal = false;
	var val = VAL_StripNonAlphaNumeric ( inStr );
	if ( !VAL_IsEmpty ( val ) ){
		retVal = true;
	}
	return retVal;
}

// ------------------------------------------------------------------------ //
// Removes all whitespace characters from str. Global variable
// VAL_whitespace (see top of file) defines which characters are considered
// whitespace.

function VAL_StripWhitespace(
	str  // string value
)
{
	return VAL_StripCharsInBag (str, VAL_whitespace);
}


// ------------------------------------------------------------------------ //
// Removes leading and trailing whitespace characters from str. Global
// variable VAL_whitespace (see top of file) defines which characters are
// considered whitespace.

function VAL_StripOuterWhitespace (
	str // string value
)
{
	str = VAL_StripLeadingWhitespace( str );
	return VAL_StripTrailingWhitespace( str );
}

// ------------------------------------------------------------------------ //
// Removes leading whitespace characters from str. Global variable
// VAL_whitespace (see top of file) defines which characters are considered
// whitespace.
function VAL_StripLeadingWhitespace (
	str // string value
)
{
	var i = 0;
	while ((i < str.length) && (VAL_whitespace.indexOf(str.charAt(i)) >= 0))
		i++;
	return str.substring (i, str.length);
}

// ------------------------------------------------------------------------ //
// Removes trailing whitespace characters from str. Global variable
// VAL_whitespace (see top of file) defines which characters are considered
// whitespace.

function VAL_StripTrailingWhitespace (
	str // string value
)
{
	var i = str.length - 1;
	while ((i >= 0) && (VAL_whitespace.indexOf(str.charAt(i)) >= 0))
		i--;
	return str.substring (0, i + 1);
}

// ------------------------------------------------------------------------ //
// Removes all characters which appear in string bag from string str.

function VAL_StripCharsInBag (
	str, // string value to strip
	bag  // bag of characters to strip out
)
{
	var returnString = "";

	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (var i = 0; i < str.length; i++)
	{
		// Check that current character isn't whitespace.
		var c = str.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}

	return returnString;
}

function VAL_StripNonAlphaNumeric ( str )
{
	var returnString = "";

	for (var i = 0; i < str.length; i++)
	{
		var c = str.charAt(i);
		if ( VAL_IsLetterOrDigit ( c ) ) returnString += c;
	}

	return returnString;
}

function VAL_StripNonNumeric ( str )
{
	var returnString = "";

	for (var i = 0; i < str.length; i++)
	{
		var c = str.charAt(i);
		if ( VAL_IsDigit ( c ) ) returnString += c;
	}

	return returnString;
}

// ------------------------------------------------------------------------ //
// don't use with boolean false or numeric zero because they eval as null
function VAL_NVL ( val, def )
{
	if ( val == "undefined" || val == null || val == "" )
		return def;
	else
		return val;
}

// ------------------------------------------------------------------------ //
// Removes leading zeros  from str. Global variable
// VAL_zero is the string representing zero
function VAL_StripLeadingZeros (str)
{
	var i = 0;
	while ((i < str.length) && (VAL_zero.indexOf(str.charAt(i)) >= 0))
		i++;
	return str.substring (i, str.length);
}

// ------------------------------------------------------------------------ //
// Returns the index of the char within the string value, zero-based.
// Start index is optional. Returns -1 if not found.
// This could be upgraded search for strings instead of chars by using char.length
function STR_Instr ( stringValue, charVal, startIndex )
{
	if ( startIndex == null || startIndex == "" ) startIndex = 0;
	var found = false;
	var index = startIndex;
	var max = stringValue.length;

	while ( index < max && ! found ) {
		var currChar = stringValue.substring ( index, index + 1 );
		if ( currChar == charVal ) {
			found = true;
		} else {
			index ++;
		}
	}

	if ( ! found ) { index = -1; }
	return index;
}

function VAL_searchAndReplace (
      str, // string value to strip
      searchChar,  // bag of characters to strip out
      replaceChar
)
{
      var returnString = "";
 
      // Search through string's characters one by one.
      // If character is not = searchChar, append to returnString.
      for (var i = 0; i < str.length; i++)
      {
            var c = str.charAt(i);
            if (searchChar.indexOf(c) == -1) {
                  returnString += c;
            } else {
                  returnString += replaceChar;
            }
      }
 
      return returnString;
}

 
// ------------------------------------------------------------------------ //
//    Checks whether a field is blank.  
//    Returns a string with the field name if blank
//    Returns an empty string "" if not blank
 
function VAL_IsBlankField(
      form,      // a form reference with the number to validate
      fieldName, // the field name
      fieldType  // the type of number i.e. how mapped to the form
)
{
  var retVal = fieldName;
      if (fieldType == "INPUT" || fieldType == "HIDDEN") {
            if (!VAL_IsBlank( form.elements[fieldName].value )) {
              retVal = "";
            }
      } else if (fieldType == "INPUTSHADOW") {
            // for shadows set the real field to blank if the shadow one is
            if (!VAL_IsBlank( form.elements[VALLOC.VAL_GetShadowFieldName(fieldName)].value )) {
              retVal = "";
            } else {
                  form.elements[fieldName].value = "";
            }
      }
      return retVal;
}

function VAL_IsBlankNumber(
      form,      // a form reference with the number to validate
      fieldName // the field name
)
{
      return VAL_IsBlankField(form, fieldName, "INPUTSHADOW");
}

// ------------------------------------------------------------------------ //
// Gets the "shadow" name for a field.  Returns blank if the field cannot be parsed.
function VAL_GetShadowFieldName (
      fieldName
)
{
      var retVal = "";
      var stringArray = fieldName.split( "_" );
      var numberChunks = stringArray.length;
      if (numberChunks == 2 || numberChunks == 3) {
            retVal = stringArray[0] + "_" + stringArray[1] + "SHADOW";
            if (numberChunks == 3) {
            			retVal += "_" + stringArray[2];
            }
      }
      return retVal;
}

// ------------------------------------------------------------------------ //
// Check if Shadow Field Exists or not
function VAL_ShadowFieldExists (
      form,
      fieldName
)
{
     var retVal = false;
     if (eval( form.elements[VAL_GetShadowFieldName(fieldName)] )) {
      	retVal = true;     
     }
     
     return retVal;
}

// ------------------------------------------------------------------------ //
// Checks if there is a "shadow" field and sets the focus on the "shadow" name for a field. 
// Otherwise focus is set on the given field
function VAL_SetFocusOnField (
			form,
      fieldRef
)
{
	var shadowFieldRef = VAL_GetShadowFieldName(fieldRef.name);
	if (eval( form.elements[shadowFieldRef] )) {
		form.elements[shadowFieldRef].focus();
	} else {
		fieldRef.focus();
	}
}
 
//-->
