/* Common Javascript used throughout system */

var gEventWindow, gHelpWindow, gPhotoViewerWindow, gCalWindow, gJScripts;
var gAddrElements = new Array("Address1","Address2","City","Province","Postal");
var gToggleOpened = "panelOpened.gif";
var gToggleClosed = "panelClosed.gif";
var gSearchForm = "frmSearchParms";

userAgent = window.navigator.userAgent; 
browserVers = parseInt(userAgent.charAt(userAgent.indexOf("/")+1),10);
CSIsW3CDOM = ((document.getElementById) && !(IsIE()&&browserVers<6)) ? true : false;

function populateCountries(pSelectObj) {

// Populate Country select options based on selected Continent 

	return;	//country seelction suppressed
	
	var aForm = pSelectObj.form;
	var aContinent = pSelectObj.options[pSelectObj.selectedIndex].value;
	var aCountrySelectObj = aForm.Country;
	
	aCountrySelectObj.length = 1;	//just keep the "All countries" item
	
	for(var aI=0; aI<arCountrys.length; aI+=3) {
		if (aContinent=='0' || aContinent==arCountrys[aI+2]) {			
			aCountrySelectObj.add(new Option(arCountrys[aI+1], arCountrys[aI], false, false), null);
		}
	}
}

function populateMembers(pSelectObj) {

// Populate Member select options based on selected Continent 

	var aForm = pSelectObj.form;
	var aContinent = pSelectObj.options[pSelectObj.selectedIndex].value;
	var aMemberSelectObj = aForm.Member;
	
	aMemberSelectObj.length = 1;	//just keep the "All members" item
	
	for(var aI=0; aI<arMembers.length; aI+=3) {
		if (aContinent=='0' || aContinent==arMembers[aI+2]) {			
			aMemberSelectObj.add(new Option(arMembers[aI+1], arMembers[aI], false, false), null);
		}
	}
}

function checkDatabaseSearchForm() {

// check advanced search form... no checking required (selections only)

	return true;
	
}

function searchJSInit() {

// initialize the machinery to show expertise description when expertise item selected

	var aSelectObj = document.getElementById("Expertise")
	
	aSelectObj.onchange=function() { //run some code when "onchange" event fires
		var aSelectedOption = this.options[this.selectedIndex];
		if (aSelectedOption)	{
			var aDefinition = this.form.elements[aSelectedOption.value + "_definition"].value;
			if (aDefinition != "")  alert("This area of expertise includes:\r\n" + aDefinition);
		}
	}
}

function trim(val) {
	var i,j;
	i = 0;
	while (i<val.length && val.charAt(i) == " ") i++;
	if (i>= val.length) return "";
	j = val.length-1;
	while (j>=0 && val.charAt(j) == " ") j--;
	return val.substring(i,j+1);
}

var gClientTimezoneOffset = (new Date()).getTimezoneOffset()
var gDaylightDiff = gClientTimezoneOffset - (new Date(2006,0)).getTimezoneOffset(); //negative if summer time on
var gServerTimezoneOffset;
var gTimezoneOffsetStandard = gServerTimeZoneOffsetStandard();
try{
	gServerTimezoneOffset = gTimezoneOffsetStandard + gDaylightDiff; //minutes
}
catch(aEx){
	// assume server in Ottawa
	gServerTimezoneOffset = -360 + gDaylightDiff; //minutes
}

function gServerTimeZoneOffsetStandard(){
	
	// returns the offset (minutes) at the server: current server time - UTC
	// negative if west of Greenwich (-300 for Ottawa/Montreal; -480 for Vancouver)
	
	return(-1 * (new Date(2006,0)).getTimezoneOffset()); 
}

function IsIE() { return userAgent.indexOf("MSIE") > 0;}

function IsWin() { return (typeof(navigator.platform) != "undefined"  &&  navigator.platform.substr(0,3)=="Win");}

function CSIEStyl(s) { return document.all.tags("div")[s].style; }

function CSNSStyl(s) { if (CSIsW3CDOM) return document.getElementById(s).style; else return findElement(s,0);  }

mustInitImg = true;

function initImgID() {
	di = document.images; 
	if (mustInitImg && di) { 
		for (var i=0; i<di.length; i++) { 
			if (!di[i].id) di[i].id=di[i].name; 
		} 
	mustInitImg = false;
	}
}

function findElement(n,ly) {
	d = document;
	if (browserVers < 4) return d[n];
	if ((browserVers >= 6) && (d.getElementById)) {initImgID; return(d.getElementById(n))}; 
	var cd = ly ? ly.document : d;
	var elem = cd[n];
	if (!elem) {
		for (var i=0;i<cd.layers.length;i++) {
			elem = findElement(n,cd.layers[i]);
			if (elem) return elem;
		}
	}
	return elem;
}

function changeImages() {
	d = document;
	if (d.images) {
		var img;
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			img = null;
			if (d.layers) {img = findElement(changeImages.arguments[i],0);}
			else {img = d.images[changeImages.arguments[i]];}
			if (img) {img.src = changeImages.arguments[i+1];}
			//else alert("ChangeImages can't find " + changeImages.arguments[i]);
		}
	}
}

function EF(pE,pF) {

// return English or French version: pE and pF may not be strings!

	if (gLanguage == "E") {
		return pE;
	} else {
		if (typeof(pF) == "string" && pF=="*F") {
			if (typeof(pE) == "string") return "*F " + pE;
			else return pE;
		}
		else return pF;
	}
	
}

