/*
 *
 *  Application:    Item of Supply System (ISIS)
 *  Class Name :    isisUtils.js
 *
 *  Copyright 2004 LogicaCMG UK Ltd.
 *
 *  LogicaCMG UK Ltd's prior written consent is required before any part of this
 *  program is reproduced.
 *
 *  Code History
 *  Version  Date        By   Description
 * ==============================================================================
 *  1.0      05/04/05  NL   Initial Version
 *  1.1      03/05/05  AL   Added loadFrame and loadMainFrame functions
 *  1.2		 04/05/05  NL	Added getDeleteConfirmation().
 *  1.3		 05/05/05  NL	Added showNotImplementedMessage().
 *  1.4		 12/05/05  NL	Modified not implemented message.
 *	1.5		 18/05/05  NL	Added showTooltip() and hideTooltip().
 *  1.6		 18/05/05  NL	Modified tooltip layout.
 *  1.7      09/06/05  DMP  Added populateCallingForm, showPopupAt and 
 *                          getDefinitionList. Added function headers.
 *  1.8      10/06/05  AL   Altered getDefinitionList to pickup typeId value
 *  1.9      29/06/05  DMP  Altered getDefinitionList as type name is passed
 *                          in rather than the type element ID now. Resized Popup
 *  1.10     30/06/05  DMP  Added addNameToResult, closeAndPopulate, setCursorBusy
 *  1.11     14/07/05  DMP  Added numericSearchField and alphaNumericSearchField
 *                          which strip unwanted chars from the field
 *  1.12     20/07/05  DMP  Updated valid chars i numericSearchField and alphaNumericSearchField
 *  1.13	 20/07/05  NL	Added buildSMDDetailsURL() function.
 *  1.14	 20/07/05  NL   Modified buildSMDDetailsURL() to ignore spaces in element value.
 *  1.15	 29/07/05  NL	Added toggleExplanationField() function.
 *  1.16     02/08/05  DMP  Added checkEnabled and checkDisabled
 *  1.17	 02/08/05  NL	Modified getDeleteConfirmation() to accept message as input.
 *  1.18     04/08/05  AL   Added logout
 *  1.19	 09/08/05  NL	Added refreshMRCs() function.
 *  1.20	 09/08/05  NL	Added setFieldValue() and valueChanged() functions.
 *  1.21	 10/08/05  NL	Added new parms to refreshMRCs() function.
 *  1.22	 13/08/05  NL	Added updateMRCAction() and trim() functions.
 *  1.23	 16/08/05  NL	Added updateUserList() and updateUserCode() functions.
 *  1.24	 16/08/05  NL	Modified updateUserList() to blank existing users.
 *  1.25	 18/08/05  NL	Added functions to support iosDetails.jsp
 *  1.26	 25/08/05  NL	Added updateSelectedReply() function.
 *  1.27     26/08/05  DMP  Added confirmSubmitAction() function.
 *  1.28     25/08/05  AL   logout() no longer has a return value
 *  1.29	 26/08/05  NL	Updated buildSMDDetailsURL() with new action name and parameters.
 *  1.30	 28/08/05  NL	Modified refreshAIN() to pass IIG value in request.
 *  1.31	 28/08/05  NL	Modified buildSMDDetailsURL() to handle empty string.
 *  1.32	 28/08/05  NL	Removed spurious alert.
 *  1.33     30/08/05  DMP  Added printSMD()
 *  1.34	 30/08/05  NL	Added methods to support dynamic IOS user update.
 *  1.35     31/08/05  DMP  Adjusted popup sizes in printSMD()
 *  1.36	 01/09/05  NL	Modified updateSelectedReply() to trim strings.
 *  1.37	 07/09/05  NL	Added refreshQueryDetails() method.
 *  1.38	 14/09/05  NL	Modified updateDescription() to display error for invalid CSU.
 *  1.39	 27/09/05  NL	Added checkReplyComplete() function.
 *  1.40	 29/09/05  NL	Added addCurrentAddress() and getConfirmation() functions.
 *  1.41	 13/10/05  NL	Modified userTypeChanged() to always call refreshUserList.do.
 *  1.42	 24/10/05  NL	Modified parameters for buildSMDDetailsURL() function.
 *  1.43	 27/10/05  NL   Modified updateMRCAction() to no longer blank SAC if reply blank.
 *  1.44	 31/10/05  NL	Modified refreshAIN() to only refresh if INCs are not 7s or blank.
 *  1.45	 11/11/05  DS	Modified updateMRCAction() for changes to SACs - will only work properly
 *                          with ACN87 version of ValidateSubmission
 *	1.46	 11/11/05  DS	Changed AIN refresh message
 *	1.47	 15/11/05  DS	Added showPopupCheckNCAGE()
 *  1.48	 06/12/05  NL	Added populateCallingFormWithSelectedTask().
 *  1.49	 08/12/05  NL	Added showTaskSelectionPopup() method.
 *  1.50	 14/12/05  NL	Added refreshLsaNain() method.refreshLsaNain
 *	1.51     19/12/05  DS   Changed updateMRCAction() to only change action if field value has actually changed
 *  1.52	 10/01/06  NL	Added methods to support line entry popups and DCN generation for LSAs.
 *  1.53	 13/01/06  NL	Added refreshLsaFieldAvailability() function.
 *  1.54	 17/01/06  NL	Added getDeleteLSAConfirmation() function.
 *  1.55	 19/01/06  NL	Fixed populateCallingFormWithSelectedTask() to handle empty string parms.
 *  1.56	 19/01/06  NL	Added toggleL07EnquiryTaskFieldAvailability() function.
 *  1.57	 23/01/06  NL	Added addAssociatedLSA() and removeAssociatedLSA() functions.
 *  1.58	 26/01/06  NL	Replaced above functions with setHiddenAssociatedLSA() and setHiddenPotentialLSA().
 *  1.59	 27/01/06  NL	Added refreshPotentialLSAs() function.
 *  1.60	 02/02/06  NL	Added populateK27Reason() function.
 *  1.61	 09/02/06  NL	Added toggleK27EnquiryFieldAvailability() and toggleL27EnquiryFieldAvailability().
 *  1.62	 12/02/06  DS	Removed printSMD().
 *  1.63	 15/02/06  DS	Added setCursorBusy() to refreshMRCs()
 *  1.64	 20/02/06  NL	Added checkReportComplete() function.
 *  1.65	 21/02/06  NL	Added checkSRSCValue() function.
 *	1.66	 01/03/06  DS	Added setScrollPosition() for scrollable divs.
 *	1.67	 05/03/06  DS	Various improvements to task and line entry selection for LSAs.
 *	1.68     08/03/06  NL   Added showSponsorContextMenu() and setDefConMultiplier().
 *	1.69	 09/03/06  DS	refreshPotentialLSAs() - only refresh if stuff has actually changed.
 *  1.70	 10/03/06  NL	Added confirmLineWithdrawal() function.
 *  1.71	 14/03/06  NL	Fixed positioning bug in showSponsorContextMenu() function.
 *  1.72	 18/03/06  NL	Added fireProjectChanged() and fireContractorChanged() functions.
 *  1.73	 19/03/06  DS	Various bug fixes - IOS Users and MRC refresh.
 *  1.74	 22/03/06  DS	setCursorBusy on refreshAIN.
 *  1.75	 23/03/06  NL	Added parseDate() function.
 *  1.76	 29/03/06  NL	Added setHiddenAvailable640() and setHiddenAssociated640() functions.
 *  1.77	 05/04/06  DS	Do not show showSponsorContextMenu() if line entry status is D.
 *  1.78	 15/04/06  NL	Added setHiddenAvailableSite() and setHiddenAssociatedSite() functions.
 *  1.79	 20/04/06  NL	Added parseDateTime() function.
 *  1.80	 26/04/06  NL	Added setHiddenAvailableDownload(), setHiddenAuthorisedDownload(), 
 *							setHiddenAvailableUpload() and setHiddenAuthorisedUpload() functions.
 *  1.81	 09/05/06  NL	Added checkFieldLength() function.
 *  1.82	 10/05/06  NL	OR85:  Modified updateNsnRelationCode() to store selected code on form bean.
 *  1.83	 12/05/06  NL	Fixed action bug in updateMRCAction() function.
 *  1.84	 16/05/06  NL	Added deleteMRC() function.
 *  1.85	 01/06/06  NL	Added showIncMrcSummaryContextMenu() function.
 *  1.86	 21/06/06  NL	Added markRowDirty() function.
 *  1.87	 12/07/06  NL	Added showMrcValidTablesContextMenu() function.
 *  1.88	 27/07/06  NL	Added showPermittedIsacsContextMenu() function.
 *  1.89	 27/07/06  DS	Added setCursorBusyAndSubmit() function.
 *  1.90	 07/08/06  DS	Modified positioning of some context menus.
 *  1.91	 15/08/06  NL	Added displayNcbReport() function.
 *	1.92	 17/08/06  DS	Added catchBackspace(), initSelectInput(), selectListboxValue() and selectKeypress().
 *	1.93	 17/08/06  DS	Modifications to selectKeypress().
 *  1.94	 11/09/06  NL	Added closeOnComplete() function.
 *	1.95	 21/09/06  DS	Change parseDate to handle additional operators before date.
 *	1.96	 21/09/06  DS	Fix refreshPotentialLSAs to work with URL rewriting.
 *	1.97	 27/09/06  DS	Change parseDateTime to handle additional operators before date.
 *	1.98	 09/10/06  DS	Fix calls to showPopup for PCCP report. 
 *	1.99	 20/10/06  DS	Fix bug in parseDateTime.
 *	2.00	 25/10/06  DS	Add showFlashPopup and corrections to closeOnComplete.
 *	2.01	 26/10/06  DS 	OR20635 - 	Change checkReportComplete for the PCCP report so that the 2nd report is
 *										not produced if the non NATO country is not selected.
 *	2.02     15/12/06  DS	ACN109 SCR1403 - Added confirmPutTaskLine.
 *	2.03	 19/01/07  DS	ACN109 SCR1403 - Ensure integer comparison is used in above change.
 *	2.04	 28/11/07  SV	ACN114 SCR1472 - Fix the getDeleteLSAConfirmation() so cancel doesn't delete
 *	2.05	 12/02/08  DL	ACN121: Added showTooltipId function to display the tooltip for a given tooltip ID.
 *	2.06	 27/02/08  DL	ACN121: Added showResizablePopup function to display a resizable pop-up window.
 *			 28/02/08  DL	ACN121: Modified updateSelectedReply to update the RDG data according to the selected
 *							MRC reply.
 *			 03/03/08  DL	ACN121: Added constructRDGImageURL function to build the URL for an RDG image.
 *	2.07	 27/05/08  DS   ACN121: Changes to updateSelectedReply 
 *	2.08	 11/06/08  JF	ACN124: Added showETaskNcageLookupPopup()
 *	2.09	 13/06/08  DL	ACN118: Added elementDisabled function.
 *	2.10	 23/06/08  DL	ACN118: Added setHiddenSelectedItem function.
 *	2.11	 27/06/08  JF	ACN124: Added showPopupResizable()
 *	2.12	 17/09/08  JF	Added showTooltipWithStyle()
 *	2.13	 18/09/08  JF	Added return true to setCursorBusy() and setCursorBusyAndSubmit()
 *	2.14	 14/10/08  JF	Removed setCursorBusyAndSubmit()
 *	2.15	 23/10/08  DS	Modified confirmSubmitAction()
 *	2.16	 18/11/08  JF 	OR817 - Amended fireContractorChanged() and fireProjectChanged()
 *	2.17	 25/11/08  JF	OR817F1 - Amended fireContractorChanged() and fireProjectChanged() to avoid firing when newCode is empty
 *	2.18	 07/01/09  JF	Corrected a bug in all setHidden() methods
 *	2.19	 13/03/09  JF	ACN130 - Added checkDecimalValue()
 *	2.20	 29/06/09  JF	Added function showItemNamePopup()
 *  2.21     02/03/10  SV   ACN145 - altered error message in checkDecimalValue()
 *  2.22     24/06/10  SV   ACN149 - new method populateCurrentWindowDcn
 *  2.23	 09/08/10  JF	Amended populateCurrentWindowDcn() to convert the taskNo in uppercase
 *  2.24	 23/09/10  JF	Fixed a bug in buildSMDDetailsURL() to avoid building URL if space
 *	2.25	 03/12/10  DS	OR1150 - Changes to deleteMrc and updatMrcAction to support JSP changes
 *	2.26	 10/01/11  DS	OR1175 - Add busy cursor to refreshQueryDetails()
 *  2.27     16/02/11  SR   ACN154 - Added updateSrcDataAction
 *	2.28	 01/03/11  DS   Modified updateSelectedReply to use list key for coded reply
 *	2.29	 03/03/11  DS	Fix javascript error when array of RDG information contains nulls
 *	2.30	 18/05/11  SR   ACN153/ACN154 - Added showSrcDataReferenceContextMenu and showReferenceLookupContextMenu
 *	2.31	 18/05/11  SR   ACN154 - Updated ClientX to clientX in showReferenceLookupContextMenu
 *	2.32	 19/05/11  DS	Moved check report complete function to new file isisReport.js
 *-----------------------------------------------------------------------------
 */

/*-----------------------------------------------------------------------------
 * Declare global variables 
 *----------------------------------------------------------------------------- 
 */
var tooltipShowingKey = ""; // For popup tooltips

// The following two variables are needed for the interactive drop-down lists
var selectBoxInput = "";
var selectBoxInputLength = 0;

// Catch the backspace key for all documents - this only works with IE
if (window.event) {
	document.onkeydown = catchBackspace;
}

