/* *******************************************************************
global.js contains global JavaScript functions.

NB: Only functions that are generic and common to multiple applications 
on this server should be included in this file.
******************************************************************* */


/* *******************************************************************
General string functions
******************************************************************* */

/* ===================================================================
PROCEDURE: trim()

PURPOSE:
Removes leading and trailing spaces from a string.
	
PARAMETERS:
none

RETURN VALUE:
String:	Trimmed input string.

EXAMPLE:
trim('  hello  ') // Returns 'hello'

HISTORY:
2005-02-09, C.Krook: Originated.
=================================================================== */

function trim(inputString) {
	//return inputString.replace(/^\s*/,"").replace(/\s*$/,"");  
	return inputString.replace(/^\s+|\s+$/g,"");
}

/* ===================================================================
PROCEDURE: allTrim()

PURPOSE:
Removes leading and trailing spaces from a string, and replaces 
multiple embedded spaces with a single space.
	
PARAMETERS:
inputString:	Required string - to be trimmed.

RETURN VALUE:
string:	Trimmed input string.

EXAMPLE:
allTrim('  John    Bull  ') // Returns 'John Bull'
	
HISTORY:
2005-02-09, C.Krook: Originated.
=================================================================== */

function allTrim(inputString) {
	return trim(inputString).replace(/\s+/g," ");
}

/* ===================================================================
PROCEDURE: pCase()

AUTHOR: Chris Hohmann

SOURCE: http://www.aspfaq.com/show.asp?id=2299

PURPOSE:
Converts a string to proper case (initial capitals).
	
PARAMETERS:
inputString:	Required string - To be converted to proper case.
	
RETURN VALUE:
String:	Proper cased input string.

EXAMPLE:
pCase('john bull') // Returns 'John Bull'
=================================================================== */

function pCase(inputString) {
	return inputString.replace(/(\w)(\w*)/g,function
		(
			strMatch,
			strFirst,
			strRest,
			intMatchPos,
			strSource
		) {
			return strFirst.toUpperCase()
			+strRest.toLowerCase();
		});
}

/* ===================================================================
PROCEDURE: replaceSubstring()

PURPOSE:
Searches a string for an occurance of a substring, and replaces it 
if found, with optional case sensitivity.
	
PARAMETERS:
inputString:	Required string - string to be searched.
badString:		Required string - substring to be replaced.
goodString:		Required string - replacement string.
caseSensitive:	Optional Boolean - to flag case-sensitive search.
	
RETURN VALUE:
String:	The modified string, or the original string if the substring was not found.

EXAMPLE:
replaceSubstring('John is a bad boy', 'bad', 'good') // Returns 'John is a good boy'
replaceSubstring('John is a BAD boy', 'bad', 'good', true) // Returns 'John is a bad boy'

HISTORY:
2005-03-16, C.Krook: Originated.
=================================================================== */

function replaceSubstring(inputString, badString, goodString, caseSensitive) {
	fixedReplace = "";
	UI = inputString;
	UB = badString;
	
	if ((caseSensitive != 1) && (caseSensitive != true)) {
		UI = inputString.toUpperCase();
		UB = badString.toUpperCase();
	}
	badEnd = -1;
	badLoc = UI.indexOf(UB);
	if (badLoc != -1) {
		for (x=1; (badLoc != -1); x++) {
			fixedReplace = fixedReplace + inputString.substring((badEnd + 1), badLoc) + goodString;
			badEnd = badLoc + UB.length - 1;
			badLoc = UI.indexOf(UB, (badLoc + 1));
		}
		fixedReplace = fixedReplace + inputString.substring((badEnd + 1), inputString.length);
	}
	else {
		fixedReplace = inputString;
	}
	
	return fixedReplace;
}

/* ===================================================================
PROCEDURE: isValidEmail()

PURPOSE:
Checks the validity of an e-mail address using only two basic 
conditions: a period located after the 3rd character, and an "@" 
located after the 1st chacter, e.g. a@b.com.
	
PARAMETERS:
sEmail: Required string - the e-mail address to be validated.
	
RETURN VALUE:
Boolean:	true = valid; false = invalid.

EXAMPLE:
isValidEmail('a.b@c.com') // Returns true
	
HISTORY:
2005-03-14, C.Krook: Originated.
=================================================================== */