function openPhotoViewer(pFile,pWidth,pHeight) {
// Open Photo viewer window and load the specified file

	var aContents, aXTop, aYTop, aWinWidth, aWinHeight, aRows;
	var aWindowTopX = screen.availWidth - pWidth - 36;  //indent 36px from right of screen
	var aWindowTopY = 75;
	var aWindowWidth = pWidth;
	var aWindowHeight = Math.min(screen.height-(aWindowTopY*2),pHeight);
	var aPosArray = new Array();
	var aOptions = "resizable=yes, toolbar=no, menubar=no, status=no";
	var aName = "PhotoViewer";

	if(gPhotoViewerWindow && gPhotoViewerWindow.open && !gPhotoViewerWindow.closed){
		gPhotoViewerWindow.location = pFile;
		gPhotoViewerWindow.focus();
	}else{

		if(getCookie("PhotoViewerFramesPosData"))
		{
			aPosArray = setWindowPositionFromCookie("PhotoViewerFramesPosData");
			if(IsIE()){
				aXTop = "left=" + aPosArray[0];
				aYTop = "top=" + aPosArray[1];
			}else{
				aXTop = "screenX=" + aPosArray[0];
				aYTop = "screenY=" + aPosArray[1];
			}
			aWinWidth = "width=" + aPosArray[2];
			aWinHeight = "height=" + aPosArray[3];
		}else{
			aPosArray = new Array(aWindowTopX,aWindowTopY,aWindowWidth,aWindowHeight);
			if(IsIE())
			{
				aXTop  = "left=" + aWindowTopX;
				aYTop  = "top=" + aWindowTopY;
			
		
			}else{

				aXTop = "screenX=" + aWindowTopX;
				aYTop = "screenY=" + aWindowTopY;
			}
			aWinWidth = "width=" + aWindowWidth;
			aWinHeight = "height=" + aWindowHeight;

		}
	}

   gPhotoViewerWindow = window.open(pFile, aName, aOptions + ',' + aXTop + ',' + aYTop + ',' + aWinHeight + ',' + aWinWidth);
   gPhotoViewerWindow.focus();

}

function openHelp(pFolder,pFile,pKey) { 
// Open a Help window with specified Folder, File and Key

	var aContents, aXTop, aYTop, aWinWidth, aWinHeight, aRows;
	var aWindowTopX = 0; 
	var aWindowTopY = 75;
	var aWindowWidth = 300;
	var aFrameIndexHeight = 237;
	var aFrameContentsHeight = 664;
	var aFrameFooterHeight = 47;
	var aWindowHeight = screen.height-(aWindowTopY*2);
	var aPosArray = new Array();
	var aOptions = "resizable=yes, toolbar=no, menubar=no";
	var aName = "Help";
	var aScriptsIndex = pFolder.toLowerCase().indexOf("/scripts/");
	var aDirSystem = pFolder.substring(0,aScriptsIndex);


	if(gHelpWindow && !gHelpWindow.closed && gHelpWindow.frames[1].location){
		gHelpWindow.frames[1].location.href = pFolder + pFile + "#" + pKey;
	}else{
	
		gJScripts = "<script language='JavaScript' src='" + aDirSystem + "/Scripts/Common/jsCommon.js'></script>"
			+ "<script language='JavaScript' src='" + aDirSystem + "/Scripts/Common/jsFrames.js'></script>"; 
		

	if(pFile == ""  || pFolder == null ){
	   pFile = "HelpDefaultE.htm";
	}

	if(pFolder == "" || pFolder == null ) {
	   pFolder = "";
	}

	if(getCookie("HelpFramesPosData"))
    {
		aPosArray = setWindowPositionFromCookie("HelpFramesPosData");
		if(IsIE()){
			aXTop = "left=" + aPosArray[0];
			aYTop = "top=" + aPosArray[1];
		}else{
			aXTop = "screenX=" + aPosArray[0];
			aYTop = "screenY=" + aPosArray[1];
		}
		aWinWidth = "width=" + aPosArray[2];
		aWinHeight = "height=" + aPosArray[3];
		aRows =  getFrameRows(aPosArray,4);
		

	}else{
		aPosArray = new Array(aWindowTopX,aWindowTopY,aWindowWidth,aWindowHeight,aFrameIndexHeight,aFrameContentsHeight,aFrameFooterHeight);
		if(IsIE())
		{
			aXTop  = "left=" + aWindowTopX;
			aYTop  = "top=" + aWindowTopY;
			
		
		}else{

			aXTop = "screenX=" + aWindowTopX;
			aYTop = "screenY=" + aWindowTopY;
		}
		aWinWidth = "width=" + aWindowWidth;
		aWinHeight = "height=" + aWindowHeight;
		aRows = aFrameIndexHeight + "," + aFrameContentsHeight + "," + aFrameFooterHeight;
	}


		gHelpWindow = window.open(aDirSystem + "/Scripts/Help/Blank.htm", aName, aOptions + ',' + aXTop + ',' + aYTop + ',' + aWinHeight + ',' + aWinWidth);
	
	var aFile = pFile;
		if (aFile.indexOf("#") == -1 && pKey != "") aFile += "#" + pKey;
	
	aContents = "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>";
	aContents += "<html><head>";
	aContents += "<meta http-equiv='content-type' content='text/html;charset=windows-1252'>";
		aContents += "<title>" + EF("Help Window","Fen&ecirc;tre d&rsquo;aide") + "</title>";
	aContents += gJScripts + "<Script>var gFrameBottom = new Array(true,false,false);";
	aContents += "var gWindowDimensions = new Array(" + aPosArray[0] + "," + aPosArray[1] + "," + aPosArray[2] + "," + aPosArray[3] + ");";
	aContents += "var gFrameHeightCur = new Array(" + aPosArray[4] + "," + aPosArray[5] + "," + aPosArray[6] + ");";
	aContents += "</Script></head>";
	aContents += "<frameset id='HelpFrameset' name='HelpFrameset' rows='" + aRows + windowResize() + windowOnLoad() + windowUnload(aName) + ">";
	aContents += "<frame id='HelpIndex' name='HelpIndex' src='" + pFolder + EF("HelpIndexE.htm","HelpIndexF.htm") + "' onresize='top.frameScroll();'>";
	aContents += "<frame id='HelpContents' name='HelpContents' src='" + pFolder + aFile + "'>";
	aContents += "<frame id='HelpClose' name='HelpClose' src='" + pFolder + EF("HelpCloseE.htm","HelpCloseF.htm") + "' noresize>";
	aContents += "</frameset></html>";
	
	gHelpWindow.document.writeln(aContents);

	}
	
	gHelpWindow.focus();

}