/*-----------------------------------------------------------------------------
 * Name:        catchBackspace
 * Description: Used by document onkeydown to catch the backspace keypress and stop
 *				IE going back.  If the source element is an input field, then don't
 *				catch the backspace.
 * Parameters: 
 *-----------------------------------------------------------------------------
 */
function catchBackspace()
{
	if (window.event.keyCode == 8) {
		if (window.event.srcElement.tagName.toUpperCase() == 'INPUT') {
			return true;
		}
		else {
			return false;
		}
	}
}

/*-----------------------------------------------------------------------------
 * Name:        checkEnabled
 * Description: enables an object dependent on the state of a checkbox or radio
 *              button.
 * Parameters: 
 *              check - checkbox/radio button
 *              access - object/element to enable
 *-----------------------------------------------------------------------------
 */
function checkEnabled(check, access)
{
	access.disabled = !(check.checked);
}

/*-----------------------------------------------------------------------------
 * Name:        checkDisabled
 * Description: disables an object dependent on the state of a checkbox or radio
 *              button.
 * Parameters: 
 *              check - checkbox/radio button
 *              access - object/element to disable
 *-----------------------------------------------------------------------------
 */
function checkDisabled(check, access)
{
	access.disabled = check.checked;
}

/*-----------------------------------------------------------------------------
 * Name: elementDisabled
 * Description: Sets the disabled state of an element.
 *
 * Parameters: element - an element to disable
 *			   state - the disabled state to set (either true or false)
 *-----------------------------------------------------------------------------
 */
function elementDisabled(element, state)
{
	element.disabled = state;
}

/*-----------------------------------------------------------------------------
 * Name:        numericSearchField
 * Description: Removes any non numeric character except * and space
 *
 * Parameters
 *-----------------------------------------------------------------------------
 */
 function numericSearchField( fld )
{
	if ( fld.value.length > 0 )
	{
		fld.value = fld.value.replace( /[\D^\*^ ^;^%^\x1C^\x1D]+/g, '' ) ;
	}
}

/*-----------------------------------------------------------------------------
 * Name:        alphaNumericSearchField
 * Description: Removes any non alpha numeric character except * and space
 *
 * Parameters
 *-----------------------------------------------------------------------------
 */
 function alphaNumericSearchField( fld )
{
	if ( fld.value.length > 0 )
	{
		fld.value = fld.value.replace( /[\W^\*^ ^;^%^\x1C^\x1D]+/gi, '' ) ;
	}
}


/*-----------------------------------------------------------------------------
 * Name:        setCursorBusy
 * Description: Displays a hidden form element "hideMe" the style attributes of
 *              which set the cursor to hourglass.
 *              Nice to have would be to make style opaque
 *
 * Parameters
 *				
 *-----------------------------------------------------------------------------
 */
 function setCursorBusy()
{
	hm = window.document.getElementById("hideMe") ;
	hm.style.display = "" ;
	return true;
}

/*-----------------------------------------------------------------------------
 * Name:        closeAndPopulate
 * Description: Calls populateCallingForm() and then closes the current window
 *
 * Parameters
 *				
 *-----------------------------------------------------------------------------
 */
function closeAndPopulate()
{
	populateCallingForm( ) ;
	self.close();
	
}

/*-----------------------------------------------------------------------------
 * Name:        addNameToResult
 * Description: writes the specified value to the hiddenResult field on the 
 *              The string is built up using ; as delimiters by subsequent calls
 *
 * Parameters
 *				name - Data to add to field
 *-----------------------------------------------------------------------------
 */
function addNameToResult( name )
{
    var n = new String(name) ;
	var re, r ;
	var res = new String( ) ;

	res = window.document.getElementById("hiddenResult").value ;
	
	
	if ( n == "$" ) n = "\\$" ;
	eval('re = /' + n + '(;|$)/i') ;
	r = res.search( re ) ;

	if ( r == -1 )
	{
		if ( res.length > 0 ) res = res.concat(";") ;		
		res = res.concat( n ) ;	
	}
	else
	{
		res = res.replace( re,"") ;
	}
	res = res.replace( /;;/,";") ; 
	// Strip out \$
	res = res.replace( /\\\$(;|$)/,"$") ;
	
	window.document.getElementById("hiddenResult").value = res ;
}
/*-----------------------------------------------------------------------------
 * Name:        getDefinitionList
 * Description: Function returns a definition list for the specified type
 *              in a new popup window
 * Parameters
 *				returnId - ID of the element to set with the resulting selection
 *              typeId   - ID of the element containing the type.
 *-----------------------------------------------------------------------------
 */
function getDefinitionList ( returnId, type, matchId, encodedUrlId )
{	
	match = window.document.getElementById( matchId ).value ; 
	target = "/webisis/definitionList.do?returnID=" + returnId + "&type=" + type + "&title=Select " + type + " From List" + "&match=" ; // + match ;
	return showPopupAt( target, encodedUrlId, '510', '400', 'yes', 164, 120 ) ;
}	
						
/*-----------------------------------------------------------------------------
 * Name:        populateCallingForm
 * Description: writes the specified value in hiddenResult to a field on a 
 *              popup windows calling page that is specified by the ID contained             
 *              in the hiddenReturnID field on the popup page.
 *
 * Parameters
 *-----------------------------------------------------------------------------
 */
function populateCallingForm(  )
{
	var cur = new String() ;
	
	eval('val = window.document.getElementById("hiddenResult").value') ;
	eval('ret = window.document.getElementById("hiddenReturnID").value') ;
	eval('cur = window.opener.document.getElementById("' + ret + '").value');
	if  ( cur.length > 0 )
	{
		eval('window.opener.document.getElementById("' + ret + '").value = window.opener.document.getElementById("' + ret + '").value + ";" + val') ;	
	}
	else
	{
		eval('window.opener.document.getElementById("' + ret + '").value = val') ;		
	}
}
/*-----------------------------------------------------------------------------
 * Name:        populateCallingFormBy
 * Description: writes the specified value to a field on a popup windows
 *              calling page that is specified by the ID contained in 
 *              the hiddenReturnID field on the popup page.
 *
 * Parameters
 *				val	- value to set
 *-----------------------------------------------------------------------------
 */
function populateCallingFormBy( val )
{
	eval('ret = window.document.getElementById("hiddenReturnID").value') ;
	eval('window.opener.document.getElementById("' + ret + '").value = val') ;
	self.close();	
}

/*-----------------------------------------------------------------------------
 * Name:        showPopupAt
 * Description: Generates a popup window at the specified screen co-ords.
 * Parameters:
 *				url 		- Target URL
  *				encodedId 	- ID of an element which contains an encoded URL
 *          	width		- width of PopUp Window
 *          	height		- height of PopUp Window
 *          	scroll		- window is scrollable ( yes | no )
 *          	left		- absolute Left co-ordinate
 *          	top			- absolute Top co-ordinate
 *
 * Returns:     false
 *-----------------------------------------------------------------------------
 */
function showPopupAt(url, encodedId, width, height, scroll, left, top ) {
		
	var settings = 'left=' + left + ', top=' + top + ', resizable=0, directories=0, menubar=0, status=0, location=0, scrollbars=' + scroll + ', width=' + width + ', height=' + height;	
	var encodedUrl = url;
		
	if (encodedId != null) {
		var encodedUrl = encodeUrl(document.getElementById(encodedId).value, url);
	}
	window.open(encodedUrl, "PopUpAt", settings);
	
	return false ;
}

/*-----------------------------------------------------------------------------
 * Name:        showPopupCheckNCAGE
 * Description: Same as showPopup but just called for NCAGEs.  Checks that
 *				NCAGE is 5 characters before calling showPopup
 * Parameters:
 *				ncage		- NCAGE
 *				url 		- Target URL
 *				encodedId	- ID of an element which contains an encoded URL
 *          	windowName  - Name of the window (not displayed)
 *          	width		- Width of PopUp Window
 *          	height		- Height of PopUp Window
 *          	scrollbars	- Window is scrollable ( yes | no )
 *
 * Returns:     false
 *-----------------------------------------------------------------------------
 */
function showPopupCheckNCAGE(ncage, url, encodedId, windowName, width, height, scrollbars) {

	if (ncage.length == 5) {
	
		showPopup(url,encodedId,windowName,width,height,scrollbars);
		
	}
	
	return false ;
}

/*-----------------------------------------------------------------------------
 * Name:        showItemNamePopup
 * Description: Same as showPopup but just add the current name to the URL.
 * Parameters:
 *				url 		- Target URL
 *				itemNameId	- Element ID to get the value from
 *				encodedId	- ID of an element which contains an encoded URL
 *          	windowName  - Name of the window (not displayed)
 *          	width		- Width of PopUp Window
 *          	height		- Height of PopUp Window
 *          	scrollbars	- Window is scrollable ( yes | no )
 *
 * Returns:     false
 *-----------------------------------------------------------------------------
 */
function showItemNamePopup(url, itemNameId, encodedId, windowName, width, height, scrollbars) {

	var callingFieldVal = document.getElementById(itemNameId).value;
	var newURL = url + "&itemName=" + callingFieldVal;

	showPopup(newURL,encodedId,windowName,width,height,scrollbars);
}

/*-----------------------------------------------------------------------------
 * Name:        showPopup
 * Description: Generates a popup window.
 * Parameters:
 *				url 		- Target URL
 *				encodedId	- ID of an element which contains an encoded URL
 *          	windowName  - Name of the window (not displayed)
 *          	width		- Width of PopUp Window
 *          	height		- Height of PopUp Window
 *          	scrollbars	- Window is scrollable ( yes | no )
 *
 * Returns:     false
 *-----------------------------------------------------------------------------
 */
function showPopup(url, encodedId, windowName, width, height, scrollbars) {
		
	var winl = (screen.width)?(screen.width-width)/2:100;
	var wint = (screen.height)?(screen.height-height)/2:100;
	var settings = 'left=' + winl + ', top=' + wint + ', resizable=0, directories=0, menubar=0, status=0, location=0, scrollbars=' + scrollbars + ', width=' + width + ', height=' + height;
	var encodedUrl = url;
		
	if (encodedId != null) {
		var encodedUrl = encodeUrl(document.getElementById(encodedId).value, url);
	}
	win = window.open(encodedUrl, windowName, settings);
	
	return false ;
}

/*-----------------------------------------------------------------------------
 * Name:        showPopupResizable
 * Description: Generates a popup window.
 * Parameters:
 *				url 		- Target URL
 *				encodedId	- ID of an element which contains an encoded URL
 *          	windowName  - Name of the window (not displayed)
 *          	width		- Width of PopUp Window
 *          	height		- Height of PopUp Window
 *          	scrollbars	- Window is scrollable ( yes | no )
 *
 * Returns:     false
 *-----------------------------------------------------------------------------
 */
function showPopupResizable(url, encodedId, windowName, width, height, scrollbars) {
		
	var winl = (screen.width)?(screen.width-width)/2:100;
	var wint = (screen.height)?(screen.height-height)/2:100;
	var settings = 'left=' + winl + ', top=' + wint + ', resizable=1, directories=0, menubar=0, status=0, location=0, scrollbars=' + scrollbars + ', width=' + width + ', height=' + height;
	var encodedUrl = url;
		
	if (encodedId != null) {
		var encodedUrl = encodeUrl(document.getElementById(encodedId).value, url);
	}
	win = window.open(encodedUrl, windowName, settings);
	
	return false ;
}

/*-----------------------------------------------------------------------------
 * Name:        showResizablePopup
 * Description: Generates a resizable popup window.
 * Parameters:
 *				url 		- Target URL
 *				encodedId	- ID of an element which contains an encoded URL
 *          	windowName  - Name of the window (not displayed)
 *          	width		- Width of PopUp Window
 *          	height		- Height of PopUp Window
 *          	scrollbars	- Window is scrollable ( yes | no )
 *
 * Returns:     false
 *-----------------------------------------------------------------------------
 */
function showResizablePopup(url, encodedId, windowName, width, height, scrollbars) {

	var winl = (screen.width)?(screen.width-width)/2:100;
	var wint = (screen.height)?(screen.height-height)/2:100;
	var settings = 'left=' + winl + ', top=' + wint + ', resizable=1, directories=0, menubar=0, status=0, location=0, scrollbars=' + scrollbars + ', width=' + width + ', height=' + height;
	var encodedUrl = url;
	
	if (encodedId != null) {
		var encodedUrl = encodeUrl(document.getElementById(encodedId).value, url);
	}
	win = window.open(encodedUrl, windowName, settings);
	
	return false ;
}

/*-----------------------------------------------------------------------------
 * Name:        loadFrame
 * Description: Loads the specified frame from the target URL
 * Parameters:
 *          	id		- ID of the frame element
 *				url 	- Target URL
 *-----------------------------------------------------------------------------
 */
function loadFrame( id, url ) {

   if ( id && url ) {
       var frame = parent.document.getElementById(id);
       if ( frame ) {
           frame.src = url;
       }
   }
}

/*-----------------------------------------------------------------------------
 * Name:        loadMainFrame
 * Description: Loads the main frame from the target URL
 * Parameters:
 *				url 	- Target URL
 *-----------------------------------------------------------------------------
 */
 function loadMainFrame( url ) {

    if ( url ) {
        loadFrame( "mainFrame", url );
    }
}

/*-----------------------------------------------------------------------------
 * Name:        getDeleteConfirmation
 * Description: Displays a confirm delete msg box
 * Parameters:
 * Returns:     True  if confirmed
 *              False if cancel
 *-----------------------------------------------------------------------------
 */
function getDeleteConfirmation(msg) {
	return window.confirm(msg);
}

/*-----------------------------------------------------------------------------
 * Name:        showNotImplementedMessage
 * Description: Displays an information msgbox indicating that the requested
 *              functionality is as yet unimplemented.
 * Parameters:
 *-----------------------------------------------------------------------------
 */