function isValidEmail(sEmail) {
	return (sEmail.indexOf(".") > 2) && (sEmail.indexOf("@") > 0);
}

/* ===================================================================
isEmailValid() checks the validity of an e-mail address using a 
regular expression:

AUTHOR: Chris Hohmann

SOURCE: http://www.aspfaq.com/show.asp?id=2238
=================================================================== */

function isEmailValid(sEmail) {
	return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w{2,}$/.test(sEmail);
}

/* ===================================================================
PROCEDURE: arrayIndexOfStr()

PURPOSE:
Searches an array of strings for the token string.
	
PARAMETERS:
sArray:		Required string array - to search for sToken.
sToken:		Required string - to look for in sArray.
bCaseSens:	Optional Boolean - to flag case sensitive search. Defaults to non-case sensitive search.
	
RETURN VALUE:
integer:	Index of sToken in sArray, or -1 to indicate sToken not found in sArray.

EXAMPLE:
alert(((arrayIndexOfStr(['Dog', 'Cat', 'Mouse'], 'cat') > -1) ? 'Found' : 'Not found')); // 'Found'
alert(((arrayIndexOfStr(['Dog', 'Cat', 'Mouse'], 'cat', true) > -1) ? 'Found' : 'Not found')); // 'Not found'
	
HISTORY:
2005-04-14, C.Krook: Originated.	
=================================================================== */

function arrayIndexOfStr(sArray, sToken, bCaseSens) {
	var i;
	var iMatch = -1;

	for (i = 0; i < sArray.length; i++) {
		if (bCaseSens) {
			if (sToken == sArray[i]) {
				iMatch = i;
				break;
			}
		}
		else {
			if (sToken.toLowerCase() == sArray[i].toLowerCase()) {
				iMatch = i;
				break;
			}
		}
	}

	return iMatch;
}

/* ===================================================================
PROCEDURE: rightStr()

PURPOSE:
Returns a specified number of characters from the right-hand side 
of a String object.

PARAMETERS:
sSource:	Required string - from which to extract characters.
iChars:		Required integer - number of characters to extract.

RETURN VALUE:
string:		The specified number of right-hand characters.

EXAMPLE:
rightStr('R.A. Grace M. Hopper', 3) // Returns 'per'

HISTORY:
2005-04-22, C.Krook: Originated.
=================================================================== */

function rightStr(sSource, iChars) {
	var iLen;
	var sSub =''; // Default return value.

	if ((typeof sSource == 'string') && (typeof iChars == 'number') && (iChars > 0)) {
		sSub = sSource; // Amend default return value.
		iLen = sSource.length;
		if (iChars <= iLen) {
			sSub = sSource.substr(iLen - iChars, iChars)
		}
	}

	return sSub;
}

/* *******************************************************************
Cookies
******************************************************************* */

/* ===================================================================
cookies.js

SOURCE:
Derived from Chapter 6, JavaScript Application Cookbook by Jerry Bradenbaugh. 
Copyright 1999 O'Reilly & Associates, Inc. ISBN: 1-56592-577-7.
Downloaded from http://www.oreilly.com/catalog/jscook/index.html
Derived from the Bill Dortch code at http://www.hidaho.com/cookies/cookie.txt

HISTORY:
2005-02-18, C.Krook: Added code from above source.
=================================================================== */

function getCookieVal (offset) {
	// This is an internal function only: Do not call directly.
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) { endstr = document.cookie.length; }
	return unescape(document.cookie.substring(offset, endstr));
}

function SetCookie (name,value,expires,path,domain,secure) {
	// The name and value arguments are mandatory.
	document.cookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
}

function GetCookie (name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) {
			return getCookieVal (j);
		}
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break; 
	}
	return null;
}