function eventsOpen() {

// Open a window with blank contents

	var aWinHeight, aWinWidth, aXTop, aYTop;
	var aWindowTopX = 0; 
	var aWindowTopY = 75;
	var aWindowWidth = 400;
	var aWindowHeight = screen.height-(aWindowTopY*2);
	var aPosArray = new Array();
	var aOptions = "resizable=yes, toolbar=no";
	if (gcMode != "Prod")
	{
		aOptions += ", menubar=yes";
	}else{
		aOptions += ", menubar=no";
	}

	var aName = "Event";

	if(gEventWindow && gEventWindow.open && !gEventWindow.closed){
		gEventWindow.focus();
	}else{

		if(getCookie("EventFramesPosData"))
		{
			aPosArray = setWindowPositionFromCookie("EventFramesPosData");
			if(IsIE()){
				aXTop = "left=" + aPosArray[0];
				aYTop = "top=" + aPosArray[1];
			}else{
				aXTop = "screenX=" + aPosArray[0];
				aYTop = "screenY=" + aPosArray[1];
			}
			aWinWidth = "width=" + aPosArray[2];
			aWinHeight = "height=" + aPosArray[3];
		
		}else{
			if(IsIE())
			{
				aXTop  = "left=" + aWindowTopX;
				aYTop  = "top=" + aWindowTopY;
			}else{

				aXTop = "screenX=" + aWindowTopX;
				aYTop = "screenY=" + aWindowTopY;
			}
			aWinWidth = "width=" + aWindowWidth;
			aWinHeight = "height=" + aWindowHeight;
			
		}

		gEventWindow = window.open("eCoopEvents.asp?Op=Init",aName,aOptions + ',' + aXTop + ',' + aYTop + ',' + aWinHeight + ',' + aWinWidth);
		if(gEventWindow)gEventWindow.focus();
	}
}

function popupsClose() {

// Close any open popup windows (help, events)

	//if (!top.newWin) alert("top.newWin is not there!");
	//if (top.newWin) alert("top.newWin is there!");
	if (top.newWin) gCalWindow.close();
	if (gEventWindow) gEventWindow.close();
	if (gHelpWindow) gHelpWindow.close();

}

function transfer(pTransfer) {

// Submits a form that goes to current script to check for changes before going to transfer script

      if (document.frmEdit.action.indexOf("Transfer=") == -1) {	//don't do it twice!
         document.frmEdit.action += "Transfer=" + pTransfer; 
         document.frmEdit.submit();
      }

}

function DateDiff(pUnits, pDate1, pDate2) {

// Returns the difference in Units between Date1 and Date 2 -- only for days now!

	var aMillisecs;
	
	switch (pUnits.toUpperCase()) {
		case "D" : aMillisecs = 1000*60*60*24; break;
	}
	  
	return (Math.floor(pDate2.getTime()/aMillisecs) - Math.floor(pDate1.getTime()/aMillisecs));}


function sFormatDate(pDate) {

// Formats a date in standard dd mon yyyy format

	if(!pDate || pDate == "") return String(pDate);
	if(isNaN(pDate)) return String(pDate);

	var aMonths;
	if (gLanguage == "F"){ 
	   aMonths = new Array("janv","f\xE9v","mars","avr","mai","juin","juil","ao\xFBt","sept","oct","nov","d\xE9c");
	}else{
	   aMonths = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	}
	
	return pDate.getDate() + " " + aMonths[pDate.getMonth()] + " " + pDate.getFullYear();
	
}
	
function sFormatDateNum(pDate) {

// Formats a date in numeric mm/dd/yyyy format as a string

	if(!pDate || pDate == "") return String(pDate);
	if(isNaN(pDate)) return String(pDate);

	return pDate.getMonth() + 1  + "/" + pDate.getDate() + "/" + pDate.getFullYear();
	
}
	