function showNotImplementedMessage() {
	alert('This functionality is not implemented in the prototype');
}

/*-----------------------------------------------------------------------------
 * Name:        showTooltip
 * Description: Displays Ben's revolutionary advancement in display technology
 * Parameters: 
 *              divName     - Name of the div to contain the tip. 
 *              rowKey      - Unique ID for this tooltip.
 *              toolTipText - Text to be displayed.
 *-----------------------------------------------------------------------------
 */
function showTooltip(divName, rowKey, tooltipText) {

	var tooltipTable = "<table width=\"100%\" height=\"100%\">" +
						"<tr valign=\"top\"><td width=\"98%\" height=\"5\">" + tooltipText + "</td><td align=\"right\" width=\"2%\" onClick=\"hideTooltip('" + divName + "', '" + rowKey + "');\" style=\"cursor:hand;\"><img src=\"jsp/images/delete.gif\"></td></tr></table>";
	
	var tooltipDiv = document.getElementById(divName + rowKey);
	
	if (tooltipShowingKey != "") {
		hideTooltip(divName, tooltipShowingKey);
	}
	
	tooltipDiv.innerHTML = tooltipTable;
	tooltipDiv.style.display = "";
	tooltipShowingKey = rowKey;
	tooltipDiv.focus();
	
}

/*-----------------------------------------------------------------------------
 * Name:        showTooltipWithStyle
 * Description: Displays Ben's revolutionary advancement in display technology
 * Parameters: 
 *              divName     - Name of the div to contain the tip. 
 *              rowKey      - Unique ID for this tooltip.
 *              toolTipText - Text to be displayed.
 *-----------------------------------------------------------------------------
 */
function showTooltipWithStyle(divName, rowKey, tooltipText, style) {

	var tooltipTable = "<table width=\"100%\" height=\"100%\">" +
						"<tr valign=\"top\"><td width=\"98%\" height=\"5\" style=\"" + style + "\">" + tooltipText + "</td><td align=\"right\" width=\"2%\" onClick=\"hideTooltip('" + divName + "', '" + rowKey + "');\" style=\"cursor:hand;\"><img src=\"jsp/images/delete.gif\"></td></tr></table>";
	
	var tooltipDiv = document.getElementById(divName + rowKey);
	
	if (tooltipShowingKey != "") {
		hideTooltip(divName, tooltipShowingKey);
	}
	
	tooltipDiv.innerHTML = tooltipTable;
	tooltipDiv.style.display = "";
	tooltipShowingKey = rowKey;
	tooltipDiv.focus();
	
}

/*-----------------------------------------------------------------------------
 * Name:        showTooltipId
 * Description: Displays the tooltip that corresponds to the tooltip ID.
 * Parameters: 
 *              divName     - Name of the div to contain the tip. 
 *              rowKey      - ID of the row the tooltip is being displayed for.
 *              toolTipId   - Unique ID for this tooltip.
 *-----------------------------------------------------------------------------
 */
function showTooltipId(divName, rowKey, tooltipId) {

	var tooltipText = document.getElementById(tooltipId).value;
	
	var tooltipTable = "<table width=\"100%\" height=\"100%\">" +
						"<tr valign=\"top\"><td width=\"98%\" height=\"5\">" + tooltipText + "</td><td align=\"right\" width=\"2%\" onClick=\"hideTooltip('" + divName + "', '" + rowKey + "');\" style=\"cursor:hand;\"><img src=\"jsp/images/delete.gif\"></td></tr></table>";
	
	var tooltipDiv = document.getElementById(divName + rowKey);
	
	if (tooltipShowingKey != "") {
		hideTooltip(divName, tooltipShowingKey);
	}
	
	tooltipDiv.innerHTML = tooltipTable;
	tooltipDiv.style.display = "";
	tooltipShowingKey = rowKey;
	tooltipDiv.focus();
	
}

/*-----------------------------------------------------------------------------
 * Name:        hideTooltip
 * Description: Hides the specified div
 * Parameters: 
 *              divName     - Name of the div
 *              rowKey      - UniqueId for the div.
 *-----------------------------------------------------------------------------
 */
function hideTooltip(divName, rowKey) {

	var tooltipDiv = document.getElementById(divName + rowKey);
	tooltipDiv.style.display = "none";
	tooltipShowingKey = "";
}		


/*-----------------------------------------------------------------------------
 * Name:        buildSMDDetailsURL(encodedAction, srcElement, callingFromPopup) {
 * Description: Builds a request URL to the smdDetails page, including the value
 *				held in the srcElement as a parameter.
 * Parameters: 
 *				encodedAction - The SMD Details Forward Action
 *              srcElement  - The element whose onClick() event called this 
 *              			  function.
 *				callingFromPopup - Boolean to indicate whether calling from IOS Details
 *								   in a popup window.
 *-----------------------------------------------------------------------------
 */
function buildSMDDetailsURL(srcElement, callingFromPopup) {
	
	var elementVal = srcElement.value;
	var smdDetailsURL = '';
	
	if ((null != elementVal) && (elementVal != '') && (elementVal != ' ')) {
		smdDetailsURL = "smdDetailsForward.do?service=" + elementVal + "&callingFromPopup=" + callingFromPopup;
	}
	srcElement.blur();
	
	if (smdDetailsURL != '') {
		return smdDetailsURL;
	}
	else {
		return false;
	}
}

/*-----------------------------------------------------------------------------
 * Name:        toggleExplanationField(l23Select, expFieldName, expLabelName)
 * Description: Hides or displays an explanation field and label depending on
 				the value of the L23 Code Combo.  
 * Parameters: 
 *              l23Select - ID of the L23 Combo.
 *				expFieldName - ID of the explanation field.
 *				expLabelName - ID of the field label.
 *-----------------------------------------------------------------------------
 */
function toggleExplanationField(l23Select, expFieldName, expLabelName) {

	var l23Combo = document.getElementById(l23Select);
	var l23Code = l23Combo.value;

	var expField = document.getElementById(expFieldName);
	var expLabel = document.getElementById(expLabelName);
	
	if (l23Code == 'F') {
		expField.style.display = "";
		expLabel.style.display = "";
	}
	else {
		expField.style.display = "none";
		expLabel.style.display = "none";
	}
}

/*-----------------------------------------------------------------------------
 * Name:        getElementsOfClass
 * Description: returns a list of elements that match a given class.
 * Parameters: 
 *              element - element tag
 *              className - class to match.
 *-----------------------------------------------------------------------------
 */
function getElementsOfClass( element, className )
{
	classList = new Array() ;
	elementList = document.getElementByTagName( element ) ;
	
	for ( i=0; i < elementList.length; i++ )
	{
		if ( elementList[ i ].className == className ) 
		{
			classList[ classList.length ] = elementList[ i ] ;
		}
	}
	
	if ( classList.length == 0 ) classList = null ;
	return classList ;
}


/*-----------------------------------------------------------------------------
 * Name:        confirmSubmitAction
 * Description: Displays an alert box requesting confirmation of an Action.
 *              The form is submitted if the action is confirmed.
 * Parameters:  msg     message to display
 *-----------------------------------------------------------------------------
 */
function confirmSubmitAction( msg ) {

	response = window.confirm( msg ) ;
	
	if ( response )
	{
		//submit the form
		setCursorBusy();
	}
	return response ;
}


/*-----------------------------------------------------------------------------
 * Name:        confirmMRCDelete
 * Description: Displays an alerting requesting confirmation of MRC deletion.
 * Parameters:  None
 *-----------------------------------------------------------------------------
 */
function confirmMRCDelete() {

	return window.confirm('Are you sure you want to remove this existing characteristic?');

}

/*-----------------------------------------------------------------------------
 * Name:        logout
 * Description: Displays a confirmation dialog displaying the confirmMessage 
 *              parameter. If the user confirms the logout then the logout page
 *              is loaded into the parent window and the current window is cloesd.
 * Parameters:  logoutUrl
 *              confirmMessage
 *-----------------------------------------------------------------------------
 */
function logout(logoutUrl, confirmMessage){
	
	var dec = window.confirm(confirmMessage);
	
	if (dec){
		window.location=logoutUrl; 
	}
}

/*-----------------------------------------------------------------------------
 * Name:        refreshMRCs
 * Description: Checks whether the MRC list needs refreshing (by determining 
 *				i) whether the relation code is in the list of active relation
 *				codes and 
 *				ii) whether the field value has changed).  
 *				If both of these conditions are met, forward to the appropriate
 * 				action, otherwise return false.
 *
 * Parameters:  activeRelationCodeStr
 *              currentRelationCode
 *				fieldName
 *				newValue
 *				mrcSessionID
 *				sacField
 *				replyField
 *-----------------------------------------------------------------------------
 */
function refreshMRCs(activeRelationCodeStr, currentRelationCode, fieldName, callingField, mrcSessionID) {
	
	var callingFieldVal = document.getElementById(callingField).value;

	//If current relation code is in active list
	if (currentRelationCode != null && currentRelationCode != '' && activeRelationCodeStr.indexOf(currentRelationCode) != -1) {
	
		// If field value has changed
		if (valueChanged(fieldName, callingFieldVal) == true) {
			//window.location="/webisis/refreshMRCs.do?mrcSessionID=" + mrcSessionID + "&sacVal=" + sacFieldVal + "&replyVal=" + replyFieldVal;

			var formElement = document.forms[0];
			var formAction = formElement.action;
			
			// Change action from iosDetails.do to refreshMRCs.do
			var newAction = formAction.replace('iosDetails.do', 'refreshMRCs.do');
			//alert(newAction);
			setCursorBusy();
			formElement.action = newAction;
			formElement.submit();
		}
		else {
			return false;
		}
	}
	else {
		return false;
	}
}

/*-----------------------------------------------------------------------------
 * Name:        setFieldValue
 * Description: Sets the value of a given field in order to work out
 *				whether a field value has changed or not.
 * Parameters:  hiddenFieldName
 *              currentValue
 *-----------------------------------------------------------------------------
 */
function setFieldValue(fieldName, currentValue){
	var field = document.getElementById(fieldName);
	field.value = currentValue;
}

/*-----------------------------------------------------------------------------
 * Name:        valueChanged
 * Description: Boolean function to compare a value with that of a given field
 *				and work out whether it has changed.
 * Parameters:  fieldName
 *				currentValue
 *-----------------------------------------------------------------------------
 */
function valueChanged(fieldName, newValue) {
	
	var fieldVal = document.getElementById(fieldName).value;
	
	if (fieldVal == newValue) {
		return false;
	}
	else {
		return true;
	}
}

/*-----------------------------------------------------------------------------
 * Name:        updateMRCAction(modeCodeField, sacField, replyField, actionField)
 * Description: Update an MRC Action field depending on modeCode, sac and reply 
 *				values.
 * Parameters:  rowID
 *				mrcField
 *				modeCodeField
 *				sacField
 *				replyField
 *				actionField
 *-----------------------------------------------------------------------------
 */
function updateMRCAction(fieldName, callingField, sacField, originalSac, replyField, actionField, dirtyField) {

	var sac = document.getElementById(sacField).value;
	var reply = document.getElementById(replyField).value;
	var action = document.getElementById(actionField).value;
	var newAction = action; // Initialise to existing value
	var newSac = sac; // Initialise to existing value
	var callingFieldVal = document.getElementById(callingField).value;
	
	if (sac == null) { sac = ''; }

	// If the reply is not blank
	if (reply != '') {
		
		// If row is currently existing or changed
		
		if (action == 'E' || action == 'C') {
		
			// If any aspect of the SAC changes then set the action to S (otherwise C).  If the action is 
			// S, ValidateSubmission will delete the whole MRC and then re-add all the replies for that MRC
			// which have actions A, C, E or S.
			
			if (originalSac.length != sac.length ||
			((sac.length > 0 || originalSac.length > 0) && originalSac != sac))
			{
				newAction = 'S';
			}
			else
			{
				newAction = 'C';
			}
		}
		
		// If row is currently blank
		else if (action == ' ' || action == '') {
			newAction = 'A';
		}
		
		// If action is D then it must've originally been E so set to C or S as above.
		else if (action == 'D') {
		
			if (originalSac.length != sac.length ||
			((sac.length > 0 || originalSac.length > 0) && originalSac != sac))
			{
				newAction = 'S';
			}
			else
			{
				newAction = 'C';
			}
		
		}
	}
	
	// Else if the reply is blank
	else {
	
		// If action is E, C or S then change to D
		if ((action == 'E') || (action == 'C') || (action == 'S')) {
			newAction = 'D';
		}
		
		// If action is A then blank action
		else if (action == 'A') {
			newAction = ' ';
		}
	} 
	
	if (valueChanged(fieldName, callingFieldVal) == true)
	{
	
		// Update sac and action fields with new values if changed
		if (newSac != sac) {
			document.getElementById(sacField).value = newSac;
		}
		if (newAction != action) {
			document.getElementById(actionField).value = newAction;
		}
	
		// Mark row as dirty
		document.getElementById(dirtyField).value = 'true';
	}
}

//ACN154
/*-----------------------------------------------------------------------------
 * Name:        updateSrcDataAction(actionField, dirtyField)
 * Description: Update a SrcData Action field depending on it's current value.
 * Parameters:  actionField
 *              dirtyField
 *-----------------------------------------------------------------------------
 */
function updateSrcDataAction(actionField, currentValue, newValue, dirtyField) {

	var action = document.getElementById(actionField).value;
	if (currentValue != 'publicViewing') {
		var newValue = document.getElementById(newValue).value;
	}
	var newAction = 'C'; // Initialise to existing value

	// If the action is 'E' then change it to 'C'
	if (currentValue != newValue) {
		if (action == 'E'){
			document.getElementById(actionField).value = newAction;
		}
		// Mark row as dirty
		document.getElementById(dirtyField).value = 'true';
	}
}