function DeleteCookie (name,path,domain) {
	if (GetCookie(name)) {
		document.cookie = name + "=" +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

/* ===================================================================
Test whether the user accepts cookies.

Amended version of WM_acceptsCookies, obtained from...

SOURCE: Webmonkey Code Library http://www.hotwired.com/webmonkey/javascript/code_library/

AUTHOR: Nadav Savio nadav@wired.com

HISTORY:
2005-02-18, C.Krook: Added code from above source.
=================================================================== */

function AcceptsCookies () {
	var acceptsCookies = false;
	
	// Check if there are currently any cookies.
	if(document.cookie == '') {
		// Try to set a cookie.
		document.cookie = 'acceptsCookies=yes';
		
		// If it succeeds, set return variable.
		if(document.cookie.indexOf('acceptsCookies=yes') != -1) {
			acceptsCookies = true;
		}
	}
	else {
		// There was already a cookie.
		acceptsCookies = true;
	}
	
	return acceptsCookies;
}

/* ===================================================================
PROCEDURE: fixDate()

PURPOSE:
The Macintosh version of Netscape Navigator 2.0x is one day in the future.
This procedure fixes the bug.
Hand all instances of the Date object to this function for "repairs".

PARAMETERS:
date:	Any instance of the Date object.

RETURN VALUE:
nothing

HISTORY:
2005-05-26, C.Krook: Originated.
=================================================================== */


function fixDate(date) {

   var base = new Date(0);
   var skew = base.getTime();
   
   if (skew > 0) date.setTime(date.getTime() - skew);
}

/* ===================================================================
PROCEDURE: SetPersistentCookie()

PURPOSE:
Sets a cookie that is persistent across browser sessions.
NB: There is a limit to cookie storage size!

PARAMETERS:
See SetCookie()

RETURN VALUE:
nothing

HISTORY:
2005-05-26, C.Krook: Originated.
=================================================================== */

function SetPersistentCookie(name,value,path,domain,secure) {

	var today = new Date();
	var expdate = new Date(today.getTime() + 1000 * 60 * 60 * 24 * 365); // One year from now.
	
	fixDate(expdate);
	SetCookie(name,value,expdate,path,domain,secure);
}

/* ===================================================================
PROCEDURE: SetSessionCookie()

PURPOSE:
Sets a cookie value that is discarded when browser is closed.
Use this unless you have a legitimate requirement for persistence
across browser sessions.

PARAMETERS:
See SetCookie()

RETURN VALUE:
nothing

HISTORY:
2005-05-26, C.Krook: Originated.
=================================================================== */

function SetSessionCookie(name,value,path,domain,secure) {
	SetCookie(name,value,false,path,domain,secure);
}

/* *******************************************************************
Standard form validation procedures
******************************************************************* */

/* ===================================================================
Global variables for standard form validation.
=================================================================== */

var DEF_CHOICE = '<- Select ->';
var INVALID_BKGROUND = '#FFFFCC';
var VALID_BKGROUND = '#FFFFFF';

/* ===================================================================
PROCEDURE: doFormValidation()

PURPOSE:
Provides generic validation of the content of fields depending on their types.

PARAMETERS:
asFieldNames:		Required string array - Each element is the name of a field to be validated.
asInvalidMessages:	Required string array - Parallel to asFieldNames, each element is an 
					error message to display when its counterpart field name fails validation.
asRegExp: 			Optional string array - Parallel to asFieldNames, each element is a regular 
					expression to apply to its counterpart field, e.g. to test for a minimum 
					number of characters.
bHighlightInvalid:	Optional Boolean - Flag to indicate whether fields should be highlighted if 
					they fail validation.
avAttachments:		Optional variant array - Three elements: 1) An integer: The value of 
					gvAttachments in sfGlobalFormHeader to indicate number of saved attachments 
					document has; 2) A string: An error message if none of the file upload controls 
					contains a value, and there are no pre-existing attachments; 3) (Optional) An 
					integer: The maximum number of files that should be attached to the current 
					document (comparing new file uploads, current attachments, and current 
					attachments marked for deletion). The presence of this array argument 
					signals doFormValidation() that attachment validation must be done.
bFocusOnInvalid:	Optional Boolean - controls whether focus should be placed on first field to fail validation.

NB: Specify null for earlier optional arguments not passed when passing later optional arguments, 
e.g. doFormValidation(['a','b'], ['X','Y'], null, true);	

RETURN VALUE:
The function returns a string, not a Boolean.  Instead of a Boolean to indicate a pass or fail, 
the function returns an empty string if validation passes, or a string of error messages if 
validation fails.  We return a string rather than a Boolean so that the caller, (usually a function 
in a form's JS Header that is triggered by a document Save button), can optionally do further 
conditional validation on the form. For example, if a radio button's value is 'Y' then field A 
should contain an alpha value, or if the radio button's value is 'N' then field B should contain 
a numeric value.  These sort of conditional validations can't be handled in this function 
because it is a generic field validation routine.

EXAMPLE:
var asFieldNames = ['fldFirstName', 'fldAge'];
var asInvalidMessages = [' - Enter your first name', ' - Enter your age'];
var asRegExp = ['', /^\d+$/];
var sErrorMsgs;

// Validate fields in this stage form.
sErrorMsgs = doFormValidation(asFieldNames, asInvalidMessages, asRegExp, true);

// Display error messages.
if (isFormValid(sErrorMsgs)) {
	return true; // Signal doActionSaveModDlg() to submit.
}
else {
	sErrorMsgs = 'You cannot save this document until the following mandatory fields have been completed:\n' + sErrorMsgs;
	alert(sErrorMsgs);
	return false; // Signal doActionSaveModDlg() not to submit.
}

HISTORY:
2005-02-25, C.Krook: Originated.
2005-03-01, C.Krook: Added password type with 5-character RE.
2005-03-02, C.Krook: Added handling of empty string in field name array to allow conditional inclusion in calling routine.
					 Added restoration of background colour for previously invalid fields now valid.
2005-03-03, C.Krook: Removed oSubmitButton arg.
					 Added vaAttachments for file upload control and attachhments validation.
2005-04-19, C.Krook: Added bFocusOnInvalid argument.
2005-04-22, C.Krook: Removed call to chkCbRbFldVal() and removed chkCbRbFldVal() procedure itself.
					 Withdrew embedded switch for checkbox / radio button type.
=================================================================== */

function doFormValidation(asFieldNames, asInvalidMessages, asRegExp, bHighlightInvalid, vaAttachments, bFocusOnInvalid) {

	var form = document.forms[0];
	var sFldType;
	var sFldName;
	var sFldMsg;
	var sRegExp;
	var bHighlight = (bHighlightInvalid);
	var sReturnErrMsgs = '';
	var bCbRb;
	var bFirstFocus = true;

	// Validate values of specified field names.
	for (var i=0; i<asFieldNames.length; i++) {

		// Initialise this field name, etc.
		sFldName = asFieldNames[i];
		sFldMsg = asInvalidMessages[i];
		sRegExp = ((asRegExp) ? asRegExp[i] : '');
		bCbRb = false; // Set checkbox / radio button flag to allow focus on validation failure.
		
		// Field name array elements can be an empty string to allow conditional inclusion in calling routine.
		if (sFldName != '') {

			// Check value depending on field type.
			sFldType = eval('form.' + sFldName + '.type');
			switch (sFldType) {
			case 'password':
				sRegExp = /^.{5,}$/;  // Temporary override RE for password length.
				sReturnErrMsgs += chkTxtFldVal(form, sFldName, sFldMsg, sRegExp, bHighlight);
				break;
			case 'text':
				sReturnErrMsgs += chkTxtFldVal(form, sFldName, sFldMsg, sRegExp, bHighlight);
				break;
			case 'textarea':
				sReturnErrMsgs += chkTxtFldVal(form, sFldName, sFldMsg, sRegExp, bHighlight);
				break;
			case 'select-one':
				if (eval('form.' + sFldName + '.options[form.' + sFldName + '.selectedIndex].text == DEF_CHOICE')) {
					if (bHighlight) eval('form.' + sFldName + '.style.backgroundColor = INVALID_BKGROUND');
					sReturnErrMsgs += (sFldMsg + '\n');
				}
				else {
					// Set the field background for valid value.
					if (bHighlight) eval('form.' + sFldName + '.style.backgroundColor = VALID_BKGROUND');
				}
				break;
			case 'select-multiple':
				if (eval('form.' + sFldName + '.selectedIndex') == -1) {
					if (bHighlight) eval('form.' + sFldName + '.style.backgroundColor = INVALID_BKGROUND');
					sReturnErrMsgs += (sFldMsg + '\n');
				}
				else {
					// Set the field background for valid value.
					if (bHighlight) eval('form.' + sFldName + '.style.backgroundColor = VALID_BKGROUND');
				}
				break;
			default:
				// Validate checkbox / radio button.
				// We need to check the type of both single and multi-value fields.
				if (	isNaN(eval('form.' + asFieldNames[i] +'.length')) && 
						(arrayIndexOfStr(['checkbox', 'radio'], eval('form.' + asFieldNames[i] + '.type')) > -1) || 
						(arrayIndexOfStr(['checkbox', 'radio'], eval('form.' + asFieldNames[i] + '[0].type')) > -1)) {
					if (!isCbRbChecked(form, sFldName)) {
						bCbRb = true; // Prevents focus on validation failure.
						// Don't highlight invalid checkboxes and radio buttons (looks bad).
						sReturnErrMsgs += (sFldMsg + '\n');
					}
				}
				break;
			}
		}
/* 

Jis- Removing this section to avoid automatic focus on the first field.


		Because bFocusOnInvalid is an additional, optional argument, 
		added long after doFormValidation() first put into production, 
		and because the JavaScript IF statement can automatically evaluates 
		an empty argument as false, we must do some extraordinary testing of 
		the argument to decide how to use its default and explicit values.

		if (	(typeof bFocusOnInvalid != 'boolean') ||
				(typeof bFocusOnInvalid == 'boolean') && (bFocusOnInvalid == true)) {

			// Focus on first field that fails validation.
			if (bFirstFocus && sReturnErrMsgs) {

				// Don't focus on a radio button field.
				if (!bCbRb) {
					eval('form.' + sFldName + '.focus()');
				}
				
				// Prevent subsequent focus (only focus on the first invalid field).
				bFirstFocus = false;
			}

		}

End of Removing Section 

*/

	}

	// Validate file upload controls.
	if (vaAttachments) sReturnErrMsgs += validateAttachments(form, vaAttachments);

	return sReturnErrMsgs;
}

/* ===================================================================
PROCEDURE: chkTxtFldVal()

PURPOSE:
NB: This is an internal function only.

Used by doFormValidation() to get a text or textarea field value.

PARAMETERS:
form:		Required object - the form element on whichh the text field resides.
sFldName:	Required string - the name of the text field.
sFldMsg:	Required string - the validation failed user message.
sRegExp:	Optional string - a regular expression to further validate the text field.
bHighlight:	Optional Boolean - a flag to switch on background colour for an invalid field.

RETURN VALUE:
string: sFldMsg + new line character if validation fails, or empty string if it passes.

HISTORY:
2005-02-25, C.Krook: Originated.
2005-03-01, C.Krook: Coded for use regular expression argument.
2005-03-02, C.Krook: Fixed 'undefined' return value for valid fields introduced with RE handling.
					 Added restoration of background colour for previously invalid field now valid.
=================================================================== */

function chkTxtFldVal (form, sFldName, sFldMsg, sRegExp, bHighlight) {

	var sTmp = trim(eval('form.' + sFldName + '.value'));
	var sReturn = '';

	// Test if trimmed field contains a value.
	if (sTmp == '') {
		if (bHighlight) eval('form.' + sFldName + '.style.backgroundColor = INVALID_BKGROUND');
		sReturn += (sFldMsg + '\n');
	}
	else {
		// Test field value against regular expression.
		if (sRegExp) {
			if (!sRegExp.test(sTmp)) {
				sReturn += (sFldMsg + '\n');
			}
		}
	}
	
	// Set the field background for valid value.
	if ((sReturn == '') && (bHighlight)) {
		eval('form.' + sFldName + '.style.backgroundColor = VALID_BKGROUND');
	}

	return sReturn;
}

/* ===================================================================
PROCEDURE: isFormValid()

PURPOSE:
Switches the Boolean evaluation of the doFormValidation() function's return value.
	
JavaScript allows Boolean evaluation of a string, e.g. ('abc') is true and ('') is false, 
but doFormValidation() returns an empty string when a form passes validation, and a 
non-empty string when it fails.  The isFormValid() function provides a clearer way of 
testing whether the form has passed or failed validation by switching the evaluation of 
the doFormValidation() function's return value. This allows us to write code within 
validateThisForm() similar to the following:
	
	// Pass a Boolean back to doActionSave().
		if (isFormValid(sErrorMsgs) {
			return true; // Signals doActionSave() to submit.
		}
		else {
			return false; // Signals doActionSave() not to submit.
		}
	
PARAMETERS:
sValidationErrMsg:	Required string - message to evaluate
	
RETURN VALUE:
Boolean:	true if message is empty string; false if message is not empty string.

HISTORY:
2005-02-28, C.Krook: Originated.
=================================================================== */

function isFormValid(sValidationErrMsg) {
	return ((sValidationErrMsg) ? false : true); // Switch evaluation of empty string.
}

/* ===================================================================
PROCEDURE: validateAttachments()

PURPOSE:
NB: This is an internal function only.
	
Used by doFormValidation() to validate attachments to the current form 
and Notes document by checking the file upload controls, existing attachments,
and attachment deletion checkboxes. Returns a Boolean.
	
PARAMETERS:
form:			Required object - the form element on whichh the text field resides.
vaAttachments:	Required variant array - (see doFormValidation() argument of the same name).
	
RETURN VALUE:
string:	The error message element from the vaAttachments argument.

HISTORY:
2005-03-03, C.Krook: Originated.
2005-03-04, C.Krook: Added optional max. attachments array element.
=================================================================== */

function validateAttachments(form, vaAttachments) {

	var FILES_ATTACHED = vaAttachments[0];	// The number of files already attached.
	var ERROR_MESSAGE = vaAttachments[1];	// Error message to display if insufficient files.
	var MAX_ATTACHMENTS = vaAttachments[2];	// Optional - could be undefined.

	var oEl;
	var iAttachCnt = 0;
	var iDetachCnt = 0;
	var sRetErrMsg = '';

	// First, check whether any of the file upload controls contain a value, 
	// and if there are any attached files marked for deletion.
	for (i=0; i<form.elements.length; i++) {
		oEl = form.elements[i];
		switch (oEl.type) {
		case 'file':
			if (trim(oEl.value) != '') {
				iAttachCnt++;
			}
			break;
		case 'checkbox':
			if (oEl.name.toLowerCase().substr(0,8) == '%%detach') {
				if (oEl.checked) {
					iDetachCnt++;
				}
			}
			break;
		}
	}
	
	// Second, check how many of the pre-existing file attachments are marked for deletion.
	if ((iAttachCnt == 0) && (iDetachCnt == FILES_ATTACHED)) {
		sRetErrMsg = ERROR_MESSAGE;
	}
	
	// Third, check that there aren't too many files attached.
	if (MAX_ATTACHMENTS != undefined) {
		if ((FILES_ATTACHED - iDetachCnt + iAttachCnt) > MAX_ATTACHMENTS) {
			sRetErrMsg = ERROR_MESSAGE;
		}
	}
	
	return sRetErrMsg;
}

/* *******************************************************************
Miscellaneous procedures.
******************************************************************* */

/* ===================================================================
PROCEDURE: reloadIFrame()

PURPOSE:
Reloads the source of an IFrame on a specified window.

PARAMETERS:
oWin:		Required object - Window on which IFrame resides.
sIFrameID:	Required string - ID of IFrame to be reloaded.

RETURN VALUE:
nothing

EXAMPLES:
reloadIFrame(window, 'ifManDaysVw'); // E.g. from button on document containing IFrame.
reloadIFrame(window.top, 'ifManDaysVw'); // E.g. from h'link within view embedded in IFrame.
reloadIFrame(window.dialogArguments, 'ifManDaysVw'); // E.g. from procedure in modal dialog passed opening window.
reloadIFrame(window.dialogArguments.parent, 'ifManDaysVw'); // E.g. from procedure in modal dialog popped up by modal dialog opened from main window.

HISTORY:
2005-04-08, C.Krook: Originated.
2005-04-11, C.Krook: Changed position of window argument in argument list, 
			and changed it from optional to required.
2005-04-13, C.Krook: Withdrew sSrc argument and exchanged src reassignment with document.location.reload.
2005-06-26, D.Reynolds: Modified the function to reload the entire window when an iFrame cannot be re-loaded 
			indepenantly. This occurs when the Iframe is in a modal window.
			This function works in conjunction with a funciton that detects the return value
			'reload'
=================================================================== */

function reloadIFrame(oWin, sIFrameID) {
	
	var oIF;
	var sSrc;
	
	// Check if the specified window contains an IFrame with the specified ID.
	oIF = oWin.document.getElementById(sIFrameID);
	if (oIF) {
		// Reload the IFrame's contents.
		oWin.document.frames(sIFrameID).document.location.reload(true);
	}
	
	//D.R. 2005-06-26 Added this 
	if (sIFrameID == 'reload') {
		oWin.returnValue = 'reload';
	 	oWin.close();
	}
	
	
	return;
}

/* ===================================================================
PROCEDURE: doAddNewOptionSel()

PURPOSE:
This procedure makes it possible to append a new, selected option to a SELECT 
HTML element (i.e. a Notes Dialog list) using a value derived from a popup 
window (usually a modal dialog). Whilst it is usually possible to write a 
value to a main window from a popup, a dialog list in the main window can't 
be written to from the popup because it requires the creation of an Option 
object on the main form which IE SP1 no longer permits from a popup.
	
If there are multiple SELECT elements with the same name, the new option is 
only appended to the first element.
	
The sText argument is only deemed to be optional in case it has been 
derived from a field value on a form that has not been validated.
	
If the element type is select-multiple (i.e. Notes Dialog list 
'Allow multiple values' property is selected), then options (choices) already 
selected are preserved.  If only one choice is allowed, and a choice has 
already been selected, then that choice is automatically deselected.
	
NB: This procedure should be visible to the main window, and called from a 
popup window (modal dialog).

PARAMETERS:
oForm:		Required object - a form object (usually document.forms[0]).
sFldName:	Required string - the name of a SELECT element on the form.
sText:		Optional string - the text to be appended to the SELECT element 
			(i.e. text property to be assigned to a new OPTION).
sVal:		Optional string - the value property of the new option

RETURN VALUE:
nothing

EXAMPLES:
openerWin.doAddNewOptionSel(document.forms[0], 'FavColours', 'Blue', '#0000FF')

HISTORY:
2005-04-20, C.Krook: Originated.
=================================================================== */

function doAddNewOptionSel(oForm, sFldName, sText, sVal) {

	var oNewOption;
	var oSelect;

	// Test argument in case it was derived from an unvalidated form field.
	if (trim(sText) != '') {

		// Instantiate a new option object and assign its properties.
		oNewOption = new Option();
		oNewOption.text = trim(sText);
		oNewOption.value = ((sVal) ? sVal : '');

		// Append new option to select element, and set it to selected.
		/* This does not work if there are multiple select items with the same name...
		eval('oForm.' + sFldName + '.add(oNewOption)');
		eval('oForm.' + sFldName + '.options[oForm.' + sFldName + '.length-1].selected = true');
		*/
		oSelect = oForm.elements(sFldName,0);
		if (oSelect) {
			oSelect.add(oNewOption);
			oSelect.options[oSelect.options.length-1].selected = true;
		}
	}
	
	return;
}

/* ===================================================================
PROCEDURE: isCbRbChecked()

PURPOSE:
Determines if any of the values of a checkbox or radio button are checked.

Handles both single and multi-value checkboxes and radio buttons.

PARAMETERS:
oForm:		Required object - a form object (usually document.forms[0]).
sFldName:	Required string - the name of a checkbox or radio button input element on the form.

RETURN VALUE:
Boolean:	true = checked; false = not checked.

EXAMPLES:
if (!isCbRbChecked(document.forms[0], 'FavColours')) {
	alert('Please select a favourite colour.');
}

HISTORY:
2005-04-20, C.Krook: Originated.
=================================================================== */

function isCbRbChecked(form, sFldName) {

	var bChecked = false;
	var iLength = eval('form.' + sFldName + '.length');

	// Determine number of available choices in element.
	if (isNaN(iLength)) {

		// Evaluate single-choice.
		if (eval('form.' + sFldName + '.checked')) {bChecked = true};
	}
	else {

		// Evaluate multiple choices.
		for (var i=0; i<iLength; i++) {
			if (eval('form.' + sFldName + '[' + i + '].checked')) {bChecked = true};
		}
	}

	return bChecked;
}

/* ===================================================================
PROCEDURE: getCbRbSelVals()

PURPOSE:
Gets the selected value(s) from a checkbox or radio button.

Handles both single and multi-value checkboxes and radio buttons.

You can test whether any values are selected by testing the length 
property of the returned object (see Examples).
	
PARAMETERS:
oForm:		Required object - a form object (usually document.forms[0]).
sFldName:	Required string - the name of a checkbox or radio button input element on the form.

RETURN VALUE:
Object:	An array of one or more values if any checkbox or radio button values selected, 
		or an empty array if no values selected.

EXAMPLES:
if (getCbRbSelVals(document.forms[0], 'FavColours').length == 0) {
	alert('You have not selected a favourite colour!');
}

HISTORY:
2005-04-20, C.Krook: Originated.
=================================================================== */

function getCbRbSelVals(form, sFldName) {

	var iLength = eval('form.' + sFldName + '.length');
	var saValues = new Array();
	var iArrInd = 0;

		// Determine number of available choices in element.
		if (isNaN(iLength)) {

			// Evaluate single-choice.
			if (eval('form.' + sFldName + '.checked')) {
				saValues[iArrInd] = eval('form.' + sFldName + '.value');
			}
		}
		else {

			// Evaluate multiple choices.
			for (var i=0; i<iLength; i++) {
				if (eval('form.' + sFldName + '[' + i + '].checked')) {
					saValues[iArrInd] = eval('form.' + sFldName + '[' + i + '].value');
					iArrInd++;
				}
			}
		}

	return saValues;
}

/* ===================================================================
PROCEDURE: visToggle()

PURPOSE:
Toggles the visibility style of all elements with a specified ID when, 
for example, you wish to hide interface elements and display a processing 
message.
	
PARAMETERS:
none
	
RETURN VALUE:
nothing
	
HISTORY:
2005-04-18, C.Krook: Originated.
2005-04-22, C.Krook: Added sName argument and removed 'VisToggle' literal.
=================================================================== */

function visToggle(sName) {

	var aEl = document.getElementsByName(sName);

	for (var i = 0; i < aEl.length; i++) {
		switch (aEl[i].style.visibility) {
			case 'visible' :
				aEl[i].style.visibility = 'hidden';
				break;
			case 'hidden' :
				aEl[i].style.visibility = 'visible';
				break;
			default :
				aEl[i].style.visibility = 'visible';
				break;
		}
	}
}


//**********************************************
// function to jump view to position based on value entered
//**********************************************
function JumpToView(){
	Search = document.forms[0].Search.value;
	if(Search==""){
		alert('Please enter the string to search');
		return false;
	}
	document.location = document.location.pathname + "?OpenView&StartKey=" + Search
}