function sFormatDateTime(pDate) {

// Formats a date in standard dd mon yyyy hh:mm am|pm Eastern Time format

	if(!pDate || pDate == "") return String(pDate);
	if(isNaN(pDate)) return String(pDate);

	var aMonths = (gLanguage == "F") ? 
	   (new Array("janv","f\xE9v","mars","avr","mai","juin","juil","ao\xFBt","sept","oct","nov","d\xE9c"))
	   : (new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"));
	   
	var aTimezone;
	var aDaylightDiff = pDate.getTimezoneOffset() - (new Date(2006,0)).getTimezoneOffset(); //< 0 if pDate is daylight savings time
	
	if (gLanguage == "E") {
		aTimezone = (aDaylightDiff == 0) ? "EST" : "EDT";
	} else {
		aTimezone =  (aDaylightDiff == 0) ? "HNE" : "HAE";
	}
	
	var aHours = pDate.getHours();
	var aMinutes = pDate.getMinutes();
	if (aHours == 0 && aMinutes == 0) return sFormatDate(pDate);
	
	aMinutes = String(100 + aMinutes).substr(1);
	if (aHours < 12) return sFormatDate(pDate) + " " + aHours + ":" + aMinutes + " am " + aTimezone;
	else if (aHours == 12) return sFormatDate(pDate) + " " + "12:" + aMinutes + " pm " + aTimezone;
	else return sFormatDate(pDate) + " " + (aHours-12) + ":" + aMinutes + " pm " + aTimezone;
	
}
	
function setTimeField(aSelectObject) {

// Sets the time field to the time represented by the three popups (_hour, _min, _ampm)
// used by dxTimeOfDay in libDE

	var aForm = aSelectObject.form
	
	var aFieldParts = aSelectObject.name.split("_");
	
	var aTimeField = aFieldParts[0];
	
	aForm.elements[aTimeField].value 
		= aForm.elements[aTimeField + "_hour"].value + ":"
		+ aForm.elements[aTimeField + "_min"].value + ":00 "
		+ aForm.elements[aTimeField + "_ampm"].value;
		
}

function sUnformatNumber(pString) {

// Returns the numeric value of the unformatted string, or NaN if not a number

   var aFieldValue = pString.replace(/,| |\xa0/g,""); //remove commas, blanks and non-br space
   
   var aFieldValue2 = aFieldValue.replace(/\(([^\)]*)\)/,"$1");	//convert enclosing brackets...
   if (aFieldValue != aFieldValue2) aFieldValue = "-" + aFieldValue2;	//...to minus
   
   return parseInt( aFieldValue, 10);

}


function sFormatNumber(pValue) {

// Formats a number with thousands separators [comma for English, blank for French], brackets negative values

   var aValue = sUnformatNumber(pValue)
   
   if ( isNaN(aValue) ) return pValue;

   var aSep = (gLanguage=="E") ? "," : " ";
   
   if (pValue >= 0 ) {aSign=""; aValue = pValue;}
   else {aSign="-"; aValue = -pValue;}
   
   var aResult = "";
   for(;true;) {
      if(aResult != "") aResult = aSep + aResult;
      aResult =  aValue>999  ?  ( (1000 + (aValue%1000)) + "").substr(1) + aResult  :  aValue%1000 + "" + aResult; 
      aValue = parseInt(aValue/1000, 10);
      if (aValue<1) break; 
   }
   return (aSign=="-" && aResult!="0") ? "(" + aResult + ")": aResult  + "\xa0"; // 	//avoid (0)
}


function toggleDisplay(pBlockId, pTextId) {

// toggle display of the block and toggle the text ("Show", "Hide")

	var aDisplayBlock = document.getElementById(pBlockId);
	var aTextBlock = document.getElementById(pTextId);
	
	var aDisplayedText = aTextBlock.innerHTML;
	switch (aDisplayedText) {
		case "Show":
		case "Montrer":
		case "Afficher":
			aTextBlock.innerHTML = EF("Hide", "Cacher");
			aDisplayBlock.style.display = "Block";
			break;
		case "Hide": 
		case "Cacher":
			aTextBlock.innerHTML = EF("Show", "Afficher");
			aDisplayBlock.style.display = "None";
			break;
	}

}

function selectboxResize(pFieldName, pbOpen){

// resize the select box to full and multiple or one option showing

	var aFrm = document.forms[gSearchForm];
	var aOptions = aFrm.elements[pFieldName].options;

	var aSize, aI;
	if (pbOpen) {
		aOptions[0] = null;
		aSize = aOptions.length;
		for(aI = 0; aI<aOptions.length; aI++) {
			aOptions[aI].selected = false;
		}
	} else {
		aOptions[aOptions.length] = new Option;
		for(var aI = aOptions.length-1; aI>0; aI--) {
			aOptions[aI].text = aOptions[aI-1].text;
			aOptions[aI].value = aOptions[aI-1].value;
			aOptions[aI].selected = false;
		}
		aOptions[0].text = EF("(All)", "(Tous)");
		aOptions[0].value = "(All)";
		aOptions[0].selected = false;
		aSize = 1;
	}
	aFrm.elements[pFieldName].size = aSize;
	
}
 
function toggleSelectBox(pFieldName){

// open or close select box and toggle associated image

	var aImage = document.getElementById("Toggle" + pFieldName);
	var aLoc = aImage.src.lastIndexOf("/");
	var aPath = aImage.src.substring(0,aLoc+1);
	var aFile = aImage.src.substr(aLoc+1);
	selectboxResize(pFieldName, (aFile == gToggleClosed));
	aImage.src = (aFile == gToggleClosed? aPath + gToggleOpened : aPath + gToggleClosed);
	
}

function disableSections(){

// temporary function to disable print blank form for incomplete sections

	var af = document.frmEdit;
    var aSet = af.report[1].checked;

	for(var aI = 1; aI < af.section.length-1; aI++){
		af.section[aI].disabled = aSet; 
    }
}

function printSectionsCheck(){
// check if there are any check boxes selected for the print sections

	var aFrm = document.frmEdit;
	
	for(var aI = 0; aI < aFrm.section.length; aI++){
		if(aFrm.section[aI].checked){ return true; } 
    }

	alert("Sorry, you haven't selected any sections to print");
	return false;

}