/*-----------------------------------------------------------------------------
 * Name:        trim(str)
 * Description: Remove spaces from a given string.
 * Parameters:  str
 *-----------------------------------------------------------------------------
 */
function trim(str) {
	return str.replace(/^\s+|\s+$/g,'');
}

/*-----------------------------------------------------------------------------
 * Name:        updateNsnRelationCode(relCodeFieldName, relDefFieldName, prevCodeFieldName)
 * Description: Remove spaces from a given string.
 * Parameters:  relCodeFieldName
 *				relDefFieldName
 *				prevCodeFieldName
 *-----------------------------------------------------------------------------
 */
 function updateNsnRelationCode(relCodeFieldName, relDefFieldName, prevCodeFieldName) {
 
	var relDefField = document.getElementById(relDefFieldName);
 	var relDefFieldVal = relDefField.value;

	// Get handle to relation code field and update value
 	document.getElementById(relCodeFieldName).value = relDefFieldVal;

 	// OR85: Store selected code on form bean
	document.getElementById(prevCodeFieldName).value = relDefFieldVal;
}


/*-----------------------------------------------------------------------------
 * Name:        updateUserList(typeField, userField, csuList, iptList)
 * Description: Dynamically build an option list for a given user type.
 * Parameters:  typeField
 *				userField
 *				csuList
 *				iptList
 *-----------------------------------------------------------------------------
 */
function updateUserList(typeField, userField, csuList, iptList, userCodeField) {

	var userTypeVal = document.getElementById(typeField).value;
	var userOptions = document.getElementById(userField).options;
	// If user type is IPT, split iptList
	if (userTypeVal == "IPT") {
		var newUserArray;
		
		if (iptList.length > 0) {
			newUserArray = iptList.split(",");
		}
	}
	
	// Else if user type is CSU, split csuList.
	else {
		var newUserArray;
		if (csuList.length > 0) {
			newUserArray = csuList.split(",");
		}
	}

	// Blank existing user list
	var userOptionsLength = userOptions.length;
	for (i=0; i < userOptionsLength; i++) {
			// Have to blank first as list shrinks with each iteration.
			userOptions[0] = null;
	}

	if (newUserArray != null) {

		// Iterate array of new user values
		for (j=0; j < newUserArray.length; j++) {
		
			// If CSU, use first character as key
			if (userTypeVal == "CSU") {
				var newKey = newUserArray[j].charAt(0);
			}
			// If FNU, use first 5 characters as key
			else if (userTypeVal == "IPT") {
				var newKey = newUserArray[j].substring(0,5);
			}
			var newVal = newUserArray[j];

			// Add new option to list		
			var opt = new Option(newVal, newKey);
			userOptions.add(opt);
		}
		
		// Set user code field to first option in list
		document.getElementById(userCodeField).value = newUserArray[0].charAt(0);
	}
	
	// Otherwise set user code to blank
	else {
		document.getElementById(userCodeField).value = "";
	}
}

/*-----------------------------------------------------------------------------
 * Name:        updateUserCode(userCodeField, userDescField)
 * Description: Update a given user code field.
 * Parameters:  userCodeField
 *				userDescField
 *-----------------------------------------------------------------------------
 */
function updateUserCode(userCodeField, userDescField) {
	var selectedUserCode = document.getElementById(userDescField).value;
	document.getElementById(userCodeField).value = selectedUserCode;
}

/*-----------------------------------------------------------------------------
 * Name:        refreshAIN(incField, originalIncVal, originalIigVal)
 * Description: Refresh name field by changing form action and submitting.
 * Parameters:  incField
 *				originalIncVal
 *				originalIigVal
 *-----------------------------------------------------------------------------
 */
function refreshAIN(incField, originalIncVal) {

	var incVal = document.getElementById(incField).value;
	var blankInc = '';
	var sevensInc = '77777';
	var getConfirmation = false;
	
	var confirmationMsg = 'INC changed - any non-SRVAL replies entered may be lost (if IIG does not remain at A23900).  Do you want to continue?';
	
	// If value has changed...
	if (originalIncVal != incVal) {
	
		// If new INC is 7s or blank...
		if ((trim(incVal) == blankInc) || (incVal == sevensInc)) {
			
			// If old INC is NOT 7s NOR blank...
			if ((originalIncVal != sevensInc) && (originalIncVal != blankInc)) {
				getConfirmation = true;
			}
		}
		
		// Otherwise if dealing with another INC...
		else {
			getConfirmation = true;
		}
		
		if (getConfirmation) {

			// Get confirmation from user
			if (window.confirm(confirmationMsg)) {
		
				var formElement = document.forms[0];
				var formAction = formElement.action;
					
				// Change action from iosDetails.do to refreshAIN.do
				var newAction = formAction.replace('iosDetails.do', 'refreshAIN.do');
				formElement.action = newAction;
				setCursorBusy();
				formElement.submit();
			}
			
			// Otherwise restore original values 
			else {
				document.getElementById(incField).value = originalIncVal;
				return false;
			}
		}
	}
	
	// If no value changed, just return false
	else {
		return false;
	}
}

/*-----------------------------------------------------------------------------
* Name: numericSearchField
* Description: Removes any non numeric character except * % ; and space
* Parameters
*-----------------------------------------------------------------------------
*/
function numericSearchField( fld )
{
	if ( fld.value.length > 0 ) {
		fld.value = fld.value.replace( /[^\d\*\s;%]+/g, '' ) ;
	}
}

/*-----------------------------------------------------------------------------
* Name: alphaNumericSearchField
* Description: Removes any non alpha numeric character except * % ; and space
*
* Parameters
*-----------------------------------------------------------------------------
*/
function alphaNumericSearchField( fld )
{
	if ( fld.value.length > 0 ) {
		fld.value = fld.value.replace( /[^\w\*\s;%]+/gi, '' ) ;
	}
}


/*-----------------------------------------------------------------------------
* Name: constructRDGImageURL
* Description: Constructs the URL to retrieve an RDG image for a given RDG image filename.
*
* Parameters: rdgImageFilename
*-----------------------------------------------------------------------------
*/
function constructRDGImageURL(rdgImageFilename)
{
	var imageLocation = document.getElementById("imageLocation").value;
	var imageFilenameExt = document.getElementById("imageFilenameExt").value;
	
	return imageLocation + rdgImageFilename + imageFilenameExt;
}

/*-----------------------------------------------------------------------------
* Name: updateUserCode
* Description: Updates the user code field depending on the selected description.
*
* Parameters userCodeFieldName
*			 descriptionFieldName.
*-----------------------------------------------------------------------------
*/
function updateUserCode(userCodeFieldName, descriptionFieldName) {

	var userCodeField = document.getElementById(userCodeFieldName);
	var descriptionField = document.getElementById(descriptionFieldName);
	var selectedUserCode = descriptionField.options[descriptionField.selectedIndex].value;
	
	userCodeField.value = selectedUserCode;
	
}

/*-----------------------------------------------------------------------------
* Name: updateDescription
* Description: Updates the description field depending on the first char of user code.
*
* Parameters userCodeFieldName
*			 descriptionFieldName.
*-----------------------------------------------------------------------------
*/
function updateDescription(typeFieldName, descriptionFieldName, userCodeFieldName) {


	var typeFieldVal = document.getElementById(typeFieldName).value;
	var descriptionField = document.getElementById(descriptionFieldName);
	var userCodeField = document.getElementById(userCodeFieldName);

	// If type field is IPT use the entire usercode to find matching description
	if (typeFieldVal == "IPT") {
		descriptionField.value = userCodeField.value.toUpperCase();
	}
	
	// Otherwise if type field is CSU, use first char of user code to find description
	else if (typeFieldVal == "CSU") {
		descriptionField.value = userCodeField.value.substring(0,1).toUpperCase();
	}
	
	// If selection is blank, no match found so display error message.
	if (descriptionField.value == '') {
		alert('Invalid User Code entered');
		userCodeField.value = '';
		userCodeField.focus();
	}
}

/*-----------------------------------------------------------------------------
* Name: userTypeChanged
* Description: Repopulates the available list of users depending on selected type.
*
* Parameters typeFieldName
*			 descriptionFieldName.
*			 userCodeFieldName
*			 csuList.
*-----------------------------------------------------------------------------
*/
function userTypeChanged() {

		var formElement = document.forms[0];
		var formAction = formElement.action;
	
		// Change action from iosDetails.do to refreshUserList.do
		var newAction = formAction.replace('iosDetails.do', 'refreshUserList.do');
		formElement.action = newAction;
		setCursorBusy();
		formElement.submit();
}

/*-----------------------------------------------------------------------------
* Name: refreshQueryDetails
* Description: Changes form action and submits to refresh contents.
*-----------------------------------------------------------------------------
*/
function refreshQueryDetails() {

	var formElement = document.forms[0];
	var formAction = formElement.action;

	// Change action from queryDetails.do to queryDetailsLookupTask.do
	var newAction = formAction.replace('queryDetails.do', 'queryDetailsLookupTask.do');
	formElement.action = newAction;
	setCursorBusy();
	formElement.submit();
		
}

/*-----------------------------------------------------------------------------
* Name: checkReplyComplete(replyCompleteFieldName, replyValFieldName, replyValFieldName)
* Description: Checks a given field to see whether a complete reply has 
			   been selected and if so, closes the form.
*-----------------------------------------------------------------------------
*/
function checkReplyComplete(replyCompleteFieldName, fieldToUpdateName, replyValFieldName) {

	var completeFieldVal = document.getElementById(replyCompleteFieldName).value;
	
	// If complete field is true...
	if (completeFieldVal == 'true') {
	
		// Get handle to appropriate field on calling form
		var replyField = window.opener.document.getElementById(fieldToUpdateName);
		
		// Get actual reply value
		var replyVal = document.getElementById(replyValFieldName).value;
		
		// Update value of calling field
		replyField.value = replyVal;

		// Close the popup		
		self.close();
		replyField.focus();
	}
}
	
/*-----------------------------------------------------------------------------
* Name: addCurrentAddress(sourceColName, targetColName, rowKey)
* Description: Appends the selection from a source column to a target column
			   for a given row.
*-----------------------------------------------------------------------------
*/
function addCurrentAddress(sourceColName, targetColName, rowKey) {

	var sourceCol = document.getElementById(sourceColName + rowKey);
	var tarCol = document.getElementById(targetColName + rowKey);
	var selInd = sourceCol.selectedIndex;
	var selText = sourceCol.options[selInd].text;

	var currentText = tarCol.value;

	var newText;
	
	if (currentText.indexOf(selText) == -1) {
	
		if (currentText.length==0) {
			newText = selText;
		}
		else {
			newText = currentText + '; ' + selText;
		}
	
		tarCol.value = newText;
		document.getElementById('dirty' + rowKey).value = true;
		
	}
}

/*-----------------------------------------------------------------------------
 * Name:        getConfirmation
 * Description: Displays a confirmation dialog with a given message
 * Parameters:
 * Returns:     True  if confirmed
 *              False if cancel
 *-----------------------------------------------------------------------------
 */
function getConfirmation(msg) {
	return window.confirm(msg);
}

/*-----------------------------------------------------------------------------
 * Name:        populateCallingFormWithSelectedTask(selectedTaskVal, taskFieldToPopulateName, lineFieldToClearName)
 * Description: Writes the specified value in selectedTask to a field on a 
 *              popup windows calling page that is specified by the ID contained             
 *              in the taskFieldName field.
 *
 * Parameters	selectedTaskVal - the selected task no
 *				taskFieldToPopulateName - the styleID of the task no field on 
 *										  the calling form.
 *				lineFieldToClearName - the styleID of the line no field on
 *									   the calling form.
 *-----------------------------------------------------------------------------
 */
function populateCallingFormWithSelectedTask(selectedTaskVal, taskFieldToPopulateName, lineFieldToClearName)
{

	/* Get handle to the task no field we want to populate */
	var taskFieldToPopulate = window.opener.document.getElementById(taskFieldToPopulateName);
	var originalTaskValue = taskFieldToPopulate.value;
	
	/* Update the value of the field with the selected value */	
	/* If linefieldToClear is blank, assume this is an enquiry screen and allow setting of blank task */

	
	if (lineFieldToClearName == null || lineFieldToClearName == '' || (selectedTaskVal != null && selectedTaskVal != '')) {
		taskFieldToPopulate.value = selectedTaskVal;
	
		if (originalTaskValue == null || originalTaskValue == '' || originalTaskValue != selectedTaskVal) {
		
			/* Reset the line no field if it is provided, as this is directly linked to the task */
			if (null != lineFieldToClearName && lineFieldToClearName != '') {
				var lineFieldToClear = window.opener.document.getElementById(lineFieldToClearName);
				lineFieldToClear.value = '';
			}
			
		}
	}
	
	/* Close the popup window */
	self.close();
}

/*-----------------------------------------------------------------------------
 * Name:        showTaskSelectionPopup(url, contractorCodeFieldName)
 * Description: Calls showPopupAt with the given URL, appending the contractor
 *				code as a request parameter.
 *
 * Parameters	url - the url to invoke the task selection popup
 *				contractorCodeName - the styleID of the contractor code field on 
 *									 the calling form.
 *-----------------------------------------------------------------------------
 */
function showTaskSelectionPopup(url, contractorCodeFieldName, encodedUrlId)
{
	/* Get handle to the contractor code field we want to append */
	var contractorCodeField = document.getElementById(contractorCodeFieldName);
	
	/* Get value of the contractor code */
	var contractorCodeValue = contractorCodeField.value;
	
	/* Append the value as a request parameter on the url */
	var newUrl = url + "&contractorCode=" + contractorCodeValue;

	/* Invoke popup using new url */
	showPopupAt(newUrl, encodedUrlId, '510', '400', 'yes', 164, 120 );
	
	/* Return false to prevent page being submitted */
	return false;
}

/*-----------------------------------------------------------------------------
 * Name:        showETaskNcageLookupPopup(url, ncageCodeFieldName, ncageNameFieldName, encodedUrlId)
 * Description: Calls showPopupAt with the given URL, appending the ncageCode and ncageName
 *			 as request parameters.
 *
 * Parameters	url - the url to invoke the task selection popup
 *				ncageCodeFieldName - the styleID of the ncageCode field on 
 *									 the calling form.
 *				ncageCodeFieldName - the styleID of the ncageName field on 
 *									 the calling form.
 *-----------------------------------------------------------------------------
 */
function showETaskNcageLookupPopup(url, ncageCodeFieldName, ncageNameFieldName, encodedUrlId)
{
	/* Get handle to the ncage code field we want to append */
	var ncageCodeField = document.getElementById(ncageCodeFieldName);
	
	/* Get value of the contractor code */
	var ncageCodeValue = ncageCodeField.value;
	
	/* Get handle to the ncage code field we want to append */
	var ncageNameField = document.getElementById(ncageNameFieldName);
	
	/* Get value of the contractor code */
	var ncageNameValue = ncageNameField.value;
	
	/* Append the value as a request parameter on the url */
	var newUrl = url + "&ncageCode=" + ncageCodeValue + "&ncageName=" + ncageNameValue;

	/* Invoke popup using new url */
	showPopupAt(newUrl, encodedUrlId, '640', '440', 'yes', 164, 120 );
	
	/* Return false to prevent page being submitted */
	return false;
}

/*-----------------------------------------------------------------------------
 * Name:        refreshLsaNain(incField, originalIncVal)
 * Description: Refresh name field by changing form action and submitting.
 * Parameters:  incField
 *				originalIncVal
 *-----------------------------------------------------------------------------
 */
function refreshLsaNain(incField, originalIncVal) {

	var incVal = document.getElementById(incField).value;
	var blankInc = '';
	var sevensInc = '77777';
	var getConfirmation = false;
	
	// If value has changed...
	if (originalIncVal != incVal) {
	
		var formElement = document.forms[0];
		var formAction = formElement.action;
			
		// Change action from iosDetails.do to refreshLSANain.do
		var newAction = formAction.replace('lsaDetails.do', 'lsaDetailsRefreshNain.do');
		formElement.action = newAction;
		setCursorBusy();
		formElement.submit();
	}
	
	// If no value changed, just return false
	else {
		return false;
	}
}

/*-----------------------------------------------------------------------------
 * Name:        showLineEntrySelectionPopup(url, taskFieldName)
 * Description: Calls showPopupAt with the given URL, appending the Task No
 *				as a request parameter.
 *
 * Parameters	url - the url to invoke the task selection popup
 *				taskFieldName - the styleID of the Task No field on 
 *									 the calling form.
 *-----------------------------------------------------------------------------
 */
function showLineEntrySelectionPopup(url, taskFieldName, encodedUrlId)
{
	/* Get handle to the Task No field we want to append */
	var taskNoField = document.getElementById(taskFieldName);
	
	/* Get value of the task no */
	var taskNoValue = taskNoField.value;
	
	/* Ensure task no has a  value */
	var blankTask = '';
	if (taskNoValue != blankTask) {

		/* Append the value as a request parameter on the url */
		var newUrl = url + "&taskNo=" + taskNoValue;
	
		/* Invoke popup using new url */
		showPopupAt(newUrl, encodedUrlId, '600', '400', 'yes', 164, 120 );
		
		/* Return false to prevent page being submitted */
		return false;
	}
	else {
		alert('Please select a Task');
	}
}

/*-----------------------------------------------------------------------------
 * Name:        populateCallingFormWithSelectedLine(selectedLineVal, lineFieldToPopulateName, generateDcn)
 * Description: Writes the specified value in selectedLineVal to a field on a 
 *              popup window's calling page that is specified by the ID contained             
 *              in the lineFieldToPopulateName parm.
 *
 * Parameters	selectedLineVal - the selected line no
 *				lineFieldToPopulateName - the styleID of the line no field on 
 *										  the calling form.
 *				dcnRequired - boolean flag for generating a DCN for LSAs.
 *-----------------------------------------------------------------------------
 */
function populateCallingFormWithSelectedLine(selectedLineVal, lineFieldToPopulateName)
{

	/* Get handle to the line no field we want to populate */
	var lineFieldToPopulate = window.opener.document.getElementById(lineFieldToPopulateName);
	
	/* Update the value of the field with the selected value (DPS - only if not 0) */
	
	if (selectedLineVal != 0) {
		lineFieldToPopulate.value = selectedLineVal;
	}
	
	/* Close the popup window */
	self.close();
	
}

/*-----------------------------------------------------------------------------
 * Name:        populateDcn(dcnFieldName, julianDateFieldName, taskFieldName, lineFieldName, contractorFieldName)
 * Description: Generate a DCN and populate the DCN field with it.
 * Parameters:  
 *-----------------------------------------------------------------------------
 */
function populateDcn(dcnFieldName, julianDateFieldName, taskFieldName, lineFieldName, contractorFieldName) {

	var MAX_LINE_NO_LENGTH = 4;

	/* Get handles to fields on calling window */
	var dcnField = window.opener.document.getElementById(dcnFieldName);
	var julianDate = window.opener.document.getElementById(julianDateFieldName).value;
	var taskNo = window.opener.document.getElementById(taskFieldName).value;
	var lineNo = window.opener.document.getElementById(lineFieldName).value;
	var contractorCode = window.opener.document.getElementById(contractorFieldName).value;
	
	/* Concatenate values to generate a dcn and set value on field */
	if (lineNo != '') {
		if (contractorCode != '' && taskNo != '') {
			
			var lineNoLength = lineNo.length;

			/* If lineNo < 4 characters, lpad it with zeros */			
			if (lineNoLength < MAX_LINE_NO_LENGTH) {
				for (var i = lineNoLength; i < MAX_LINE_NO_LENGTH; i++) {
					lineNo = '0' + lineNo;
				}
			}
			
			var dcn = contractorCode + 'ZK' + julianDate + taskNo.substring(2,5) + lineNo;
			
			dcnField.value = dcn;
		}
	} else {
		dcnField.value = '';
	}			
}

/*-----------------------------------------------------------------------------
 * Name:        populateCurrentWindowDcn(dcnFieldName, julianDateFieldName, taskFieldName, lineFieldName, contractorFieldName)
 * Description: Generate a DCN in the current window and populate the DCN field with it.
 * Parameters:  
 *-----------------------------------------------------------------------------
 */
function populateCurrentWindowDcn(dcnFieldName, julianDateFieldName, taskFieldName, lineFieldName, contractorFieldName) {

	var MAX_LINE_NO_LENGTH = 4;

	/* Get handles to fields in current window */
	var dcnField       = document.getElementById(dcnFieldName);
	var julianDate     = document.getElementById(julianDateFieldName).value;
	var taskNo         = document.getElementById(taskFieldName).value.toUpperCase();
	var lineNo         = document.getElementById(lineFieldName).value;
	var contractorCode = document.getElementById(contractorFieldName).value;
	
	/* Concatenate values to generate a dcn and set value on field */
	if (lineNo != '') {
		if (contractorCode != '' && taskNo != '') {
			
			var lineNoLength = lineNo.length;

			/* If lineNo < 4 characters, lpad it with zeros */			
			if (lineNoLength < MAX_LINE_NO_LENGTH) {
				for (var i = lineNoLength; i < MAX_LINE_NO_LENGTH; i++) {
					lineNo = '0' + lineNo;
				}
			}
			
			var dcn = contractorCode + 'ZK' + julianDate + taskNo.substring(2,5) + lineNo;
			
			dcnField.value = dcn;
		}
	} else {
		dcnField.value = '';
	}			
}


/*-----------------------------------------------------------------------------
 * Name:        refreshLsaFieldAvailability()
 * Description: Refresh field availability.
 * Parameters:  
 *-----------------------------------------------------------------------------
 */
function refreshLsaFieldAvailability() {

	var formElement = document.forms[0];
	var formAction = formElement.action;
			
	// Change action from iosDetails.do to refreshLSAFieldAvailability.do
	var newAction = formAction.replace('lsaDetails.do', 'lsaDetailsRefreshFieldAvailability.do');
	formElement.action = newAction;
	formElement.submit();
}

/*-----------------------------------------------------------------------------
 * Name:        getDeleteLSAConfirmation
 * Description: Displays an alert box requesting confirmation of an Action.
 *              The form is submitted if the action is confirmed.
 * Parameters:  msg     message to display
 *-----------------------------------------------------------------------------
 */
function getDeleteLSAConfirmation(msg) {

	var formElement = document.forms[0];
	response = window.confirm( msg ) ;
	
	if ( response )
	{
		//submit the form
		formElement.submit() ;
	}
	else
	{
	    document.getElementById('btnDeleteHidden').value = '';
	}
	return response ;
}

/*-----------------------------------------------------------------------------
 * Name:        toggleL07EnquiryTaskFieldAvailability(selectedOption, taskDivName, taskFieldName)
 * Description: Toggles the Task field between enabled and disabled depending
 *				on the selected option.
 * Parameters:  selectedOption the selected radio button on l07Enquiry.jsp.
 *				taskDivName the ID of the DIV containing task elements.
 *				taskFieldName the ID of the Task No field
 *-----------------------------------------------------------------------------
 */
function toggleL07EnquiryTaskFieldAvailability(selectedOption, taskDivName, taskFieldName) {

	var taskDiv = document.getElementById(taskDivName);
	var taskField = document.getElementById(taskFieldName);
	
	// If sent is selected, enable task selection
	if (selectedOption == 'SENT') {
		
		taskDiv.style.display = '';
		
	}
	
	// If received is selected, disable task selection and blank field
	else {
	
		taskDiv.style.display = 'none';
		taskField.value = '';
	}
}

/*-----------------------------------------------------------------------------
 * Name:        setHiddenAssociatedLSA(associatedFieldName, hiddenFieldName)
 * Description: Updates the contents of a hidden field with the value of the 
 *				selected Associated LSA.
 * Parameters:  associatedFieldName
 *				hiddenFieldName
 *-----------------------------------------------------------------------------
 */
function setHiddenAssociatedLSA(associatedFieldName, hiddenFieldName) {

	// Get field elements
	var associatedLSAField = document.getElementById(associatedFieldName);
	var hiddenField = document.getElementById(hiddenFieldName);
	
	// Get the value of the currently selected Associated LSA
	if (associatedLSAField.options.length > 0) {
		if (associatedLSAField.selectedIndex >= 0) {
			var selectedAssociatedLSAValue = associatedLSAField.options[associatedLSAField.selectedIndex].value;
		
			// Update the hidden field with the selected value
			hiddenField.value = selectedAssociatedLSAValue;
		}
	}
}

/*-----------------------------------------------------------------------------
 * Name:        setHiddenPotentialLSA(potentialFieldName, hiddenFieldName)
 * Description: Updates the contents of a hidden field with the value of the 
 *				selected Potential LSA.
 * Parameters:  potentialFieldName
 *				hiddenFieldName
 *-----------------------------------------------------------------------------
 */
function setHiddenPotentialLSA(potentialFieldName, hiddenFieldName) {

	// Get field elements
	var potentialLSAField = document.getElementById(potentialFieldName);
	var hiddenField = document.getElementById(hiddenFieldName);
	
	// Get the value of the currently selected Potential LSA
	if (potentialLSAField.options.length > 0) {
		if (potentialLSAField.selectedIndex >= 0) {
			var selectedPotentialLSAValue = potentialLSAField.options[potentialLSAField.selectedIndex].value;
		
			// Update the hidden field with the selected value
			hiddenField.value = selectedPotentialLSAValue;
		}
	}
}

/*-----------------------------------------------------------------------------
 * Name:        refreshPotentialLSAs(moeCodeFieldName, activityCodeFieldName)
 * Description: Updates the LSA lists on the l07Details.jsp
 * Parameters:  moeCodeFieldName
 *				activityCodeFieldName
 *-----------------------------------------------------------------------------
 */
function refreshPotentialLSAs(moeCodeFieldName, activityCodeFieldName, currentMoeCodeFieldName, currentActivityCodeFieldName) {

	// Get field elements
	var moeCodeField = document.getElementById(moeCodeFieldName);
	var activityCodeField = document.getElementById(activityCodeFieldName);
	var currentMoeCodeField = document.getElementById(currentMoeCodeFieldName);
	var currentActivityCodeField = document.getElementById(currentActivityCodeFieldName);
	
	if (moeCodeField.value != currentMoeCodeField.value || activityCodeField.value != currentActivityCodeField.value) {
	
		// Get the field values and build into a URL
		var moeCode = moeCodeField.value;
		var activityCode = activityCodeField.value;
		
		var newParams = "?l07MoeCode=" + moeCode.toUpperCase() + "&l07ActivityCode=" + activityCode.toUpperCase();
		
		var formElement = document.forms[0];
		var formAction = formElement.action;
				
		// Change action from l07Details.do to new URL
		var newAction = formAction.replace('l07Details.do', 'l07DetailsRefreshLSAs.do');
		newAction = newAction + newParams;
		
		formElement.action = newAction;
		formElement.submit();
		setCursorBusy();
	}
}

/*-----------------------------------------------------------------------------
 * Name:        populateK27Reason(replyFieldName, reasonFieldName, selectedReply, selectedReasonCode)
 * Description: Updates the reason row on k27Details.jsp with selected data.
 * Parameters:  replyFieldName - reply field to be populated
 *				reasonFieldName - reason field to be populated
 *				selectedReply - Value of the selected reply
 *				selectedReasonCode - Value of the selected reason code
 *-----------------------------------------------------------------------------
 */