function CSOpenWindow(action) {
	var wf = "";	
	wf = wf + "width=" + action[3];
	wf = wf + ",height=" + action[4];
	wf = wf + ",resizable=" + (action[5] ? "yes" : "no");
	wf = wf + ",scrollbars=" + (action[6] ? "yes" : "no");
	wf = wf + ",menubar=" + (action[7] ? "yes" : "no");
	wf = wf + ",toolbar=" + (action[8] ? "yes" : "no");
	wf = wf + ",directories=" + (action[9] ? "yes" : "no");
	wf = wf + ",location=" + (action[10] ? "yes" : "no");
	wf = wf + ",status=" + (action[11] ? "yes" : "no");		
	window.open(action[1],action[2],wf);
}
//
// CROSS-BROWSER ROUTINES TO DEAL WITH KEYBOARD INPUT
// In IE on Windows, uses default Tab action and converts Enter to Tab except in Textareas and Submits
// On other browsers/platforms, traps Tab and Enter, and uses nextFocus routine to advance
// the focus to the next focusable field in tabindex order.
// Function firstFocus sets focus to focusable field with lowest positive tabindex.

function keyCode(pEvent) {

// cross-browser keycode for keyboard event

   if (IsIE()) return event.keyCode;
   var aKeyCode = pEvent.keyCode;
   if (aKeyCode == 0) aKeyCode = pEvent.which;	//Mozilla
   return aKeyCode;
}
	
function keyTarget(pEvent) {

// cross-browser target of keyboard event

   return IsIE() ? event.srcElement : pEvent.target;
}

function tabIndex(pElement) {

// Return signed tabIndex (Safari forces tabIndex to be positive)

	return (pElement.tabIndex < 16384) ? pElement.tabIndex : pElement.tabIndex - 32768;
}

function IsFocusable(pElement) {

// Returns true if pElement is a form element that can be given the focus and 
// is not disabled or readonly or inside a DIV with display=none

   if (pElement.disabled || pElement.readOnly) return false;
   for (var elAncestor = pElement.parentNode; (elAncestor.nodeName != "HTML") && (elAncestor.nodeName != "FORM") && (elAncestor.nodeName!="DIV"); elAncestor = elAncestor.parentNode); 
   if ((elAncestor.nodeName == "DIV") && (elAncestor.style.display == "none")) return false;
   
   var aType = pElement.type;
   return (aType == "text" ||  aType == "textarea" || aType == "password" || aType == "submit" ); 
   //|| aType.substr(0,6) == "select");
}

function trapEnter(pEvent) {

// onkeydown="return trapEnter(event);" convert enter to tab in IE Windows; call nextFocus on tab,enter in IE Mac

   return IEtrapEnter();
}

function IEtrapEnter() {

// onkeydown="return IEtrapEnter();" convert enter to tab in IE Windows; call nextFocus on tab,enter in IE Mac

   if (IsIE()) {
      var aTarget = event.srcElement;
      if (IsWin()) {
         if (event.keyCode == 13  &&  aTarget.type != "textarea"  &&  aTarget.type != "submit") event.keyCode = 9;
         return true;
      } else {
         if ( event.keyCode == 9  ||  (event.keyCode == 13  &&  aTarget.type != "textarea"  &&  aTarget.type != "submit") ) {
            nextFocus(aTarget);
            return false;
         }
      }
   }
   return true;
}

function trapTabEnter(pEvent) {

// onkeypress="return trapTabEnter(pEvent);" convert enter to tab in IE Windows; call nextFocus on tab,enter for other browsers; 
// if neither tab or enter, return keycode (treated as true)

   var aKeyCode = keyCode(pEvent);
   var aTarget = keyTarget(pEvent);
   if (aKeyCode == 9  ||  (aKeyCode == 13  &&  aTarget.type != "textarea"  &&  aTarget.type != "submit") ) {
      if (IsIE()  &&  IsWin()) {
         event.keyCode = 9; 
         return true;
      }
      nextFocus(aTarget);
      return false;
   }
   return aKeyCode;
}

// Checks for valid data entry

function trapInvalid(pEvent,pValidChars) {

// cross-browser; traps tab/enter moving focus, traps and suppresses invalid char
	
   var aResult = trapTabEnter(pEvent);
   //alert("aResult: " + aResult);
   switch (aResult) {
      case true:
         return aResult;
      case false:
         return aResult;
      case 8:	//backspace
      case 127:	//delete
         return true;
      default:
		 //alert("String.fromCharCode(aResult): " + String.fromCharCode(aResult));
		 //alert("pValidChars.indexOf(String.fromCharCode(aResult)): " + pValidChars.indexOf(String.fromCharCode(aResult)));
         return (pValidChars.indexOf(String.fromCharCode(aResult)) >= 0);
   }
}

function trapInvalidDigit(pEvent) {

   return trapInvalid(pEvent,"0123456789");
}

function trapInvalidInteger(pEvent) {

   return trapInvalid(pEvent,"0123456789");
}

function trapInvalidSignInteger(pEvent) {

   return trapInvalid(pEvent,"0123456789-");
}

function trapInvalidDecimal(pEvent) {

   return trapInvalid(pEvent,"0123456789.");
}

function trapInvalidDecimalE(pEvent) {

   return trapInvalid(pEvent,"0123456789.");
}

function trapInvalidDecimalF(pEvent) {

   return trapInvalid(pEvent,"0123456789,");
}