function populateK27Reason(replyFieldName, reasonFieldName, selectedReply, selectedReasonCode) {

	var replyFieldToPopulate = window.opener.document.getElementById(replyFieldName);
	var reasonFieldToPopulate = window.opener.document.getElementById(reasonFieldName);
	
	if (null != selectedReply && selectedReply != '') {
		replyFieldToPopulate.value = selectedReply;
		reasonFieldToPopulate.value = selectedReasonCode;
	}
	
	self.close();
}

/*-----------------------------------------------------------------------------
 * Name:        toggleK23EnquiryFieldAvailability(selectedOption, taskDivName, activityFieldName)
 * Description: Toggles the Task and Activity Code fields between enabled and disabled depending
 *				on the selected option.
 * Parameters:  selectedOption the selected radio button on l07Enquiry.jsp.
 *				taskDivName the ID of the DIV containing task elements.
 *				activityFieldname the ID of the Activity Code field
 *-----------------------------------------------------------------------------
 */
function toggleK23EnquiryFieldAvailability(selectedOption, taskDivName, activityFieldName) {

	var taskDiv = document.getElementById(taskDivName);
	var activityField = document.getElementById(activityFieldName);
	
	// If sent is selected, enable task selection
	if (selectedOption == 'SENT') {
		
		taskDiv.style.display = 'none';
		activityField.disabled = true;
		
	}
	
	// If received is selected, disable task and activity
	else {
	
		taskDiv.style.display = '';
		activityField.disabled = false;
	}
}

/*-----------------------------------------------------------------------------
 * Name:        toggleL23EnquiryFieldAvailability(selectedOption, taskDivName, activityFieldName)
 * Description: Toggles the Task and Activity Code fields between enabled and disabled depending
 *				on the selected option.
 * Parameters:  selectedOption the selected radio button on l07Enquiry.jsp.
 *				taskDivName the ID of the DIV containing task elements.
 *				activityFieldname the ID of the Activity Code field
 *-----------------------------------------------------------------------------
 */
function toggleL23EnquiryFieldAvailability(selectedOption, taskDivName, activityFieldName) {

	var taskDiv = document.getElementById(taskDivName);
	var activityField = document.getElementById(activityFieldName);
	
	// If received is selected, enable task selection
	if (selectedOption == 'RECEIVED') {
		
		taskDiv.style.display = 'none';
		activityField.disabled = true;
		
	}
	
	// If sent is selected, disable task and activity 
	else {
	
		taskDiv.style.display = '';
		activityField.disabled = false;
	}
}

/*-----------------------------------------------------------------------------
 * Name:        checkSRSCValue(srscFieldName, lsaSRSC, url)
 * Description: Checks the SRSC value against a valid LSA SRSC and if they 
 *				match then it will display a popup with the given URL contents.
 * Parameters:  srscFieldName - name of the field containing the SRSC value.
*				lsaSRSC - value of an LSA SRSC.
 *				url - the URL as generated by the row bean.
 *-----------------------------------------------------------------------------
 */
function checkSRSCValue(srscFieldName, lsaSRSC, url, encodedUrlId) {

	var srscField = document.getElementById(srscFieldName);
	var srscValue = srscField.value;
	
	// If values match show LSA in popup
	if (srscField.value == lsaSRSC) {
		showPopup(url, encodedUrlId, 'LSADetailsPopup', '1020', '650', '1');
	}
	
	// Always return false to prevent Callback being executed.
	return false;
}

/*-----------------------------------------------------------------------------
 * Name:        setScrollPosition(divId, scrollFieldId)
 * Description: Sets the scroll position of a scrollable div
 * Parameters:  divId - ID of scrollable div
 *				scrollFieldId - ID of field whose value is the scroll position
 *-----------------------------------------------------------------------------
 */
function setScrollPosition(divId, scrollFieldId) {
	var theDiv = document.getElementById(divId);
	
	if (theDiv) {
		var posField = document.getElementById(scrollFieldId);
		if (posField) {
			theDiv.scrollTop = posField.value;
		}
	}
}


/*-----------------------------------------------------------------------------
 * Name:        showSponsorContextMenu
 * Description: Displays the Sponsor context menu.
 * Parameters: 
 *              divName     - Name of the div to contain the tip. 
 *              rowKey      - UniqueId for the selected row.
 *              sponsorRef  - Sponsor Reference
 *              menuSponsorFieldName - Name of Sponsor Ref field on menu.
 *              divShadowName - Name of the div making up the shadow
 *              hiddenRowFieldName - Name of the hidden row field holding the row ID for the selected row.
 *-----------------------------------------------------------------------------
 */
function showSponsorContextMenu(divName, rowKey, lineStatus, sponsorRef, menuSponsorFieldName, divShadowName, hiddenRowFieldName) {

			if (lineStatus != 'D') {
	            // Get Sponsor Ref field and set value
	            var menuSponsorField = document.getElementById(menuSponsorFieldName);
	            menuSponsorField.value = sponsorRef;
	
	            // Get menu div, set position and display
	            var menuDiv = document.getElementById(divName)
	            menuDiv.style.top = event.y - 60;
	            menuDiv.style.left = 260;                                    
	            menuDiv.style.display = "";
	            menuDiv.focus();
	
	            // Get shadow div, set position and display
	            var shadowDiv = document.getElementById(divShadowName);
	            shadowDiv.style.top = event.y - 55;
	            shadowDiv.style.left = 265;
	            shadowDiv.style.display = "";
	
	            // Get the hidden row ID field and set the value 
	            var hiddenRowField = document.getElementById(hiddenRowFieldName);
	            hiddenRowField.value = rowKey;
			}
}


/*-----------------------------------------------------------------------------
 * Name:                       Set DefCon multiplier
 * Description: Displays the Sponsor context menu.
 * Parameters: 
 *              defConCodesListName - Name of the Defcon codes list element.
 *              multiplierFieldName - Name of the multiplier field.
 *-----------------------------------------------------------------------------
 */
function setDefConMultiplier(defConCodesListName, multiplierFieldName) {
 
            // Get handle to fields
            var defConList = document.getElementById(defConCodesListName);
            var multiplierField = document.getElementById(multiplierFieldName);
            
            // Get selected defcon value
            var defConValue = defConList.options[defConList.selectedIndex].text;
 
            // If the value is 11, enable the multiplier field and set to 1.000
            if (defConValue == 11) {
                        multiplierField.disabled = false;
                        multiplierField.value = '1.000';
            }
            // Otherwise disable the multiplier field and set to 1.000
            else {
                        multiplierField.disabled = true;
                        multiplierField.value = '1.000';
            }                       
}

/*-----------------------------------------------------------------------------
 * Name:        confirmLineWithdrawal
 * Description: Displays the Sponsor context menu.
 * Parameters: 
 *              taskFieldName - Name of the field containing Task No
 *              lineRangeFieldName - The name of the field containing line range.
 *-----------------------------------------------------------------------------
 */
function confirmLineWithdrawal(taskFieldName, lineRangeFieldName) {

	var taskNoField = document.getElementById(taskFieldName);
	var lineRangeField = document.getElementById(lineRangeFieldName);
	
	var lineRange = lineRangeField.value;
	
	if (null != lineRange && lineRange.length > 0) {
	
		var msg = "Please confirm that you want to withdraw\nthe following lines from this Task:\n" + lineRangeField.value;
		return window.confirm(msg);
	}
	else {
		alert('Please enter some lines to withdraw');
		return false;
	}

}

/*-----------------------------------------------------------------------------
 * Name:		fireContractorChanged()
 * Description: 
 * Parameters: 	originalCode - contractor code to revert to
 *				contractorFieldName - contractor field
 *-----------------------------------------------------------------------------
 */
function fireContractorChanged(originalCode, contractorFieldName) {
 
 	var contractorField = document.getElementById(contractorFieldName);
 	var newCode = contractorField.options[contractorField.selectedIndex].text;
 	
 	/* OR817F1 - Do not fire if CC code is empty and no change */
 	if (originalCode.length==0 && newCode.length<2) {
 		newCode = '';
 	}
 	
 	if (originalCode != newCode) {
		var msg = 'This will change the Contractor Code of this task \nfrom ' + originalCode + 
		    	' to ' + newCode + ' and will save the change. It will also update the \ncontractor ' +
		    	'code for all associated contractor queries,\nand will commit any other changes made ' +
			   'on this screen. \nDo you want to continue?';
		
		var retVal = getConfirmation(msg); 
	
		if (retVal) {
			document.getElementById('callbackMethod').name='btnUpdateContractorCode';
			//CCUtility.submitEnclosingForm(this);
			setCursorBusy();
			document.forms[0].submit();
		}
		else {
			contractorField.value = originalCode;
		}
		return retVal;
	}
 }

/*-----------------------------------------------------------------------------
 * Name:		fireProjectChanged()
 * Description: 
 * Parameters: 	originalCode - project code to revert to
 *				projectFieldName - project field
 *-----------------------------------------------------------------------------
 */
function fireProjectChanged(originalCode, projectFieldName) {
 
 	var projectField = document.getElementById(projectFieldName);
 	var newCode = projectField.options[projectField.selectedIndex].text;
 	
 	/* OR817F1 - Do not fire if CC code is empty and no change */
 	if (originalCode.length==0 && newCode.length<2) {
 		newCode = '';
 	}
 	
 	if (originalCode != newCode) {
		var msg = 'This will change the Project Code of this task \nfrom ' + originalCode + 
		    	' to ' + newCode + ' and will save the change. It will also update the \nproject ' +
		    	'code for all associated sponsors references,\nand will commit any other changes made ' +
			   'on this screen. \nDo you want to continue?';
		
		var retVal = getConfirmation(msg); 
	
		if (retVal) {
			document.getElementById('callbackMethod').name='btnUpdateProjectCode'; 
			//CCUtility.submitEnclosingForm(this);
			setCursorBusy();
			document.forms[0].submit();
		}
		else {
			projectField.value = originalCode;
		}
		return retVal;
	}
 }

/*-----------------------------------------------------------------------------
 * Name:		parseDate()
 *
 * Description: Attempts to parse a given String to the format dd/mm/yyyy.
 *				Strips the string of all non numerical characters, then 
 *				assumes that:
 *	 				i) if the string is 6 chars, it is ddmmyy.
 *					ii) if the string is 4 chars, it is ddmm.
 *					iii) if the string is 8 chars, it is ddmmyyyy.
 *
 * Parameters: 	str - the string to parse
 *
 * Returns: String of the format dd/mm/yyyy if parsing was successful, or 
 *			'Invalid' otherwise.
 *-----------------------------------------------------------------------------
 */
function parseDate(str) {

	if (null != str && str.length > 0) {

		/* Detect expression at beginning of string */
		var compChar = str.substring(0,2);
		if (compChar != ">=" && compChar != "<=" ) {
			compChar = str.substring(0,1);
			if (compChar != ">" && compChar != "<" ) {
				compChar = '';
			}
		}

		/* Remove all non numeric characters */
		str = str.replace(/\D/g, '');
		
		var strLen = str.length;
		
		/* If 4 characters, add current 4 digit year */
		if (strLen == 4) {
			str = str + new Date().getFullYear();
		}
		
		/* If 6 characters, assume year is last 2 digits and calculate century */
		else if (strLen == 6) {
		
			/* Get year as 2 characters and current year as 2 and 4 character */
			var year = str.substring(4,6);
			var current4DigitYear = '' + new Date().getFullYear();
			var current2DigitYear = current4DigitYear.substring(2,4);

			if (Math.abs(parseInt(current2DigitYear) - parseInt(year)) > 50) {
			
				/* Assume last century */
				var newYear;
				if (parseInt(current2DigitYear) - parseInt(year) < 0) {
					
					century = ('' + (((parseInt(current4DigitYear) / 100) - 1) * 100)).substring(0,2);
					newYear = century + year;
				}
				
				/* Else assume next century*/
				else {
					century = ('' + (((parseInt(current4DigitYear) / 100) + 1) * 100)).substring(0,2);
					newYear = century + year;
				}
			}
			else {

				/* Assume this century */
				century = ('' + current4DigitYear).substring(0,2);
				newYear = century + year;
			}

			/* Replace last 2 characters of string with new year */
			str = str.substring(0,4) + newYear;
		}

		/* String should now be 8 characters, so convert to dd/mm/yyyy */
		if (str.length == 8) {
			var newStr = str.substring(0,2) + "/" + str.substring(2,4) + "/" + str.substring(4,8);
			str = newStr;
			
			/* Place comparision character(s) back if required */
			
			if (compChar.length > 0) {
				str = compChar + newStr;
			}
		}
		else str = 'Invalid';
	}
	
	/* Return parsed String */
	return str;
}
 
/*-----------------------------------------------------------------------------
 * Name:        setHiddenAssociated640(currentFieldName, hiddenFieldName)
 * Description: Updates the contents of a hidden field with the value of the 
 *				selected Current MOD640.
 * Parameters:  currentFieldName
 *				hiddenFieldName
 *-----------------------------------------------------------------------------
 */
function setHiddenAssociated640(currentFieldName, hiddenFieldName) {

	// Get field elements
	var currentMOD640Field = document.getElementById(currentFieldName);
	var hiddenField = document.getElementById(hiddenFieldName);
	
	// Get the value of the selected Current MOD640
	if (currentMOD640Field.options.length > 0) {
		if (currentMOD640Field.selectedIndex >= 0) {
			var selectedMOD640Value = currentMOD640Field.options[currentMOD640Field.selectedIndex].value;
		
			// Update the hidden field with the selected value
			hiddenField.value = selectedMOD640Value;
		}
	}
}

/*-----------------------------------------------------------------------------
 * Name:        setHiddenAvailable640(availableFieldName, hiddenFieldName)
 * Description: Updates the contents of a hidden field with the value of the 
 *				selected Available MOD640.
 * Parameters:  availableFieldName
 *				hiddenFieldName
 *-----------------------------------------------------------------------------
 */
function setHiddenAvailable640(availableFieldName, hiddenFieldName) {

	// Get field elements
	var availableMOD640Field = document.getElementById(availableFieldName);
	var hiddenField = document.getElementById(hiddenFieldName);
	
	// Get the value of the selected Current MOD640
	if (availableMOD640Field.options.length > 0) {
		if (availableMOD640Field.selectedIndex >= 0) {
			var selectedMOD640Value = availableMOD640Field.options[availableMOD640Field.selectedIndex].value;
		
			// Update the hidden field with the selected value
			hiddenField.value = selectedMOD640Value;
		}
	}
}

/*-----------------------------------------------------------------------------
 * Name:        setHiddenAssociatedSite(currentFieldName, hiddenFieldName)
 * Description: Updates the contents of a hidden field with the value of the 
 *				selected Current Site.
 * Parameters:  currentFieldName
 *				hiddenFieldName
 *-----------------------------------------------------------------------------
 */
function setHiddenAssociatedSite(currentFieldName, hiddenFieldName) {

	// Get field elements
	var currentSiteField = document.getElementById(currentFieldName);
	var hiddenField = document.getElementById(hiddenFieldName);
	
	// Get the value of the selected Current Site
	if (currentSiteField.options.length > 0) {
		if (currentSiteField.selectedIndex >= 0) {
			var selectedSiteValue = currentSiteField.options[currentSiteField.selectedIndex].value;
		
			// Update the hidden field with the selected value
			hiddenField.value = selectedSiteValue;
		}
	}
}

/*-----------------------------------------------------------------------------
 * Name:        setHiddenAvailableSite(availableFieldName, hiddenFieldName)
 * Description: Updates the contents of a hidden field with the value of the 
 *				selected Available Site.
 * Parameters:  availableFieldName
 *				hiddenFieldName
 *-----------------------------------------------------------------------------
 */
function setHiddenAvailableSite(availableFieldName, hiddenFieldName) {

	// Get field elements
	var availableSiteField = document.getElementById(availableFieldName);
	var hiddenField = document.getElementById(hiddenFieldName);
	
	// Get the value of the selected Current Site
	if (availableSiteField.options.length > 0) {
		if (availableSiteField.selectedIndex >= 0) {
			var selectedSiteValue = availableSiteField.options[availableSiteField.selectedIndex].value;
		
			// Update the hidden field with the selected value
			hiddenField.value = selectedSiteValue;
		}
	}
}
 
/*-----------------------------------------------------------------------------
 * Name:		parseDateTime(str, dateType)
 *
 * Description: Attempts to parse a given String to the format dd/mm/yyyy.
 *				Strips the string of all non numerical characters, then 
 *				assumes that:
 *	 				i) if the string is 6 chars, it is ddmmyy.
 *					ii) if the string is 4 chars, it is ddmm.
 *					iii) if the string is 8 chars, it is ddmmyyyy.
 *					iv) if the string is 19 chars, it is dd/MM/yyyy hh:mm:ss
 *				Finally appends either 00:00:00 or 23:59:59 depending on dateType 
 *				(and only if there is not already a time).
 *
 * Parameters: 	str - the string to parse
 *				dateType - TO or FROM depending on date type.
 *
 * Returns: String of the format dd/mm/yyyy if parsing was successful, or 
 *			'Invalid' otherwise.
 *-----------------------------------------------------------------------------
 */
function parseDateTime(str, dateType) {

	if (null != str && str.length > 0) {
	
		/* Detect expression at beginning of string */
		var compChar = str.substring(0,2);
		if (compChar != ">=" && compChar != "<=" ) {
			compChar = str.substring(0,1);
			if (compChar != ">" && compChar != "<" ) {
				compChar = '';
			}
		}
		var compLength = compChar.length;
		var	dateStr = str.substring(compLength);
		str = dateStr;

		/* Firstly, check if String is 19 chars.  It may have already had a time appended, 
		 * so remove last 9 digits (space + hh:mm:ss) and store for later */
		var timeToAppend = '';
		if (str.length == 19) {
			timeToAppend = str.substring(10);			
			str = str.substring(0, 10);
		}

		/* Remove all non numeric characters */
		str = str.replace(/\D/g, '');
		
		var strLen = str.length;
		
		/* If 4 characters, add current 4 digit year */
		if (strLen == 4) {
			str = str + new Date().getFullYear();
		}
		
		/* If 6 characters, assume year is last 2 digits and calculate century */
		else if (strLen == 6) {
		
			/* Get year as 2 characters and current year as 2 and 4 character */
			var year = str.substring(4,6);
			var current4DigitYear = '' + new Date().getFullYear();
			var current2DigitYear = current4DigitYear.substring(2,4);

			if (Math.abs(parseInt(current2DigitYear) - parseInt(year)) > 50) {
			
				/* Assume last century */
				var newYear;
				if (parseInt(current2DigitYear) - parseInt(year) < 0) {
					
					century = ('' + (((parseInt(current4DigitYear) / 100) - 1) * 100)).substring(0,2);
					newYear = century + year;
				}
				
				/* Else assume next century*/
				else {
					century = ('' + (((parseInt(current4DigitYear) / 100) + 1) * 100)).substring(0,2);
					newYear = century + year;
				}
			}
			else {

				/* Assume this century */
				century = ('' + current4DigitYear).substring(0,2);
				newYear = century + year;
			}

			/* Replace last 2 characters of string with new year */
			str = str.substring(0,4) + newYear;
		}

		/* String should now be 8 characters, so convert to dd/mm/yyyy */
		if (str.length == 8) {
			var newStr = str.substring(0,2) + "/" + str.substring(2,4) + "/" + str.substring(4,8);
			str = newStr;

			/* If we don't have a time to append, create one according to date type */
			if (timeToAppend == '') {
				if (dateType == 'FROM') {
					timeToAppend = ' 00:00:00';
				}
				else if (dateType == 'TO') {
					timeToAppend = ' 23:59:59';
				}
				else if (compChar == "<=") {
					timeToAppend = ' 23:59:59';
				}
				else {
					timeToAppend = ' 00:00:00';
				}
			}
			
			newStr = str + timeToAppend;
			
			/* Place comparision character(s) back if required */
			
			if (compChar.length > 0) {
				str = compChar + newStr;
			}
			else {
				str = newStr;
			}
			
		}
		else str = 'Invalid';
	}
	
	/* Return parsed String */
	return str;
}
 
/*-----------------------------------------------------------------------------
 * Name:        setHiddenAuthorisedUpload(authorisedUploadFieldName, hiddenFieldName)
 * Description: Updates the contents of a hidden field with the value of the 
 *				selected Authorised Upload Site.
 * Parameters:  authorisedFieldName
 *				hiddenFieldName
 *-----------------------------------------------------------------------------
 */
function setHiddenAuthorisedUpload(authorisedUploadFieldName, hiddenFieldName) {

	// Get field elements
	var authorisedUploadField = document.getElementById(authorisedUploadFieldName);
	var hiddenField = document.getElementById(hiddenFieldName);
	
	// Get the value of the selected Authorised Upload Site
	if (authorisedUploadField.options.length > 0) {
		if (authorisedUploadField.selectedIndex >= 0) {
			var selectedUploadValue = authorisedUploadField.options[authorisedUploadField.selectedIndex].value;
		
			// Update the hidden field with the selected value
			hiddenField.value = selectedUploadValue;
		}
	}
}

/*-----------------------------------------------------------------------------
 * Name:        setHiddenAvailableUpload(availableUploadFieldName, hiddenFieldName)
 * Description: Updates the contents of a hidden field with the value of the 
 *				selected Available Upload Site.
 * Parameters:  authorisedFieldName
 *				hiddenFieldName
 *-----------------------------------------------------------------------------
 */
function setHiddenAvailableUpload(availableUploadFieldName, hiddenFieldName) {

	// Get field elements
	var availableUploadField = document.getElementById(availableUploadFieldName);
	var hiddenField = document.getElementById(hiddenFieldName);
	
	// Get the value of the selected Available Upload Site
	if (availableUploadField.options.length > 0) {
		if (availableUploadField.selectedIndex >= 0) {
			var selectedUploadValue = availableUploadField.options[availableUploadField.selectedIndex].value;
		
			// Update the hidden field with the selected value
			hiddenField.value = selectedUploadValue;
		}
	}
}

/*-----------------------------------------------------------------------------
 * Name:        setHiddenAuthorisedDownload(authorisedDownloadFieldName, hiddenFieldName)
 * Description: Updates the contents of a hidden field with the value of the 
 *				selected Authorised Download Site.
 * Parameters:  authorisedFieldName
 *				hiddenFieldName
 *-----------------------------------------------------------------------------
 */
function setHiddenAuthorisedDownload(authorisedDownloadFieldName, hiddenFieldName) {

	// Get field elements
	var authorisedDownloadField = document.getElementById(authorisedDownloadFieldName);
	var hiddenField = document.getElementById(hiddenFieldName);
	
	// Get the value of the selected Authorised Download Site
	if (authorisedDownloadField.options.length > 0) {
		if (authorisedDownloadField.selectedIndex >= 0) {
			var selectedDownloadValue = authorisedDownloadField.options[authorisedDownloadField.selectedIndex].value;
		
			// Update the hidden field with the selected value
			hiddenField.value = selectedDownloadValue;
		}
	}
}

/*-----------------------------------------------------------------------------
 * Name:        setHiddenAvailableDownload(availableDownloadFieldName, hiddenFieldName)
 * Description: Updates the contents of a hidden field with the value of the 
 *				selected Available Download Site.
 * Parameters:  authorisedFieldName
 *				hiddenFieldName
 *-----------------------------------------------------------------------------
 */
function setHiddenAvailableDownload(availableDownloadFieldName, hiddenFieldName) {

	// Get field elements
	var availableDownloadField = document.getElementById(availableDownloadFieldName);
	var hiddenField = document.getElementById(hiddenFieldName);
	
	// Get the value of the selected Available Download Site
	if (availableDownloadField.options.length > 0) {
		if (availableDownloadField.selectedIndex >= 0) {
			var selectedDownloadValue = availableDownloadField.options[availableDownloadField.selectedIndex].value;
		
			// Update the hidden field with the selected value
			hiddenField.value = selectedDownloadValue;
		}
	}
}

/*-----------------------------------------------------------------------------
 * Name:        checkFieldLength(field, maxLength)
 * Description: Checks whether the given field exceeds the max length and
 *				truncates it if necessary.
 * Parameters:	field
 *				maxLength
 *-----------------------------------------------------------------------------
 */
function checkFieldLength(field, maxLength) {

	var fieldVal = field.value;
	if (fieldVal.length >= maxLength) { 
		field.value = fieldVal.substring(0, maxLength);
	}
}

/*-----------------------------------------------------------------------------
 * Name:        function deleteMRC(actionFieldName, dirtyFieldName)
 *				
 * Description: Asks for confirmation of deletion.  If received and the action 
 *				is E it will set it to D and return false to prevent callback
 *				execution.  Otherwise it will set the cursor to busy and return
 *				the response to the confirmation request.
 *
 * Parameters:	actionFieldName - ID of the Action field for the current row.
 *				dirtyFieldName - ID of the Dirty field for the current row.
 *-----------------------------------------------------------------------------
 */
function deleteMRC(actionFieldName, dirtyFieldName) {

	var actionField = document.getElementById(actionFieldName);
	var dirtyField = document.getElementById(dirtyFieldName);

	// If action is E, set it to D and set dirty flag
	if (actionField.value == 'E') {
		actionField.value = 'D';
		dirtyField.value = 'true';
		return false;
	}
	else {
		
		//var retVal = getDeleteConfirmation('Are you sure you want to remove this existing characteristic?');
		//if (retVal) { 
		setCursorBusy();
		return true;
	} 
}

/*-----------------------------------------------------------------------------
 * Name:        showIncMrcSummaryContextMenu
 * Description: Displays the Sponsor context menu.
 * Parameters: 
 *              divName     - Name of the div to contain the menu. 
 *              rowKey      - UniqueId for the selected row.
 *              divShadowName - Name of the div making up the shadow
 *              hiddenRowFieldName - Name of the hidden row field holding the row ID for the selected row.
 *				menuMrcFieldName - Name of the menu field displaying the selected MRC.
 *				selectedMrc - The value of the selected MRC
 *-----------------------------------------------------------------------------
 */
function showIncMrcSummaryContextMenu(divName, rowKey, divShadowName, hiddenRowFieldName, menuMrcFieldName, selectedMrc) {

	// Get menu div, set position and display
	var containerBottom = 600;
	var menuDiv = document.getElementById(divName);
	var clickTop = event.y;
	var menuTop = 0;
	
	if (clickTop + 200 > containerBottom) {
		menuTop = containerBottom - 200;
	}
	else {
		menuTop = event.y;
	}
	menuDiv.style.top = menuTop;
	menuDiv.style.left = 20;                                    
	menuDiv.style.display = "";
	menuDiv.focus();
	
	// Get shadow div, set position and display
	var shadowDiv = document.getElementById(divShadowName);
	// shadowDiv.style.top = event.y + 5;
	shadowDiv.style.top = menuTop + 5;
	shadowDiv.style.left = 25;
	shadowDiv.style.display = "";
	
	// Get the hidden row ID field and set the value 
	var hiddenRowField = document.getElementById(hiddenRowFieldName);
	hiddenRowField.value = rowKey;
	
	// Get the menuMrcField and populate it
	var menuMrcField = document.getElementById(menuMrcFieldName);
	menuMrcField.value = selectedMrc;
}