function trapInvalidSignDecimal(pEvent) {

   return trapInvalid(pEvent,"0123456789.-");
}

function trapInvalidSignDecimalE(pEvent) {

   return trapInvalid(pEvent,"0123456789.-");
}

function trapInvalidSignDecimalF(pEvent) {

   return trapInvalid(pEvent,"0123456789,-");
}

function trapInvalidCurrency(pEvent) {

// Only used by AIR

   return trapInvalid(pEvent,"0123456789");
}

function trapInvalidSignCurrency(pEvent) {

// Only used by AIR

   return trapInvalid(pEvent,"0123456789-");
}

function trapInvalidCodeChar(pEvent) {

   return trapInvalid(pEvent,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,-&()' ");
}

function trapInvalidUserChar(pEvent) {

   return trapInvalid(pEvent,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-");
}

function trapInvalidPWChar(pEvent) {

   return trapInvalid(pEvent,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-#&?!@$%");
}

function firstFocus() {

// Move focus to focusable field of form with smallest positive tabIndex

   var form0 = document.frmEdit;
   if (!form0) {
//      alert("No form called frmEdit on page");
      return;
   }

//   displayFocuses();

   var numElements = form0.elements.length;
   if (numElements == 0) return;

   var elTabIndexSmallest;
   var tabIndexSmallest=99999;
   
   for (var i = 0; i<numElements; i++) {

      var elCur = form0.elements[i];

      if (IsFocusable(elCur)) {
         var tabIndexCur = tabIndex(elCur);
         if (tabIndexCur > 0  &&  tabIndexCur < tabIndexSmallest) {
            elTabIndexSmallest = elCur;
            tabIndexSmallest = tabIndexCur;
            //alert("Smallest tabindex is " + tabIndexCur + " for " + elCur.name);
         }
      }
   }
   if(tabIndexSmallest<99999) {
      elTabIndexSmallest.focus();
      elTabIndexSmallest.select();
   }
}

function displayFocuses() {

   var form0 = document.frmEdit;
   if (!form0) {
      alert("No form called frmEdit on page");
      return;
   }
   var numElements = form0.elements.length;
   var aList = "";

   for (var i=0; i<numElements; i++) {

      var elCur = form0.elements[i];

      aList += elCur.tagName + " " + elCur.name + "; "
   }
//   alert(aList);
}


function nextFocus(pElement) {

// Move focus to later focusable field of form with tabIndex same as this;
// or to first tabindex next larger than this, or to field with smallest positive tabIndex

//	if(IsIE() && IsWin()){
//		alert("Next focus with pElement = " + pElement.name);
//	}
	
   var form0 = document.frmEdit;
   if (!form0) {
      alert("No form called frmEdit on page");
      return;
   }
   var numElements = form0.elements.length;
   if (numElements == 0) return;

   var elTabIndexSmallest,elTabIndexNextLarger;
   var tabIndexSmallest=99999,tabIndexNextLarger=99999;
   
   var tabIndexBase = tabIndex(pElement);
   var aBaseElFound = false;
   var elNext=pElement;
   
   for (var i=0; i<numElements; i++) {

      var elCur = form0.elements[i];

      if (elCur===pElement) {
         aBaseElFound = true;
         for (var j=0; j<numElements; j++) {
            elNext = form0.elements[(i+j+1)%numElements];
            if (IsFocusable(elNext)) break;
         }
         continue;
      }
      
      if (IsFocusable(elCur)) {
         var tabIndexCur = tabIndex(elCur);
         if ( (tabIndexCur > tabIndexBase || (aBaseElFound  &&  tabIndexCur == tabIndexBase) )    &&  tabIndexCur < tabIndexNextLarger) {
            elTabIndexNextLarger = elCur;
            tabIndexNextLarger = tabIndexCur;
         }
         if (tabIndexCur > 0  &&  tabIndexCur < tabIndexSmallest) {
            elTabIndexSmallest = elCur;
            tabIndexSmallest = tabIndexCur;
         }
      }
   }
   elTarget = elNext;
   if (tabIndexBase > 0) {
      if (tabIndexNextLarger<99999) elTarget = elTabIndexNextLarger;
      else if (tabIndexSmallest<99999) elTarget = elTabIndexSmallest;
   }
   if(!elTarget || !IsFocusable(elTarget)) elTarget = pElement;
   	elTarget.focus();
   	elTarget.select();
   }

function addressMakeSame(pPrefix1,pPrefix2) {

// Make second address same as first

   for (var aI=0; aI<gAddrElements.length; aI++) {
      document.frmEdit.elements[pPrefix2 + gAddrElements[aI]].value = 
        document.frmEdit.elements[pPrefix1 + gAddrElements[aI]].value;
   }
}

function addressSameRadioSet(pMakeSame,pPrefix1,pPrefix2) {

// Process click on "AddressSame" radio
// (make second addr same as first addr before showing second)

   if (!pMakeSame) addressMakeSame(pPrefix1,pPrefix2);	

   blockDisplaySet(pPrefix2 + "Address", !pMakeSame);

}

function setDataConsentValues(pEl) {


// Set Data Consent checkboxes and show/hide the block containing them

	var aSelection = pEl.options[pEl.selectedIndex].value;
	var aChecked = (aSelection=="Unlimited") ? true : false;
	for(var aI=0; aI<pEl.form.elements.length; aI++) {
		var aEl = pEl.form.elements[aI];
		if(aEl.type == "checkbox" && aEl.name.substr(0,11)=="DataConsent") aEl.checked = aChecked;
	}
	blockDisplaySet("DataConsentParties", aSelection=="Limited");

}

function blockDisplaySet(pBlock, pShow) {

// Show or hide block based on pShow
	
	document.getElementById(pBlock).style.display = (pShow) ? "block" : "none" ;
}

function windowOnLoad(){
	return " 'onLoad= top.framesetInit();return true;'";
}

function windowUnload(pName){
  	
   if(IsIE()){
	   return  " 'onbeforeunload= top.closeFrameSet('" + pName + "');return true;'"
   }else{
       return  " 'onunload= top.closeFrameSet('" + pName + "');return true;'"
   }
}

function windowResize(){

	return " onresize='top.setWindowDimensions();return true;'"
}

function getFrameRows(pPosArray, aStartIndex){
	
	var aRows = "";
	
	if(pPosArray == null || aStartIndex > pPosArray.length){
		return "";
	}
	
	for(var aI = aStartIndex; aI < pPosArray.length ; aI++){
		if(aI > aStartIndex){
			aRows += " ," + pPosArray[aI];
	    }else{
			aRows += pPosArray[aI];
	    }
   }

   return aRows;
	
}

function setFilterSortPrefsFromCookie(pName){

// Set the user filter and sort preferences from the cookie data

	
	var cookie = getCookie(pName);
	var cookieData = cookie.split("&");
	var aPrefsArray = new Array(cookieData.length-1)

	for(var aI=0;aI<4;aI++){
	  var aElement = cookieData[aI].split("=");
	  var aName = aElement[0];
	  var aValue = aElement[1];

	  switch(aName) 
      {
		case "Show":
           aPrefsArray[0] = aValue;
	       break;
        case "ByDate":
           aPrefsArray[1] = aValue;
	       break;
        case "All":
	       aPrefsArray[2] = aValue;
	       break;
        case "Collapse":
           aPrefsArray[3] = aValue;
	       break;
        default:
           alert("Unrecognized position value");
       }
  
	}


	return aPrefsArray
		
}

function setWindowPositionFromCookie(pName){

// Set the frame positions based on the cookie data
 
   var aScrHeight = screen.height;
   var aScrWidth = screen.width;
   var cookie=getCookie(pName);
   var cookieData=cookie.split("&");
   var positionArray= new Array(cookieData.length-1)

   for(var aI=0;aI<4;aI++){
     var aElement = cookieData[aI].split("=");
     var aName = aElement[0];
     var aValue = aElement[1];

	 
     switch(aName) 
     {
		case "TopX":
		   if(aValue < 0)
		   {
				aValue = 0;
		   }
           positionArray[0] = aValue;
	       break;
        case "TopY":
		   if(aValue < 0)
		   {
				aValue = 0;
		   }
           positionArray[1] = aValue;
	       break;
        case "WinWidth":
		   if(IsIE()){
		      if( aValue > aScrWidth || aValue < 100){aValue = 300;}
		   }else{
			  if( aValue > aScrWidth || aValue < 0){aValue = 300;}
		   }
	       positionArray[2] = aValue;
	       break;
        case "WinHeight":
		   if(IsIE()){
		      if( aValue > aScrHeight || aValue < 100){aValue = aScrHeight;}
		   }else{
			  if( aValue > aScrHeight || aValue < 0){aValue = aScrHeight;}
		   }
           positionArray[3] = aValue;
	       break;
        default:
           alert("Unrecognized position value");
      }
  
   }

   if(cookieData.length-1 >= 4){

      for(aI=4;aI<cookieData.length-1;aI++){
			aElement = cookieData[aI].split("=");
			aName = aElement[0];
			aValue = aElement[1];

			if(aValue < 0){
				aValue = 0;
			}
	   
			positionArray[aI] = aValue;
		
      }
  }
	
  return positionArray;
}

function escapeSingleQuote(pText) {
	return pText.replace("'","/'");
}

function confirmDelete(pMessage,pOrigUrl,pTarUrl)
{
	if(confirm(pMessage))
	{
		window.location.href = pTarUrl;
		return true;
	}

	window.location.href = pOrigUrl;
	return false;
}

/* change to make generic, for CPISeries.asp */

function confirmSubmit()
{
	var aSelectedIndex = document.frmEdit.elements['BaseYears'].selectedIndex;
	var aMessage = EF('Are you sure you want to close the CPI Series for the year ' + 
		document.frmEdit.elements['BaseYears'].options[aSelectedIndex].value + '?','*F')
	
		if ( aSelectedIndex > 0){
			if(confirm(aMessage)){
				document.frmEdit.action = document.frmEdit.action + 'Op=EndSave';
				document.frmEdit.submit();
			}

			document.frmEdit.action = document.frmEdit.action + 'Op=End';
			  
		}else{
			alert(EF('Please choose a base year from the select box','*F'));
		}

}

function inspectionCheckboxToggle(pCheckBox)
// Toggle inspection check box, clearing others if this one set on
{
	var aChecked = pCheckBox.checked;
	if (aChecked){
		var aForm = pCheckBox.form;
		var aLastSplit = pCheckBox.id.lastIndexOf('_');
		var aListName = pCheckBox.id.substr(0,aLastSplit)
		
		for (var aI=0; ; aI++) {
			var aCheckbox = aForm.elements[aListName + '_' + aI];
			if (!aCheckbox) break;
			if (aCheckbox!==pCheckBox) aCheckbox.checked = false;
		}
	}
	return true;

}

function inspectionDisableControls(pCheckBox,pLineNumber)
// Disable "Health","Maintenance","ItemCost","Life" controls when "NA" or "NI" are clicked
{
	
	var aControlNameArray = new Array("Health","Maintenance","ItemCost","Life");
	var aRatingIndex = "";
	var aEl;
	var aIndexPos;
	
	for(var aI=0; aI<pCheckBox.form.elements.length; aI++) {
		aEl = pCheckBox.form.elements[aI];
		if (aEl.type == "checkbox")
		{
			aIndexPos = aEl.id.indexOf("Rating_" + pLineNumber,0)
			if (aIndexPos >= 0)
			{
				if (aEl.checked)
				{
					// Id constructed by .NET ends in _ followed by index of checkbox in ratings
					aRatingIndex = aEl.id.substr(aIndexPos + ("Rating_" + pLineNumber).length + 1)
					break;
				}
				
			}
		}
			
	}

	for(var aI=0; aI<pCheckBox.form.elements.length; aI++) {
		aEl = pCheckBox.form.elements[aI];
		if (aEl.type == "checkbox" || aEl.type == "text")
		{
			for (var aJ=0; aJ<aControlNameArray.length; aJ++ )
			{
				aIndexPos = aEl.id.indexOf(aControlNameArray[aJ] + "_" + pLineNumber,0)
				if (aIndexPos >= 0)
				{
					aEl.disabled = (aRatingIndex == "0" || aRatingIndex == "1");
					//If there is a span surrounding the checkbox list (generated by ASPNET) set its disabled attibute
					var aParent = aEl.parentNode;
					if (aParent && aParent.nodeType == 1 && aParent.tagName == "SPAN")
					{
						aParent.disabled = aEl.disabled; 
					}
				}
			}
		}
	}
		
	return true;
}

function addSelectOption(pSelectObjectName,pOpText,pOpValue,pbDefaultSelected,pbSelected)
// Appends a new option add the end of the select object option array
{
	var aSelectObject = document.getElementById(pSelectObjectName);
	
	aSelectObject.options[aSelectObject.options.length] = new Option(pOpText, pOpValue);

}

function clearSelectOptions(pSelectObjectName)
// Clears all option items in the select object
{
	var aSelectObject = document.getElementById(pSelectObjectName);

	aSelectObject.options.length = 0;
}

 function sFormatCurrency(pValue) {
   var aValue = sUnformatNumber(pValue)
   var aSep = (gLanguage=="E") ? "," : " ";

   if (isNaN(aValue))
      aValue = "0";
      sign = (aValue == (aValue = Math.abs(aValue)));
      aValue = Math.floor(aValue*100+0.50000000001);
      cents = aValue%100;
      aValue = Math.floor(aValue/100).toString();

   if (cents < 10)
      cents = "0" + cents;
      for (var i = 0; i < Math.floor((aValue.length-(1+i))/3); i++)
         aValue = aValue.substring(0,aValue.length-(4*i+3)) + aSep +
         aValue.substring(aValue.length-(4*i+3));
         
   if (gLanguage=="E") {
      aValue = (((sign)?'':'-') + '$' + aValue + '.' + cents);
      }
   else {
      aValue = (((sign)?'':'-') + aValue + ',' + cents + '$');
      }
   
   return aValue;
}

// Windowing Routines
function openFullWindow(url, name, options) {
	var WindowTopX = 10;  
	var WindowTopY = 10;
   var height = screen.availHeight;
   var width = screen.availWidth;
   var settings = 'height=' + (height - (WindowTopY * 2) - 70) + ',' ;
   settings += 'width=' + (width - (WindowTopX * 2) - 10) + ',' ;
   settings += 'top=' + WindowTopY + ',' ;
   settings += 'left=' + WindowTopX ;
   if (options.length > 0) {
      settings += ',' + options;
      }
   win = window.open(url, name, settings);
   win.window.focus();
}

function openWindow(url, name, w, h, options) {
   if (screen.width){
      var winl = (screen.width-w)/2;
      var wint = (screen.height-h)/2;
      }
   else {
      winl = 0;wint =0;
      }
   
   if (winl < 0) winl = 0;
   if (wint < 0) wint = 0;
   
   var settings = 'height=' + h + ',';
   settings += 'width=' + w + ',';
   settings += 'top=' + wint + ',';
   settings += 'left=' + winl ;
   if (options.length > 0) {
      settings += ',' + options;
      }
   win = window.open(url, name, settings);
   win.window.focus();
}

/*==================================================*/

/** START: Methods to create, retrieve and delete cookies **/

/*--------------------------------------------------*/


function getCookie(pName){

// Gets the value of the specified cookie
/**
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist or if the cookie does not have the right number of arguements.
 *
 */
 
   var aArg = pName + "=";
   var aAlen = aArg.length;

   if(aAlen < 18)
   {
	   return null;
   }

   var aClen = document.cookie.length;
   var aI = 0;
   while (aI < aClen) {
     var aJ = aI + aAlen;
     if (document.cookie.substring(aI, aJ) == aArg){
       var aValue = getCookieVal(aJ);
		 if(aValue < 0)
	     {
			 return null;
		 }
	   return aValue;
     }
     aI = document.cookie.indexOf(" ", aI) + 1;
     if (aI == 0) break;
   }

   return null;
}

function getCookieVal (pOffset) {

// Returns the value of a cookie element
	
   var aEndstr = document.cookie.indexOf (";", pOffset);
   if (aEndstr == -1)
   aEndstr = document.cookie.length;
   return unescape(document.cookie.substring(pOffset, aEndstr));
}

/** END: Methods to create, retrieve and delete cookies **/