/*-----------------------------------------------------------------------------
 * Name:        showSrcDataReferenceContextMenu
 * Description: Displays the SrcDataReference context menu.
 * Parameters: 
 *              divName       - Name of the div to contain the menu. 
 *              rowKey        - UniqueId for the selected row.
 *              scrollDivName - name of scrolling div
 *-----------------------------------------------------------------------------
 */
function showSrcDataReferenceContextMenu(divName, rowKey, scrollDivName) {
	
	// Get menu div, set position and display
	var menuDiv = document.getElementById(divName);
	var scroll = document.getElementById(scrollDivName).value;
	
	if (scroll == "") 
	{
		var scrollInt = 0;
	}
	else
	{
		var scrollInt = parseInt(scroll);
	}	
	
	menuDiv.style.top = scrollInt + 70;
	menuDiv.style.left = event.x;
	menuDiv.style.display = "";
	menuDiv.focus();	
}

/*-----------------------------------------------------------------------------
 * Name:        showReferenceLookupContextMenu
 * Description: Displays the SrcDataReference context menu.
 * Parameters: 
 *              divName       - Name of the div to contain the menu. 
 *              rowKey        - UniqueId for the selected row.
 *              scrollDivName - name of scrolling div
 *-----------------------------------------------------------------------------
 */
function showReferenceLookupContextMenu(divName, rowKey, verScrollDivName, horScrollDivName) {
	
	// Get menu div, set position and display
	var menuDiv = document.getElementById(divName);
	var verScroll = document.getElementById(verScrollDivName).value;
	
	if (verScroll == "") 
	{
		var verScrollInt = 0;
	}
	else
	{
		var verScrollInt = parseInt(verScroll);
	}
	
	var horScroll = document.getElementById(horScrollDivName).value;
	
	if (horScroll == "") 
	{
		var horScrollInt = 0;
	}
	else
	{
		var horScrollInt = parseInt(horScroll);
	}
	
	menuDiv.style.top = verScrollInt + 70;
	menuDiv.style.left = horScrollInt + event.clientX - 150;
	menuDiv.style.display = "";
	menuDiv.focus();	
}

/*-----------------------------------------------------------------------------
 * Name:        markRowDirty(rowID, dirtyColumnName)
 * Description: Marks the row with the given ID as dirty
 * Parameters: 
 *              rowID - ID of the row to mark as dirty
 *              dirtyColumnName - Name of the dirty column in each row.
 *-----------------------------------------------------------------------------
 */
function markRowDirty(rowID, dirtyColumnName) {

	// Use the row ID and column name to find the dirty column
	var dirtyColumn = document.getElementById(dirtyColumnName + rowID);
	dirtyColumn.value = true;
	return false;
	
}

/*-----------------------------------------------------------------------------
 * Name:        showMrcValidTablesContextMenu
 * Description: Displays the Sponsor context menu.
 * Parameters: 
 *              divName     - Name of the div to contain the menu. 
 *              rowKey      - UniqueId for the selected row.
 *              divShadowName - Name of the div making up the shadow
 *              hiddenRowFieldName - Name of the hidden row field holding the row ID for the selected row.
 *				menuTableFieldName - Name of the menu field displaying the selected Table.
 *				selectedTable - The value of the selected Table
 *				moveToFieldName - The name of the Move To field to focus on.
 *-----------------------------------------------------------------------------
 */
function showMrcValidTablesContextMenu(divName, rowKey, divShadowName, hiddenRowFieldName, 
	menuTableFieldName, selectedTable, moveToFieldName) {

	// Get menu div, set position and display
	var menuDiv = document.getElementById(divName);
	menuDiv.style.top = event.y;
	menuDiv.style.left = 130;                                    
	menuDiv.style.display = "";
	menuDiv.focus();
	
	// Get shadow div, set position and display
	var shadowDiv = document.getElementById(divShadowName);
	shadowDiv.style.top = event.y + 5;
	shadowDiv.style.left = 135;
	shadowDiv.style.display = "";
	
	// Get the hidden row ID field and set the value 
	var hiddenRowField = document.getElementById(hiddenRowFieldName);
	hiddenRowField.value = rowKey;

	// Get the menuMrcField and populate it
	var menuTableField = document.getElementById(menuTableFieldName);
	menuTableField.value = selectedTable;
	
	// Get the moveTo field and focus on it
	var moveToField = document.getElementById(moveToFieldName);
	moveToField.focus();
}

/*-----------------------------------------------------------------------------
 * Name:        showPermittedIsacsContextMenu
 * Description: Displays the Permitted ISACs context menu.
 * Parameters: 
 *              divName     - Name of the div to contain the menu. 
 *              rowKey      - UniqueId for the selected row.
 *              divShadowName - Name of the div making up the shadow
 *              hiddenRowFieldName - Name of the hidden row field holding the row ID for the selected row.
 *				menuKeyFieldName - Name of the menu field displaying the key identifying the selected row.
 *				key - The value of the key representing the selected row
 *-----------------------------------------------------------------------------
 */
function showPermittedIsacsContextMenu(divName, rowKey, divShadowName, hiddenRowFieldName, menuKeyFieldName, selectedKey) {

	// Get menu div, set position and display
	var menuDiv = document.getElementById(divName);
	var containerBottom = 600;
	var clickTop = event.y;
	var menuTop = 0;
	
	if (clickTop + 200 > containerBottom) {
		menuTop = containerBottom - 200;
	}
	else {
		menuTop = event.y;
	}
	
	menuDiv.style.top = menuTop;
	menuDiv.style.left = 300;                                    
	menuDiv.style.display = "";
	menuDiv.focus();
	
	// Get shadow div, set position and display
	var shadowDiv = document.getElementById(divShadowName);
	shadowDiv.style.top = menuTop + 5;
	shadowDiv.style.left = 305;
	shadowDiv.style.display = "";
	
	// Get the hidden row ID field and set the value 
	var hiddenRowField = document.getElementById(hiddenRowFieldName);
	hiddenRowField.value = rowKey;
	
	// Get the menuKeyField and populate it
	var menuKeyField = document.getElementById(menuKeyFieldName);
	menuKeyField.value = selectedKey;
}

/*-----------------------------------------------------------------------------
 * Name:        displayNcbReport(url, reportGeneratedFieldName, reportFieldName)
 * Description: If the report contains a value, display it.
 * Parameters:  url - the URL as generated by the form bean.
 *				reportGeneratedFieldName - name of the field containing a 
 *				boolean to indicate whether report is generated.
 *-----------------------------------------------------------------------------
 */
function displayNcbReport(url, reportGeneratedFieldName) {
 
 	// Get handle to boolean field
 	var reportGeneratedField = document.getElementById(reportGeneratedFieldName);
 
 	var reportGenerated = reportGeneratedField.value;
 	
 	// If report has been generated, display it in a popup.
 	if (reportGeneratedField.value == 'true') {
 		showPopup(url, null, 'Report', '780', '660', '1');
	}

	// Reset boolean indicator
	reportGeneratedField.value = 'false';

	return true;
}


/*-----------------------------------------------------------------------------
 * Name:        initSelectInput
 * Description: Initialise the user input values for interactive HTML drop-down lists
 * Parameters:  
 *-----------------------------------------------------------------------------
 */
function initSelectInput()
{
	selectBoxInput = "";
	selectBoxInputLength = 0;
}


/*-----------------------------------------------------------------------------
 * Name:        selectListboxValue
 * Description: Selects a value in a drop-down list where the first characters match
 *				the given value
 * Parameters:  id		The id of the select element
 *				value	The value to match
 *-----------------------------------------------------------------------------
 */
function selectListboxValue(id, value)
{
	var theSelect = document.getElementById(id);
	var length = value.length;
	var index = -1;

	if (theSelect && length > 0) {

		for (var i = 0; i < theSelect.options.length && index == -1; i++) {
			option = theSelect.options[i].text;
			compare = option.substring(0, length);

			if (compare == value) {
				index = i;
			}
		}

		if (index != -1) {
			theSelect.options[index].selected = true;
		}
	}
}


/*-----------------------------------------------------------------------------
 * Name:        selectKeypress
 * Description: Stores user keypresses for a drop-down listbox (single select).
 *				The only control key recognised is backspace.
 *				See taskDetails.jsp for an example of how to use this feature.
 * Parameters:  id		The id of the select element
 *				e		The event (not IE)
 *-----------------------------------------------------------------------------
 */
function selectKeypress(id, e)
{
	var keycode;

	if (window.event) {
		keycode = window.event.keyCode;
	}
	else {
		keycode = e.which;
	}

	if (keycode == 8) {

		if (selectBoxInputLength > 0) {
			selectBoxInputLength = selectBoxInputLength - 1;
			if (selectBoxInputLength == 0) {
				selectBoxInput="";
			}
			else {
				selectBoxInput = selectBoxInput.substring(0, selectBoxInputLength);
			}
		}
	}
	else if (keycode == 27) {
		selectBoxInputLength = 0;
		selectBoxInput="";
	}
	else if (keycode == 32 || keycode >= 48 && keycode <= 105) {
		selectBoxInputLength = selectBoxInputLength + 1;
		selectBoxInput = selectBoxInput + String.fromCharCode(keycode);	
	}
	else {
		return true;
	}

	selectListboxValue(id, selectBoxInput);
	if (window.event) {
		window.event.returnValue = false;
	}
	else {
		e.returnValue = false;
	}

	return false;
}



/*-----------------------------------------------------------------------------
 * Name:        encodeUrl
 * Description: Extracts the session information from the first parameter and modifies
 *				the given URL to include the session information.  Returns the result.
 *
 * Parameters:  encodedUrl	-	Any URL which already has the encoding
 *				url			-	The URL to encode
 *-----------------------------------------------------------------------------
 */
function encodeUrl(encodedUrl, url)
{
	var newUrl = url;
	var sessionInfo = ""
	start = encodedUrl.indexOf(";")
	if (start != -1) {
		end = encodedUrl.indexOf("?")
		if (end == -1) {
			sessionInfo=encodedUrl.substring(start);
		}
		else {
			sessionInfo=encodedUrl.substring(start, end-1);
		}
		
		position=url.indexOf(sessionInfo);
		
		if (position == -1) {
			position=url.indexOf("?");
			if (position == -1) {
				newUrl=url.concat(sessionInfo);
			}
			else {
				sessionInfo=sessionInfo+"?";
				newUrl=url.replace("?",sessionInfo);
			}
		}
	}
	
	return newUrl;
}

/*-----------------------------------------------------------------------------
* Name: closeOnComplete(completeFieldName)
* Description: Checks a given field to see whether it contains the value true 
* 			   and if so, closes the window.
*-----------------------------------------------------------------------------
*/
function closeOnComplete(completeFieldName) {

	var completeFieldVal = document.getElementById(completeFieldName).value;
	
	// If complete field is true...
	if (completeFieldVal == 'true') {
	
		// Close the popup		
		self.close();

	}
}


/*-----------------------------------------------------------------------------
 * Name:        showFlashPopup
 * Description: 
 *
 * Parameters:  showFlash	-	Indicates whether the user has unread flash messages
 *				url			-	The popup url
 *-----------------------------------------------------------------------------
 */
function showFlashPopup(showFlash, url) {

	if (showFlash == 'true') {
		showPopup(url, null, 'FlashNotice', '750', '560', '1');
	}
}


/*-----------------------------------------------------------------------------
 * Name:        confirmPutTaskLine
 * Description: 
 *
 * Parameters:  showFlash	-	Indicates whether the user has unread flash messages
 *				url			-	The popup url
 *-----------------------------------------------------------------------------
 */
function confirmPutTaskLine(status, forecastId, actualId) {

	var forecast = window.document.getElementById("iptForecast").value;
	var actual = window.document.getElementById("iptActual").value;
	
	var retVal = getConfirmation('This will change the status of this task from ' + status + ' to L,\nand will save the change.  Do you want to continue?'); 
	if (retVal && forecast != null && actual != null) {
		if (parseInt(actual) > parseInt(forecast)) {
			retVal = getConfirmation('This project code has exceeded its forecast number of line entries.\nDo you want to continue?');
		}
	}
	
	return retVal;
}

/*-----------------------------------------------------------------------------
 * Name: setHiddenSelectedItem
 * Description: Updates the value of a hidden field with the value of the selected item in an options list.
 *
 * Parameters: optionListName - the name of an option list element
 *			   hiddenFieldName - the name of a hidden field
 *-----------------------------------------------------------------------------
 */
function setHiddenSelectedItem(optionListName, hiddenFieldName)
{
	var optionList = document.getElementById(optionListName);
	var hiddenField = document.getElementById(hiddenFieldName);
	
	if (optionList.options.length > 0)
	{
		var selectedItemIndex = optionList.selectedIndex;
		
		if (selectedItemIndex > -1)
		{
			var selectedOptionListValue = optionList.options[selectedItemIndex].value;
			hiddenField.value = selectedOptionListValue;
		}
	}
}

/*-----------------------------------------------------------------------------
 * Name:        checkDecimalValue(fieldName, intLength)
 * Description: Check the integer part of the decimal value is not longer than
 				intLength and remove not number characters.
 * Parameters:	fieldName
 *				intLength
 *-----------------------------------------------------------------------------
 */
function checkDecimalValue(fieldName, intLength)
{
	var field = document.getElementById(fieldName);
	var fieldVal = field.value;
	
	var intPartValue;
	if (fieldVal.indexOf('.') != -1) {
		intPartValue = fieldVal.substring(0, fieldVal.indexOf('.'));
	}
	else {
		intPartValue = fieldVal;
	}
	
	if (intPartValue.length > intLength) { 
		field.value = 'Invalid';
		alert('Correct format: decimal(' + intLength + ',3)');
	}
	else {
		field.value = field.value.replace( /[^\d\*\s;%\.]+/g, '' ) ;
	}
}

