// *****************************************************************************+
// *           Copyright © 1999-2006 EMC Corporation.                           *
// *                          All Rights Reserved.                              *
// *                                                                            *
// *  This document contains copyrighted and/or trade secret and confidential   *
// *  information which is the property of EMC Corporation.  No part of  *
// *  this document may be reproduced, copied, disclosed, transmitted, stored   *
// *  in a retrieval system or translated into any human or computer language,  *
// *  in any form, by any means, in whole or in part, without the prior express *
// *  written consent of EMC Corporation.                                       *
// *                                                                            *
// ******************************************************************************
//
//   Filename:       ClientScript.js
//   Created:        11/01/99
//   Author:         Neal Finnegan
//   Description:    Script to handle client side events
//---------------------------------------------------------

// Globals
var gFocusControl;
var pageModTag;
var TCAPageType;
var IsExecutingOnPage;
var gErrorWindowName;
var IsIE, IsNS, MapObj, IsIEMac;
var IsMeetingSharePane = false;
var IsEntDBSummaryPage = false;
var isVersionedFilePage = false;
var IsMeetingsListPage = false;
var IsMeetingKeepAlive = false;
var IsProjectPlanSummaryPage = false;
var FacilitySearchPage = 1;
var RoomSearchPage = 2;
var CalendarPage = 37;
var ServerSettingsPage = 3;
var CommunitySettingsPage  =4;
var FacilitySettingsPage = 5;
var RoomSettingsPageFromRoom = 6;
var RoomSettingsPageFromFacility = 7;
var SiteSearchPage = 20;

var ERUPage = 0;
var HasCoordinatorRights = false;
var CanDeleteItemsPermanently = false;
var gDefaultButton = "";
var gAllowButtonMouseOut = true;
var showCustomFields = false;
var showPublishToDocumentum = true;
var showGoToDocumentum = true;
var bIsObserver = false;
var isDiscussionPage = false;
var	IsSingleConnectedSet = false;
var CanAddTo = false;
var IsUsingRTMeetingServer = false;
var gUseEnhanced = false;

var version = parseInt(navigator.appVersion)
var ERPageAddInCtrl;
var saveAction;
var pageType = "Standard"
var pageSubType = "None"
var repErrInit = false;
var bScrollToFirstUnread = false;
var allcookies;
var menuItem = null;
var MenuOnDisplay = false;
var LaunchedFile = false;
var bBodyFormCheckAll = true;
var bItemsCheckAll = true;
var RoomDocID = ""

var visible;
var hidden;
var nsMenuLayerMap;
var client;
var gClickInMap = false;

var gSubmitHandlers = new Array();
var gInitHandlers = new Array();
var gClientSideVerify = new Array();

// when converted through COM to VB, the all group ID becomes this value
// we never automatically check the all group, so we skip it in BodyFormCheckAll()
// FIXME:  This should be passed in somehow and it is per community
var kAllGroupID = "-2050";

var gFacilityURL;
var gRoomURL;
var gPageURL;
var gDialogRoot;
var gUserHasAuthenticated;
var gErrorTitle;
var gErrorMessage;
var UsePlugin;
var gServerVersion;
var gMinPluginVersion;
var gURLPrefix;
var ShowInstallDlg = false;
var GoDirectlyToInstallDlg = false;

// client site cookie support
var gCookieName
var gSessionCookieName

var gClientChoiceCookieFieldName
var gRefreshPageCookieFieldName
var gShowErrorPopUpCookieFieldName
var gPageModTagCookieFieldName

//var gLoggedInUserIMClient;

var monthsOfYear;
var daysOfWeek;
var sDateFormat;

var gCannotReadCookiesStr
var gMSNNotInstalledErrStr;
var gNeedPluginForIMErrStr;
var gIMNotLoggedInErrStr;
var gSelectItemsFromSameRoomForSearchErrStr;
var gYou_must_supply_a_filenameStr;
var gYou_must_supply_a_file_typeStr;

// these two vars hold the name representing the firstname; could be "firstName" or "lastName"
// they are set in ClientDynamic
var gFirstName
var gLastName

// Initialization functions
	if (navigator.appName == "Netscape") 
	{
		IsNS = true;
	} 
	else 
	{
		IsIE = true;

		// IE 5 reports as 4.0 but it has a 5. later in the version string
		// use 5. so 5.5 matches (same for IE 6.0)
		if ((navigator.appVersion.indexOf("5.") != -1) ||
			(navigator.appVersion.indexOf("6.") != -1))
		{
			version = 5;
		}
	}

// Menu display variables
	eRoomMenuName = "erMenu";

	// MenuWidth now set via eRoom.css, or an overriding localized version
	MenuBorderColor = "black";
	MenuBorderMargin = 1;
	MenuBgColor = "#A8C0F0";
	MenuSelectedItemColor = "#7A96CC";
	MenuFntCol = "black";
	MenuFntDisabledCol = "gray";
	MenuFntFam = "Trebuchet MS";
	MenuFntSiz = "11px";  
	MenuOverFnt = "white";
	MenuOverValidItem = false;

	ItemHeightNS = 17;

	itemPad = 0;  

	// Menu types
	var BackGroundMenu = "A";
	var ItemMenu = "B";
	var FileMenu = "C";
	var VersionedFileMenu = "D";
	var CompanionFileMenu = "E";
	var VersionedCompanionFileMenu = "F";
	var NewWindowLinkMenu = "G";
	var DBRowMenu = "H";
	var RecycleBinMenu = "I"; // for the recycle bin itself
	var RecycleBinItemMenu = "J"; // for items in the recycle bin
	var BlueRoomArrowMenu = "K";
	var MapVersionedFileMenu = "L";
	var MeetingShareFileMenu = "M";
	var MeetingsListPageMenu = "N";
	var WorkflowPhaseMenu = "O";
	var CalendarItemMenu = "P";
	var MeetingSharePresentFileMenu = "Q";
	var ApprovalProcessItemMenu = "R";
	var DMFileMenu = "Z";
	var EntDBInTemplateFolderMenu = "a";
	var APDBInTemplateFolderMenu = "b";		
	var CalendarEventMenu = "c";
	
	// versions of file related menus with Preview
	var FileMenu_Preview = "S";
	var VersionedFileMenu_Preview = "T";
	var CompanionFileMenu_Preview = "U";
	var VersionedCompanionFileMenu_Preview = "V";
	var MapVersionedFileMenu_Preview = "W";
	var MeetingShareFileMenu_Preview = "X";
	var MeetingSharePresentFileMenu_Preview = "Y";
	var DMFileMenu_Preview = "d"

	var IMMenu="e";
	var IMMenuNoIM="f";
	var IMMenuNoEmail="g";
	var IMMenuMemberInfoOnly="h";
	var IMMenuNoMemberInfo="i";
	var IMMenuIMOnly="j";
	var IMMenuEmailOnly="k";
	
	var RMFileHistoryItemMenu = "l";
	var VersionedRMProtectedItemMenu = "m";

	var menu_idx = 0;

	// the order defined here determines the order displayed in pop-up menu
	var PreviewItem = menu_idx++;
	var ViewItem = menu_idx++;
	var RoomEdit = menu_idx++;
	var EditItem = menu_idx++;
	var ViewFileItem = menu_idx++;
	var EditFileItem = menu_idx++;
	var RenameItem = menu_idx++;
	var CutItem = menu_idx++;
	var CopyItem = menu_idx++;
	var CopyLinkToItem = menu_idx++;
	var PasteItem = menu_idx++;
	var DeleteItem = menu_idx++;
	var EnterMeeting = menu_idx++;
	var ShareFile = menu_idx++;
	var MarkItemRead = menu_idx++;
	var MarkItemUnread = menu_idx++;
	var TrackVersions = menu_idx++;
	var ShowVersions = menu_idx++;
	var RMFileHistory = menu_idx++;
	var AccessControl = menu_idx++;
	var Notification = menu_idx++;
	var CustomFields = menu_idx++;
	var SharePaneFileIntoMeetingPresent = menu_idx++;
	var SharePaneFileIntoMeetingView = menu_idx++;
	var SharePaneFileIntoMeetingEdit = menu_idx++;
	var PublishToDocumentum = menu_idx++;
	var GoToDmProperties = menu_idx++;
	var GoToDocumentum = menu_idx++;
	var AddTopic = menu_idx++;
	var CreateItem = menu_idx++;
	var AddFile = menu_idx++;
	var SaveSettings = menu_idx++;
	var CreateEvent = menu_idx++;
	var EmptyRecycleBin = menu_idx++;
	var CreateStep = menu_idx++;
	var Restore = menu_idx++;
	var EmailMember = menu_idx++;
	var IMMember = menu_idx++;
	var ViewMember = menu_idx++;
		
	// leave this one at the end
	var NumMenuItems = menu_idx++;

	// Array of menu items command and display string mappings
	var MenuChoicesArray = new Array();
	var MenuArray = new Array();
	
	// display strings, set with "disp" field, are now set in ClientDynamic.asp
	MenuArray [PreviewItem] = { com:"PreviewItem", disp:"" }
	MenuArray [ViewItem] = { com:"ViewItem", disp: "" }
	MenuArray [RoomEdit] = { com:"RoomEdit", disp:"" }
	MenuArray [EditItem] = { com:"EditItem", disp:"" }
	MenuArray [ViewFileItem] = { com:"ViewFileItem", disp:"" }
	MenuArray [EditFileItem] = { com:"EditFileItem", disp:"" }
	MenuArray [RenameItem] = { com:"RenameItem", disp:"" }
	MenuArray [CutItem] = { com:"CutItem", disp:"" }
	MenuArray [CopyItem] = { com:"CopyItem", disp:"" }
	MenuArray [CopyLinkToItem] = { com:"CopyLinkToItem", disp:"" }
	MenuArray [PasteItem] = { com:"PasteItem", disp:"" }
	MenuArray [DeleteItem] = { com:"DeleteItem", disp:"" }
	MenuArray [EnterMeeting] = { com:"EnterMeeting", disp:"" }
	MenuArray [ShareFile] = { com:"ShareFile", disp:"" }
	MenuArray [MarkItemUnread] = { com:"MarkItemUnread", disp:"" }
	MenuArray [MarkItemRead] = { com:"MarkItemRead", disp:"" }
	MenuArray [TrackVersions] = { com:"TrackVersions", disp:"" }
	MenuArray [ShowVersions] = { com:"ShowVersions", disp:"" }
	MenuArray [AccessControl] = { com:"AccessControl", disp:"" }
	MenuArray [Notification] = { com:"Notification", disp:"" }
	MenuArray [CustomFields] = { com:"CustomFields", disp:"" }
	MenuArray [PublishToDocumentum] = { com:"PublishToDocumentum", disp:"" }
	MenuArray [GoToDmProperties] = { com:"GoToDmProperties", disp:"" }
	MenuArray [GoToDocumentum] = { com:"GoToDocumentum", disp:"" }
	MenuArray [AddTopic] = { com:"AddTopic", disp:"" }
	MenuArray [CreateItem] = { com:"CreateItem", disp:"" }
	MenuArray [AddFile] = { com:"AddFile", disp:"" }
	MenuArray [SaveSettings] = { com:"SaveSettings", disp:"" }
	MenuArray [SharePaneFileIntoMeetingPresent] = { com:"PresentShareFileItem", disp:"" }
	MenuArray [SharePaneFileIntoMeetingView] = { com:"ViewShareFileItem", disp:"" }
	MenuArray [SharePaneFileIntoMeetingEdit] = { com:"EditShareFileItem", disp:"" }
	MenuArray [CreateEvent] = { com:"CreateEvent", disp:"" }
	MenuArray [EmptyRecycleBin] = { com:"EmptyRecycleBin", disp:"" }
	MenuArray [CreateStep] = { com:"CreateStep", disp:"" }
	MenuArray [Restore] = { com:"Restore", disp:"" }
	MenuArray [EmailMember] = { com:"LINK:2", disp:"" }
	MenuArray [IMMember] = { com:"3", disp:"" }
	MenuArray [ViewMember] = { com:"LINK:1", disp:"" }
	MenuArray [RMFileHistory] = { com:"RMFileHistory", disp:"" }

// Netscape and Mozilla should not use evt.clientX and evt.clientY because they do not return values
// relative to the web browser page, so scrolling and right-clicking would be broken (bugs 35433 and 35643)
function GetBrowserX(evt)
{
	if (navigator.appName == "Netscape")
		return evt.pageX;
	else
		return evt.clientX;
}

function GetBrowserY(evt)
{
	if (navigator.appName == "Netscape")
		return evt.pageY;
	else
		return evt.clientY;
}

//**************************MouseMenu.asp**************************************
// Mouse Menu functions
	// Setup the display arrays based on the menu to display and the page settings
	function SetupItemMenuChoices(menuID, InMap, bHasPreview, menuItem) 
	{
		// Initialize the arrays based on the page settings
		SetupPageMenuChoices(menuID, InMap);
		var i;
		
		MenuChoicesArray [PreviewItem] = false;
		MenuChoicesArray [CreateStep] = false;
		
		if (menuID == RecycleBinMenu)
		{
			for (i = 0; i < NumMenuItems; i++)
			{
				if (i != ViewItem && i != AccessControl && i != EmptyRecycleBin)
				{
					MenuChoicesArray [i] = false;
				}
			}
		}
		else if (menuID == BlueRoomArrowMenu)
		{
			// View: same as clicking
			// Edit: same as the Edit button at the top of the front page
			// Paste, Mark Read: same as the corresponding buttons on the front page's item box with no items selected
			// Access Control, Notification: bring up the existing access control and notification dialogs for the front page.

			// Turn off all between EditItem and before PasteItem
			for (i = EditItem; i < PasteItem; i++) {
				MenuChoicesArray [i] = false;
			}

			// Turn off all between PasteItem+1 and before MarkItemRead
			for (i = PasteItem+1; i < MarkItemRead; i++) {
				MenuChoicesArray [i] = false;
			}

			// Turn off all between MarkItemRead+1 and before AccessControl
			for (i = MarkItemRead+1; i < AccessControl; i++) {
				MenuChoicesArray [i] = false;
			}

			// Turn off all between Notification+1 and before end
			for (i = Notification+1; i < NumMenuItems; i++) {
				MenuChoicesArray [i] = false;
			}
		}
		else if (menuID == BackGroundMenu)
		{
			// Turn off all choices before paste
			for (i = 0; i < PasteItem; i++) {
				MenuChoicesArray [i] = false;
			}
			// Turn off all choices between Delete and AddTopic
			for (i = DeleteItem; i < AddTopic; i++) {
				MenuChoicesArray [i] = false;
			}

			// Calendars can't create files.
			if (pageType == "Calendar")
			{
				MenuChoicesArray [CreateItem] = false;
				MenuChoicesArray [AddFile] = false;

				// Turn off remaining choices between EmptyRecycleBin and end
				for (i = EmptyRecycleBin; i < NumMenuItems; i++) {
					MenuChoicesArray [i] = false;
				}
			}
			else
			{
				// Turn off remaining choices between CreateEvent and end
				for (i = CreateEvent; i < NumMenuItems; i++) {
					MenuChoicesArray [i] = false;
				}
			}

			if (pageType == "Workflow")
			{
				MenuChoicesArray [CreateStep] = true;
				MenuChoicesArray [CreateItem] = false;
				MenuChoicesArray [AddFile] = false;
			}
		}
		else if(menuID>=IMMenu && menuID<=IMMenuEmailOnly)
		{
			// turn off everything before email member
			for (i = 1; i < EmailMember; i++) {
				MenuChoicesArray [i] = false;
			}

			// turn off everything after what we care about
			for (i = ViewMember+1; i < NumMenuItems; i++) {
				MenuChoicesArray [i] = false;
			}

			// customize which items are visible
			if (menuID == IMMenuNoIM)
			{
				MenuChoicesArray [IMMember] = false;
			}
			else if (menuID == IMMenuNoEmail)
			{
				MenuChoicesArray [EmailMember] = false;
			}
			else if (menuID == IMMenuMemberInfoOnly)
			{
				MenuChoicesArray [IMMember] = false;
				MenuChoicesArray [EmailMember] = false;
			}
			else if (menuID == IMMenuNoMemberInfo)
			{
				MenuChoicesArray [ViewMember] = false;
			}
			else if (menuID == IMMenuIMOnly)
			{
				MenuChoicesArray [EmailMember] = false;
				MenuChoicesArray [ViewMember] = false;
			}
			else if (menuID == IMMenuEmailOnly)
			{
				MenuChoicesArray [IMMember] = false;
				MenuChoicesArray [ViewMember] = false;
			}
		}
		else 
		{
			// Turn off all choices after AddTopic
			for (i = AddTopic; i < NumMenuItems; i++) {
				MenuChoicesArray [i] = false;
			}

			// For non Files turn off track versions and use the normal
			// view and edit
			if ((menuID == ItemMenu) || (menuID == NewWindowLinkMenu) || 
				(menuID == WorkflowPhaseMenu) || (menuID == CalendarItemMenu) ||
				(menuID == EntDBInTemplateFolderMenu || menuID == APDBInTemplateFolderMenu) ||
				(menuID == CalendarEventMenu))
			{
				MenuChoicesArray [TrackVersions] = false;
				MenuChoicesArray [ViewFileItem] = false;
				MenuChoicesArray [EditFileItem] = false;
				MenuChoicesArray [ShareFile] = false;
				MenuChoicesArray [PublishToDocumentum] = false;

				if (menuID == WorkflowPhaseMenu)
				{	// can't cut or copy phases
					MenuChoicesArray[CopyItem] = false;
					MenuChoicesArray[CutItem] = false;
				}
			}
			else if (menuID == ApprovalProcessItemMenu || menuID == APDBInTemplateFolderMenu)
			{
				MenuChoicesArray [TrackVersions] = false;
				MenuChoicesArray [ViewFileItem] = false;
				MenuChoicesArray [EditFileItem] = false;
				MenuChoicesArray [ShareFile] = false;
				MenuChoicesArray [PasteItem] = false;
				MenuChoicesArray [PublishToDocumentum] = false;
			}
			else if (menuID == DBRowMenu)
			{
				MenuChoicesArray [TrackVersions] = false;
				MenuChoicesArray [ViewFileItem] = false;
				MenuChoicesArray [EditFileItem] = false;
				MenuChoicesArray [RenameItem] = true;
				MenuChoicesArray [CustomFields] = false;
				MenuChoicesArray [ShareFile] = false;
				MenuChoicesArray [PublishToDocumentum] = false;
				if (IsEntDBSummaryPage)
				{
					MenuChoicesArray[MarkItemRead] = false;
					MenuChoicesArray[MarkItemUnread] = false;
				}
				if (IsProjectPlanSummaryPage)
				{
					MenuChoicesArray[AccessControl] = false;
				}
			}
			else if ((menuID == MeetingShareFileMenu) || (menuID == MeetingSharePresentFileMenu))
			{
				// Turn off all choices first
				for (i = 0; i < NumMenuItems; i++) {
					MenuChoicesArray [i] = false;
				}

				// now turn on just these two
				MenuChoicesArray [SharePaneFileIntoMeetingView] = true;
				MenuChoicesArray [SharePaneFileIntoMeetingEdit] = true;
				// If this is a convertable 
				if (menuID == MeetingSharePresentFileMenu)
					MenuChoicesArray [SharePaneFileIntoMeetingPresent] = true;
			}
			else if (menuID == MeetingsListPageMenu)
			{
				MenuChoicesArray [CutItem] = false;
				MenuChoicesArray [ShareFile] = false;
				MenuChoicesArray [TrackVersions] = false;
				MenuChoicesArray [ViewFileItem] = false;
				MenuChoicesArray [EditFileItem] = false;
				MenuChoicesArray [PublishToDocumentum] = false;
			}
			else if (menuID == RecycleBinItemMenu)
			{
				for (i = 0; i < NumMenuItems; i++)
					MenuChoicesArray [i] = (i == CopyItem || ((i == DeleteItem) && CanDeleteItemsPermanently) || i == Restore );
			}
			else
			{
				// For files use the file view and edit
				MenuChoicesArray [ViewItem] = false;
				MenuChoicesArray [EditItem] = false;

				MenuChoicesArray [PreviewItem] = bHasPreview;
				
				if (menuID == RMFileHistoryItemMenu)
				{
					MenuChoicesArray[RMFileHistory] = false;
					MenuChoicesArray [PublishToDocumentum] = false;
				}

				if (menuID == DMFileMenu)
					MenuChoicesArray [TrackVersions] = false;
					
				if (menuID == VersionedRMProtectedItemMenu)
				{
					MenuChoicesArray[RMFileHistory] = false;	
					MenuChoicesArray [PublishToDocumentum] = false;
				}
			}

			// Go To Documentum is only valid for DM linked files
			if (menuID != DMFileMenu)
			{
				MenuChoicesArray [GoToDocumentum] = false;
				MenuChoicesArray [GoToDmProperties] = false;
			}
			

			if ((menuID != RMFileHistoryItemMenu) &&
				(menuID != VersionedRMProtectedItemMenu))
			{
				MenuChoicesArray[RMFileHistory] = false;
			}

			// For non versioned Files turn off show versions
			if ((menuID != VersionedFileMenu) && 
				(menuID != VersionedCompanionFileMenu) &&
				(menuID != VersionedRMProtectedItemMenu))
				MenuChoicesArray [ShowVersions] = false;

			// For non share pane files, turn off share pane file choices
			if ((menuID != MeetingShareFileMenu) && (menuID != MeetingSharePresentFileMenu))
			{
				MenuChoicesArray [SharePaneFileIntoMeetingView] = false;
				MenuChoicesArray [SharePaneFileIntoMeetingEdit] = false;
			}
			if (menuID != MeetingSharePresentFileMenu)
			{
				MenuChoicesArray [SharePaneFileIntoMeetingPresent] = false;
			}

			// if not on the meetings and events page, EnterMeeting is false
			if (menuID != MeetingsListPageMenu && menuID != CalendarItemMenu)
			{
				MenuChoicesArray [EnterMeeting] = false;
			}
			
			// not BlueRoomArrowMenu
			MenuChoicesArray [RoomEdit] = false;

		}
	}

	// Display the menu at the XY coordinates
	function DisplayMenuXY (evt, x, y, iMenuItem)
	{
		var InMap = false;
		RoomDocID = "";
		// Get the item at the XY position (if present)
		if (iMenuItem)
			menuItem = iMenuItem
		else
			menuItem = GetSelectedElemAtPoint(x, y, true)
			
		// Get the type of menu to display
		var menuId = BackGroundMenu;

		if (IsBlueRoomArrow(evt) || (iMenuItem != undefined && iMenuItem.name != undefined && IsBlueRoomArrowName(iMenuItem.name)))
		{
			menuId = BlueRoomArrowMenu;
			InMap = true;
		}
		else if (menuItem)
		{
			if (menuItem.name == undefined)
			// no menu to display.  this happens in IE when right-clicking on
			// item text in details view
				return false;
			
			menuId = menuItem.name.charAt(0);
			InMap = IsInMap (x,y);

			if (IsMeetingSharePane)
			{
				menuId = MeetingShareFileMenu;
				if (CanPresent(menuItem.name))
					menuId = MeetingSharePresentFileMenu;
			}

			if (IsMeetingsListPage && !InMap)
			{
				menuId = MeetingsListPageMenu;
			}
		}

		if ((menuId == RecycleBinMenu && !HasCoordinatorRights) ||
			(menuId == RecycleBinItemMenu && bIsObserver) ||
			(menuId == BackGroundMenu && bIsObserver))
		{
			// there is no menu to display
			MenuOnDisplay = false;
			return false;
		}

		var bHasPreview = false;

		if(menuItem)
			bHasPreview=HasPreview(menuItem.name);

		// Setup the menu choices
		SetupItemMenuChoices(menuId, InMap, bHasPreview, menuItem);

		if (InMap && menuId == VersionedFileMenu)
			menuId = MapVersionedFileMenu;

		// Display the menu
		popUpXY(menuId, x, y, InMap, bHasPreview);

		if (!isLoaded)
			MenuOnDisplay = false;
			
		return true;
	}

	// Display the menu at the coordindates in the event
	function DisplayMenu(evt) 
	{
		DisplayMenuXY (evt, GetBrowserX(evt), GetBrowserY(evt));
		EventStopPropagation( evt );
	}

	function GetFacilityURLNameFromID(theID)
	{
		var retVal = "";
		// get rid of the menu prefix, first
		retVal = theID.substr( 3, theID.length);
		var pos;

		pos = retVal.indexOf("/");
		if (pos !=  -1)
		{
			retVal = retVal.substr(0, pos);
		}
		else
			retVal = "";

		return retVal;
	}

	function RemoveFacilityURLNameFromID(theID)
	{
		var pos;
		var retVal = "";

		pos = theID.indexOf("/");
		if (pos !=  -1)
		{
			var menuPrefix = GetMenuPrefixFromID(theID);
			retVal = theID.substr(pos+1, theID.length);
			retVal = menuPrefix + retVal;
		}
		else
		{
			retVal = theID;
		}

		return retVal;
	}

	function GetMenuPrefixFromID(theID)
	{
		var thePrefix;
		if (theID.length > 6)
			thePrefix = theID.substr( 0, 3);

		return thePrefix;
	}

	// Execute the command from the menu
	function ExecuteCommand(sVerb) 
	{
		if (IsMeetingSharePane)
		{
			if (!UsePlugin)
			{
				return false;
			}

			if (!TestShareFile(sVerb == "PresentShareFileItem"))
				return false;
		}

		var item = ""
		var name = ""
		var path = ""

		// Get the item id from the name - include the initial A since an item name
		// can not begin with a number
		var fBrowserOffline = false;
		if (IsIE && !navigator.onLine)
			fBrowserOffline = true;

		var menuId;
		
		if (menuItem)
		{
			item = menuItem.name.substr (2);
			if (IsIE)
				path = menuItem.parentElement.href;
			name = menuItem.name;
			
			menuId = menuItem.name.charAt(0);
		}

		if ((menuId == EntDBInTemplateFolderMenu || 
			menuId == APDBInTemplateFolderMenu) &&
			sVerb == "ViewItem")
		{	// the edit item command should do a view item instead
			sVerb = "EditItem"
		}
		
		hideAll();
		
		if (fBrowserOffline && sVerb == "ViewItem")
		{
			document.location = path;
			return false;
		}

		// Uploading a Presentation is done by a popup window
		if (sVerb == "PresentShareFileItem")
		{
			UploadPresention(name.substr (3));
			return false;
		}

		// Let the browser display files when not using the plug-in and on the site search
		// page, in order to resolve back button issues
		if (!UsePlugin && TCAPageType == SiteSearchPage && sVerb == "ViewFileItem")
		{
			restoreSelectedDisplay(menuItem);
			if (!IsIE)
			{	
				return SiteSearchViewFile( name.substr(3) );
			}
			else
			{
				document.location = path;
				return false;
			}
		}

		// Give the control a chance to process the menu choice first
		var iRes = 1;
	
		if (UsePlugin)
		{
			var sMenuObjIDs = name;
			if ((sVerb == "CopyItem") || (sVerb == "CutItem"))
				sMenuObjIDs = GetSelectedItems(name, "Items");
				
			if ( ! ContainsMultipleIDs( sMenuObjIDs ) )
			{
				var FacilityURLName = "";
				FacilityURLName = GetFacilityURLNameFromID(sMenuObjIDs);
				var ServerPrefix = "";
				if (FacilityURLName.length > 0)
				{
					sMenuObjIDs = RemoveFacilityURLNameFromID( sMenuObjIDs );
					ServerPrefix = eval("document.Items." + FacilityURLName + ".value;");
				}
			}
		
			iRes = ERPageAddInCtrl.ExecuteVerb (sVerb, ServerPrefix, FacilityURLName, sMenuObjIDs, path, fBrowserOffline);
		}

		// The control was not present or it did not process the command - redirect
		// to command.asp
		if ((iRes == 1) || (iRes == 2))
		{
			if (IsNS)
				document.Items.action = saveAction;
			OnERFormSubmit()
			var selitem = "";
			if (menuItem)
				selitem = item.substr(1);

			if (RoomDocID.length)
			{
				// the context menu is over the blue arrow next to the room name in the map.  Use the room's doc ID
				selitem = RoomDocID;
			}

			if (sVerb == "EditItem" || sVerb == "CreateItem")
			{
				launchDialogInPlace( AppendCommand(document.Items.action, sVerb, "", "", "", selitem, document.Items.SessionKey.value) );
			}
			else if (sVerb == "CreateEvent")
			{
				// To make sure 28193 and 22542 both stay fixed, always use client 
				// coordinates for calls to GetBackgroundElemAtPoint
				SubmitCommand("MouseCommands", sVerb, "", GetBackgroundElemAtPoint(xClient,yClient), "", "")
			}
			else if (pageType == "Calendar" && sVerb == "PasteItem" && GetBackgroundElemAtPoint(xClient,yClient).length)
			{
				// Paste a copied or cut calendar event into another date cell on the same calendar page.
				SubmitCommand("MouseCommands", sVerb, "", GetBackgroundElemAtPoint(xClient,yClient), "", "")
			}
			else
			{
				var theForm, theFormName;
				
				if (gClickInMap)
					theFormName = "Map";
				else
					theFormName = "Items";

				theForm = eval("document." + theFormName);
									
				if (iRes == 2) // then we want to view the file.  overwrite the verb.
					sVerb = "ViewFileItem";
					
				if (IsIE)
					saveAction = theForm.action;

				SubmitCommand(theFormName, sVerb, "", "", "", selitem)
							
				if (IsIE && !IsIEMac)  // restore (early?) causes wrong action in submit (above!)
					theForm.action = saveAction;
			}
		}
		else
		{
			if (menuItem)
				restoreSelectedDisplay (menuItem)

			// For viewing of files - refresh the page to make sure the unread 
			// marks are cleared.  For editing, do NOT refresh because the edit
			// completion wants to refresh the window and refreshing will change
			// the window handle.
			if ( (sVerb == "ViewFileItem") && (iRes != 3))
				location.replace(location.href);
		}
	}

//**************************ClientScript.asp**************************************
// Basic functions

//  Assign event handlers for both NS and IE
function ERInitScript ()
{
	ERClickInit();

	if (IsNS) 
	{
		document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
	}

	initVars();
	
	document.onmousedown = OnMouseDown;
	document.onmousemove = OnMouseMove;
	document.onmouseup = OnMouseUp;
	document.onclick = OnClick;
}


//  Client-side utility for getting cookie field value.
//  All cookies field values that are read by client
//  script should be done so using this utility.

function GetCookieValue (cookie, field)
{
	// reinitialize allcookies, in case someone has called this before
	allcookies = document.cookie;  //  in function GetCookieValue
	var cookieFindString = cookie.toLowerCase();
	var allcookiesFindString = allcookies.toLowerCase();
	var Value = "";
	var pos=allcookiesFindString.indexOf(cookieFindString + "=");
	var lowerField = field.toLowerCase();

	if (pos != -1)
	{
		var start = pos + cookie.length + 1;
		var end = allcookiesFindString.indexOf(";", start);
		if (end == -1)
			end = allcookies.length;
		var value = allcookies.substring (start, end);
		value = value.toLowerCase();
		pos=value.indexOf(lowerField + "=");
		if (pos != -1)
		{
			start = pos + lowerField.length + 1;
			end = value.indexOf("&", start);
			if (end == -1)
			{
				end = value.length;
			}
			Value = value.substring (start, end);
		}
	}

    //like the mmt, the InstallRedirect is encoded because of possible special chars in the URLs
	if ((field == "MMT" || field == "IRD") && Value.length)
	{
		// We need to  base32 decode this value.
		// It was base32 encoded since it contains user data and could
		// have spaces and other special chars
		Value = Base32ToText(Value).m_str;
	}
	return Value;
}

// Check if ClearTrust (RSA) authentication is enabled for this location.

function IsClearTrustPresent()
{
	var cookies = document.cookie;
	if (cookies.indexOf("CTSESSION=") == 0 || cookies.indexOf("; CTSESSION=") > 0)
		return true;
	return false;
}

//  Convert input text string to base32 string

function TextToBase32(text)
{
    var result = new String;

    var cA = 'A'.charCodeAt();
    var c2 = '2'.charCodeAt() - 26;

    var bits    = 0;
    var numbits = 0;
    var code;
    var i;
    var shift;
    var input = new String(text);

    for ( i = 0 ; i < input.length ; i++ )
    {
        bits   <<= 8;
        bits    |= input.charCodeAt(i);
        numbits += 8;
        while ( numbits >= 5 )
        {
            shift    = numbits - 5;
            code     = bits >> shift;

            code    += (code < 26)  ?  cA : c2;

            bits    &= ~(0x1f << shift);
            numbits -= 5;
            result  += String.fromCharCode(code);
        }
    }

    if ( numbits != 0 )
    {
        shift   = 5 - numbits;
        code    = bits << shift;
        code   += (code < 26)  ?  cA : c2;
        result += String.fromCharCode(code);
    }

    return result;
}

//  Client-side utility for setting cookie field value.
//  All cookies field values that are written by client
//  script should be done so using this utility.

function SetCookieValue(cookie, field, NewValue, domain, fPermanent)
{
	// reinitialize allcookies, in case someone has called this before
	allcookies = document.cookie;  //  in function SetCookieValue
	var allcookiesFindString = allcookies.toLowerCase();
	var cookieFindString = cookie.toLowerCase();
	var fieldFindString = field.toLowerCase();
	var value, valueFindString;

	//since the InstallRedirect cookie is set in client script and is encoded, we need to
	//encode the value before we set it with normal cookie calls
    if (field == "IRD")
	{
		var EncodeValue = NewValue;
		
		//encode the NewValue for URLs to avoid issues with invite URLs
		NewValue = TextToBase32(EncodeValue);
	}

	var Result = "";
	var pos= allcookiesFindString.indexOf(cookieFindString + "=");

	if (pos != -1)
	{
		var start = pos + cookie.length + 1;
		var end = allcookiesFindString.indexOf(";", start);
		if (end == -1)
			end = allcookies.length;

		value = allcookies.substring (start, end);
		valueFindString = value.toLowerCase();
		pos = valueFindString.indexOf(fieldFindString + "=");

		if (pos != -1)
		{
            var FieldEnd = pos + field.length + 1;
            Result = value.substring(0,FieldEnd) + NewValue;
            var ValueEnd = valueFindString.indexOf("&",FieldEnd);
            if (ValueEnd != -1)
                Result = Result + value.substring(ValueEnd,value.length);
		}
		else
		{
			Result = value + "&" + field + "=" + NewValue;
		}
	}
	else
	{
		Result = field + "=" + NewValue;
	}

	var NewValue = cookie + "=" + Result + "; path=/ ";

	if (domain != "")
		NewValue = NewValue + "; domain=" + domain;

	if (fPermanent)
		NewValue = NewValue + "; expires=Wed, 02-Jan-2030 00:00:00 GMT;";


	document.cookie = NewValue;  //  in function SetCookieValue

	return Result;
}

//  An object that holds a string and an error status.
//  If error status is true, this means that the input
//  from which the string was generated was invalid.
function StringEx( str, err )
{
	this.m_str = str;
	this.m_err = err;
}

//  Convert input lowercase base32 string to text string
function Base32ToText(input)
{
	var result = new StringEx('',false);

	var cA = 'a'.charCodeAt();
	var cZ = 'z'.charCodeAt();
	var c2 = '2'.charCodeAt();
	var c7 = '7'.charCodeAt();
	var c1 = 26 - c2;

	var bits  = 0;
	var code;
	var numbits = 0;
	var i;
	var shift;

	for ( i = 0 ; i < input.length ; i++ )
	{
		code = input.charCodeAt(i);
		if ( cA <= code  &&  code <= cZ )
			code -= cA;
		else
		if ( c2 <= code  &&  code <= c7 )
			code += c1;
		else
		{
			result.m_err = true;
			return result;
		}

		bits <<= 5;
		bits |= code;
		numbits += 5;

		if ( numbits < 8 )
			continue;

		shift = numbits - 8;
		code = bits >> shift;
		bits &= ~(0xff << shift);
		numbits -= 8;
		result.m_str += String.fromCharCode(code);
	}

	if ( numbits != 0 )
	{
		shift = 8 - numbits;
		code = bits >> shift;
		if ( code != 0 )
			result.m_str += String.fromCharCode(code);
	}

	return result;
}

function ERInitControl(pageURL, siteGuid, facilityGUID, eRoomGUID, 
						userID, browserName, bUnread, serverURL, 
						authenticateUsingBrowser) 
{
	ERInitScript();

	if (!UsePlugin)
		return;

	// If we are trying to use the plugin make sure its up to date
	if (!ValidateClientControl())
		return;

	ERPageAddInCtrl = document.ERPageAddIn;

	var cookies = document.cookie;  //  passed to ERPageAddInCtrl.Initialize
	// Tell the control if the browser is offline
	var fBrowserOffline = false;
	if (IsIE && !navigator.onLine)
		fBrowserOffline = true;

	// Get any cookie from any proxy servers out there and tell the client
	// about them.  This is done through a call to an outside file that
	// can be customized by our customers
	var proxyCookie = GetProxyCookie();

	var iRes=0;
	try
	{
		iRes= ERPageAddInCtrl.Initialize(pageURL, siteGuid, facilityGUID, eRoomGUID, 
											userID, navigator.userAgent, serverURL, 
											(bUnread.toLowerCase() != "false"), 
											fBrowserOffline, cookies,
											authenticateUsingBrowser, proxyCookie );
	}catch(ex)
	{
		alert(ex.description);
	}
	// Need to do this so that we can set cookie below
	InitDynamicVariables();

	if ((iRes == 0) && !fBrowserOffline)
	{
		// if the control did not initialize and the browser is not offline,
		// set the client choice cookie field value to thin so that subsequent
		// page requests don't try (in vain) to load the control.
		SetCookieValue (gCookieName, gClientChoiceCookieFieldName, "Thin", gCookieDomain, true);
		// redirect back to this page so that it loads without the plug-in
    	location.replace(location.href);
	}

	if (ClientSupportsFeature("SetCookieDomain"))
	{
		ERPageAddInCtrl.SetCookieDomain(gCookieDomain);
	}

	var pluginVersion = GetClientVersion(UsePlugin);
	var pluginVersionFromCookie = GetCookieValue(gSessionCookieName, gPluginVersionCookieFieldName);

	if ( pluginVersionFromCookie == "" )
	{
		SetCookieValue (gSessionCookieName,
						gPluginVersionCookieFieldName,
						pluginVersion,
						gCookieDomain,
						false);
	}

	if (browserName == "Mozilla")  // Mozilla needs a special sink
		SetupEventSink( ERPageAddInCtrl );
}

function ERClickInit()
{
	InitHandler();
	RoomPresenceAdjust();
	InitWindow();

	if( typeof(UnreadHook) == "function" )
	{
		UnreadHook();
	}

	// For dialog boxes setup the mouse handler so we can hit the floating buttons
	if (!IsExecutingOnPage)
	{
		if (document.layers)    // Netscape 4
		{
			document.captureEvents(Event.KEYPRESS | Event.MOUSEDOWN | Event.MOUSEUP);
			document.onmousedown = OnButtonMouseDown;
			document.onmouseup = OnButtonMouseUp;
		}
	}

	if (document.Items)
		saveAction = document.Items.action;
}



	//-----------------------------------------
	//Function: blank
	//---------------
	//Usage: Takes a string as an argument and returns a boolean value
	//---------------
	//The function blank returns true if a text field contains no characters
	//and will return false if there are non-whitespace characters
	//-----------------------------------------
    function blank(stringer)
	{
		for (var i=0;i< stringer.length;i++)
		{
			var c=stringer.charAt(i);
			if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
		}
		return true;
	}

	function FindElementByName(formName, elementName)
	{
		var elementCount = eval("document." + formName  + ".elements.length");
		var elementType, nameType, Name;

		for (var i=0;i < elementCount;i++)
		{
			elementType = new String( typeof(eval("document." + formName + ".elements[i]")));
			if (elementType != "undefined")
			{
				nameType = new String( typeof(eval("document." + formName + ".elements[i].name")));
				if (nameType != "undefined")
				{
					Name = eval("document." + formName + ".elements[i].name");
					if (Name == elementName)
						return true;
				}
			}
		}
	
		return false;
	}

	//-----------------------------------------
//Function:OnKeyPress
	//----------------
	//Usage: When a user enters a keypress anywhere on the document
	//---------------
	//Effect:  If the user presses "Enter" on the main form of the document,
	//         i.e. the BodyForm, eRoom will act as if the user
	//         pressed the button whose name is "btnName"
	//
	//         If the user presses enter on an element in the map,
	//         eRoom will act as if the user pressed the "Search" button
	// 
	//         If the BodyForm2 form is defined (currently only on database
	//         pages that have an expanded, i.e. visible search form), 
	//         eRoom will act as if the user pressed the query button
	//         in the search form of the database, and will perform a database
	//         query.
	//     
	//         If the user presses the escape key from within a dialog,
	//         eRoom will act as if the user had pressed the cancel button.
	//------------------------------------------
	function OnKeyPress(evt)
	{
		evt = EventSetup( evt );

		var eventKeyCode = evt.keyCode;
		var isValidTargetType = false;
		var isLink = false;
		var eventName = "undefined";
				
		if (IsIE)
		{
			if (!evt.srcElement || evt.srcElement.type != "textarea")
					isValidTargetType = true;
				
			if (evt.srcElement.href && evt.srcElement.href!="")
					isLink = true;
		}
		else
		{
			if (evt.target.type == "text" || evt.target.type == "password" )
					isValidTargetType = true;
		}

		var hasName = new String( typeof(evt.target.name) );
		if (hasName != "undefined")
			eventName = evt.target.name;

		if (isValidTargetType)
		{
			if (IsIE && isLink)
			{
				// on IE, if this is some sort of link, 
				// allow the browser to handle the keypress event
				return true;
			}
			
			if (eventKeyCode == 13)
			{
				// enter was pressed, figure out where to send the 
				// default command to

				if ( typeof(document.Map) != "undefined")
				{
					if ((hasName == "undefined" || !FindElementByName("Map", eventName)) &&
						TCAPageType != RoomSearchPage && gDefaultButton == "Search" &&
						typeof(document.Map.SearchText) != "undefined")
					{	// if focus is outside the map when they hit enter, 
						// and this isn't the room search page, but the 
						// default action is to search, and the 
						// "search" tab of the map is displayed, search
						ERMapClickHandler("Search");
					}		
																
					if (hasName != "undefined" && FindElementByName("Map", eventName))
					{	// focus was inside the map when they hit enter
						if (TCAPageType == RoomSearchPage)
						{
							// the "SearchText" text box appears both on 
							// the search page and on the search tab of the
							// map.  Make sure we aren't submitting from the
							// map when we hit enter on the search text
							// button on the page.
							if (evt.target != document.BodyForm.SearchText)
								return ERMapClickHandler("Search");
						}
						else if (typeof(document.Map.SearchText) != "undefined")
						{	// the search tab of the map is displayed
							return ERMapClickHandler("Search");
						}
					}
				}
								
				var bodyform2Type = new String( typeof(document.BodyForm2) );
				if (bodyform2Type != "undefined")
					return ERBodyForm2ClickHandler("Query")
				else 
					return ERBodyFormClickHandler(gDefaultButton);
			}
			else if(eventKeyCode == 27)
			{
				// escape was pressed, send the cancel command if in a dialog
				var cmpString = new String( document.location );
				if (cmpString.indexOf("FormDispatcher") != -1)
					return ERBodyFormClickHandler("btnCancel");
			}
		}

		return true;
	}

	function SetDefaultButtonClick(btnName)
	{
		if (IsNS) 
		{
			document.captureEvents(Event.KEYPRESS | Event.MOUSEDOWN | Event.MOUSEUP);
		}

		gDefaultButton = btnName;
		document.onkeypress = OnKeyPress;
	}

//************************** Drag & Drop **************************************

	// Set the selection state on an item
	function setSelectedDisplay(obj)
	{
		if (obj == null)
			return;

		if (document.layers)    // Netscape 4
		{
			if (!IsRoomLink(obj.name))
			{
				var newSource = obj.src;
				var testStr = obj.src;
				testStr = testStr.toLowerCase();
				dotgifLoc = testStr.lastIndexOf(".gif");

				if (dotgifLoc != -1)
				{
					var index = dotgifLoc-1;
					if (testStr.indexOf ("file_") != -1)
					{
						index = testStr.indexOf ("_") - 1;
					}
					else
					{
						var aStr = "a";
						while ((index > 0) && 
							   (testStr.charCodeAt(index) < aStr.charCodeAt(0)))
						{
							index = index - 1;
						}
					}
					if (index > 0)
					{
						newSource = newSource.substr(0, index+1);
						newSource = newSource + "S.gif";
					}
				}
				// Remember the original image - but only the first time
				if (typeof(obj.orig_img) == "undefined") 
					obj.orig_img = obj.src;
				obj.src = newSource;
			}
		}
		else
		{
			// Remember the original style - but only the first time
			if (typeof(obj.orig_sytle) == "undefined") 
			{
				obj.orig_className = obj.className;
			}
			obj.className="droptarget";
		}
	}

	function restoreDragItems()
	{
		restoreSelectedDisplay(dragitem)
		restoreSelectedDisplay(dragitem2)

		dragitem = null
		dragitem2 = null
	}

	function restoreSelectedDisplay(obj)
	{
		if (obj == null)
			return;
	    
		if (obj.orig_img)       // Netscape 4
		{
			obj.src = obj.orig_img
		}
		else
		{
			obj.className = obj.orig_className;
		}
	}

	// End Utilities

	// Global hold reference to the selected object
	var source, dragitem, dragitem2, destination, selectedObj, dragObj, localDrag
	var dragStartedInMap = false, dragStartedLocally = false


	// Determine if the cursor has moved enough to start a drag operation
	function ShouldBeginDrag(evt)
	{
		// Begin the drag when the user moves off the current item
		var res = true;
		// Are we over a valid item
		if (IsOverItem(evt, false))
		{
			res = true;
			// Make sure its not the current item
			selectedObj = GetSelectedElem(evt, false)
			if (IsValidItem(selectedObj, false))
					if (source.name == selectedObj.name)
						res = false;
		}
		return res;
	}

	function IsPointBetweenObjects(x, y, Obj1, Obj2)
	{
		var xLeft, xRight, xTop, xBottom
		var IsInside = false;

		if (typeof(Obj1) == "undefined" || typeof(Obj2) == "undefined")
			return false;

		if (IsNS)
		{
			xLeft = Obj1.x;
			xTop = Obj1.y;

			xRight = Obj2.x;
			xBottom = Obj2.y;
		}
		else if (Obj1.getClientRects)
		{
			var rcts1 = Obj1.getClientRects();
			var rcts2 = Obj2.getClientRects();

			xLeft = rcts1[0].left;
			xTop = rcts1[0].top;
			
			xRight = rcts2[0].right;
			xBottom = rcts2[0].bottom;
		}
		else
		{
			xLeft = Obj1.offsetLeft;
			xTop = Obj1.offsetTop;

			xRight = Obj2.offsetLeft + Obj2.offsetWidth;
			xBottom = Obj2.offsetTop + Obj2.offsetHeight;
		}

		if ((x > xLeft) && (x < xRight) && (y > xTop) && (y < xBottom))
		{
			IsInside = true;
		}

		return IsInside;
	}

	// Test if the x,y position is in the map
	function IsInMap (x,y)
	{
		var Obj1 = document.images.RoomUL;
		var Obj2 = document.images.MapLR;

		gClickInMap = IsPointBetweenObjects(x, y, Obj1, Obj2);
		return gClickInMap;
	}

	// Test if the x,y position is in the item box
	function IsInItemBox (x,y)
	{
		var Obj1, Obj2, Obj3
		
		Obj1 = eval ("document.images.HC_0");
		Obj2 = eval ("document.images.ItemsLR");

		return IsPointBetweenObjects(x, y, Obj1, Obj2);
	}

	// Test if the x,y position is in or below the versions box
	// of a versioned file page (note there's no ItemsEnd
	// form so IsInItemBox doesn't work)
	function IsInVersionsArea (x,y)
	{
		var Obj1, Obj2, Obj3
		
		Obj1 = eval ("document.forms.Items");
		Obj2 = eval ("document.forms.MouseCommands");

		return IsPointBetweenObjects(x, y, Obj1, Obj2);
	}

	// Test if the x,y position is in the item box
	function IsInRecycleBinBox (x,y)
	{
		var Obj1, Obj2, Obj3

		Obj1 = eval ("document.images.HC_0");
		Obj2 = eval ("document.forms.BodyForm");

		return IsPointBetweenObjects(x, y, Obj1, Obj2);
	}

	// returns true if the string passed in (generated by GetSelectedItems below)
	// contains multiple IDs
	function ContainsMultipleIDs(sSelectedItems)
	{
		if (sSelectedItems.indexOf("'") != -1)
		{
			return true;
		}
		else 
		{
			return false;
		}
	}

	// Return the corresponging icon that matches object
	function GetSelectedLinks(obj)
	{
		var res = null;
		dragitem2 = null;
		if (IsNS)
		{
			res = obj;
		}
		else
		{
			var foundFirst = false;
			if (IsBlueRoomArrowName(obj.name))
			{
				foundFirst = true;
				name = "0AL0_0";
			}
			else
			{
				name = obj.name;
			}

			// Look for the items with the same object IDs
			var objID = name.substr(3);
			for (var i = document.anchors.length - 1; i >=0; i--) 
			{
				testObj = document.anchors[i]
				if (IsValidItem (testObj, true) && !IsValidItem (testObj, false))
				{
					if (objID == testObj.name.substr(3))
					{
						if (!foundFirst)
						{
							foundFirst = true;
							res = testObj;
						}
						else
						{
							dragitem2 = testObj;
							break;
						}
					}
				}
			}
		}
		return res;
	}

	function GetSelectedElemAtPoint(x, y, fValidate, fIncludeLinks) 
	{
		var res = GetSelectedElemAtPointCore(x,y);

		if (fValidate && !(IsValidItem(res, fIncludeLinks)) )
		{
			res = null;
		}
		return res
	}

	function HandleDrop (evt)
	{
		var sourcename = "";

		if (source)
		{
			sourcename = source.name;
		}

		HandleDropXY (GetBrowserX(evt), GetBrowserY(evt), "", sourcename);
	}

	function HandleDropXY (x, y, room, id)
	{
		selectedObj = GetSelectedElemAtPoint(x, y, true, true)

		var destination = "";
		if (IsValidItem(selectedObj, true))
		{
			if (IsRoomLink(selectedObj.name))
				destination = "0AL0_0";
			else
				destination = selectedObj.name;
		}
		else
		{
			destination = GetBackgroundElemAtPoint(x,y)
		}

		if (destination && (destination != "none"))
		{
			SubmitCommand("MouseCommands", "Drag", id, destination, room, "")
		}
		else
		{
			if (source)
			{
				restoreSelectedDisplay(source)
			}
		}
		selectedObj = null;
	}

	function ExC (docID, Expansion)
	{
		if (Expansion != "Non")
		{
			var fPassAlong = true;
			var sMap;
			if (UsePlugin && IsIE && navigator.onLine && (Expansion != "Nav") && IsClearTrustPresent() == false)
			{
				// Let the plugin try to handle it
				fPassAlong = false;
				var fExpand = true;
				if (Expansion == "Exp")
					fExpand = false;

				sMap = ERPageAddInCtrl.ExpandCollapse (docID, fExpand);
				if (sMap.length > 0)
				{
					document.all.MapDiv.outerHTML = sMap;
				}
			}

			if (fPassAlong)
			{
				SubmitCommand("MouseCommands", Expansion, docID, "", "", "")
			}
		}
		return false;
	}

	function GetName(obj)
	{
		if (obj)
			return obj.name
		else
			return "";
	}

	// The first character is a type indicator (normal, preview, presentable, etc.)
	function IsValidFirstChar(TestChar)
	{
		if ((TestChar == "A") || (TestChar == "P") || (TestChar == "C") || 
			(TestChar == "p"))
			return true;
		else
			return false;
	}

	// The second character is the icon (A) or Link (L) indicator
	function IsValidSecondChar(TestChar)
	{
		if ((TestChar == "A") || (TestChar == "L"))
			return true;
		else
			return false;
	}

	// determine if this menu index is for version tracked files
	function IsVersionTrackedMenuFromMenuIndex(menuNum)
	{
		return ((menuNum == GetMenuIndexFromMenuID(VersionedFileMenu)) 
			|| (menuNum == GetMenuIndexFromMenuID(VersionedFileMenu_Preview))
			|| (menuNum == GetMenuIndexFromMenuID(MapVersionedFileMenu))
			|| (menuNum == GetMenuIndexFromMenuID(MapVersionedFileMenu_Preview))
			|| (menuNum == GetMenuIndexFromMenuID(VersionedRMProtectedItemMenu)));
	}

	// determine if this menu index is for Publish to Documentum files
	function IsPublishToDocumentumFromMenuIndex(menuNum)
	{
		return (menuNum == GetMenuIndexFromMenuID(DMFileMenu)) || 
		       (menuNum == GetMenuIndexFromMenuID(DMFileMenu_Preview));
	}

	function IsIMMenuWithIMChoice(menuNum)
	{
		return (menuNum == GetMenuIndexFromMenuID(IMMenu)) || 
			   (menuNum == GetMenuIndexFromMenuID(IMMenuNoEmail)) || 
			   (menuNum == GetMenuIndexFromMenuID(IMMenuNoMemberInfo)) || 
			   (menuNum == GetMenuIndexFromMenuID(IMMenuIMOnly));
	}
	
	// Preview is first character P or p
	function HasPreview(name)
	{
		if (IsValidSecondChar (name.charAt(2)) && ((name.charAt(1)=="P") || (name.charAt(1) == "p")))
			return true;
		else
			return false;
	}

	// Present is first character C or p
	function CanPresent(name)
	{
		if (IsValidSecondChar (name.charAt(2)) && ((name.charAt(1)=="C") || (name.charAt(1) == "p")))
			return true;
		else
			return false;
	}

	// Documents (icons) are valid first characters and A's
	function IsDocument(name)
	{
		if (IsValidFirstChar (name.charAt(1)) && (name.charAt(2) == "A"))
			return true;
		else
			return false;
	}

	// Links (the text) are valid first characters and L's
	function IsLink(name)
	{
		if (IsValidFirstChar (name.charAt(1)) && (name.charAt(2) == "L"))
			return true;
		else
			return false;
	}

	function IsRoomLink(name)
	{
		if ((name == "RoomUL") || IsBlueRoomArrowName (name))
			return true;
	}

	function IsIMIcon(name)
	{
		var TestStr="IMIcon";
		var firstPart = name.substr (1, TestStr.length);
		return (firstPart == TestStr);
	}

	function IsBlueRoomArrow(evt)
	{
		var x = GetBrowserX(evt);
		var y = GetBrowserY(evt);
		return IsBlueRoomArrowAtPoint (x,y)
	}

	function IsBlueRoomArrowAtPoint (x,y)
	{
		var res = GetSelectedElemAtPointCore(x,y);
		if (res && res.name)
		{
			return IsBlueRoomArrowName (res.name)
		}
		else
			return false;
	}

	function IsBlueRoomArrowName (name)
	{
		var roomULString = "RoomBlueArrow:"
		
		var firstPart = name.substr (0, roomULString.length)

		if (firstPart == roomULString)
		{
			RoomDocID = name.substr (roomULString.length, name.length)
			return true;
		}
		else
			return false;
	}

	function IsApprovalStepName(name)
	{
		if (name == "")
			return false;
		
		if( name.charAt(0) == WorkflowPhaseMenu)
			return true;
		else
			return false;
	}

	function IsValidItem(obj, fIncludeLinks) 
	{
		if (obj)
		{
			var name = "";
			if (typeof(obj.name) != "undefined")
				if (obj.name != "")
				{
					name = obj.name;
				}

			if (name != "")
			{
				if (IsDocument (name))
					return true;

				if (fIncludeLinks && IsLink (name))
					return true;

				if (fIncludeLinks && IsRoomLink (name))
					return true;
					
				if(IsIMIcon(name))
				{
					return true;
				}
			}
		}
		return false
	}

	function IsValidCell(element) 
	{
		if (element && (element.charAt(0) == "C") &&
			(element.charAt(1) == ":"))
			return true
		return false
	}

	function GetBackgroundElem(evt) 
	{
		var x = GetBrowserX(evt);
		var y = GetBrowserY(evt);
		return GetBackgroundElemAtPoint(x,y);
	}

	function GetBackgroundElemAtPoint(x,y) 
	{
		var element = ""
		var col, row, Obj1, Obj2, i, NotDone;
		var selobj = GetSelectedElemAtPoint(x, y, false, false);

		if (selobj)
		{
			if (typeof(selobj.name) != "undefined") 
			{
				if ((selobj.name.charAt(0) != "H") && (selobj.name.charAt(1) != "R") &&
					(selobj.name.charAt(2) != "_"))
				{
					if (IsValidCell(selobj.name))
						element = selobj.name;
					return element;
				}
			}
		}

		// IE 4 does not handle hit testing correctly
		if (IsIE && version < 5)
			return element;

		col = -1;
		row = -1;
		i = 0;
		NotDone = true;
		while (NotDone)
		{
			var xLeft = 0;
			var xRight = 0;
			Obj1 = eval ("document.images.HC_" + i);
			Obj2 = eval ("document.images.HC_" + (i+1));
			if (typeof(Obj1) != "undefined")
			{
				if (IsNS)
					xLeft = Obj1.x;
				else if (Obj1.getClientRects)
					xLeft = Obj1.getClientRects()[0].left;
				else
					xLeft = Obj1.offsetLeft;

				if (typeof(Obj2) != "undefined")
				{
					if (IsNS)
						xRight = Obj2.x;
					else if (Obj2.getClientRects)
						xRight = Obj2.getClientRects()[0].left;
					else
						xRight = Obj2.offsetLeft + Obj2.offsetWidth
				}
				else
				{
					xRight = xLeft + Obj1.width;
				}

				if ((x > xLeft) && (x < xRight))
				{
					col = i;
					NotDone = false;
				}
				i = i + 1;
			}
			else
				NotDone = false;
		}
		i = 0;
		NotDone = true;
		while (NotDone)
		{
			if (i == 0)
			{
				Obj1 = eval ("document.images.HC_0");
				Obj2 = eval ("document.images.HR_1");
			}
			else
			{
				Obj1 = eval ("document.images.HR_" + i);
				Obj2 = eval ("document.images.HR_" + (i+1));
			}
			if (Obj1 && Obj2)
			{
				var yTop = 0;
				var yBottom = 0;

				if (IsNS)
				{
					yTop = Obj1.y;
					yBottom = Obj2.y + Obj2.height;
				}
				else if (Obj1.getClientRects)
				{
					var rcts1 = Obj1.getClientRects();
					var rcts2 = Obj2.getClientRects();
					yTop = rcts1[0].top;
					yBottom = rcts2[0].bottom;
				}
				else
				{
					yTop = Obj1.offsetTop;
					yBottom = Obj2.offsetTop + Obj2.offsetHeight
				}
				if ((y > yTop) && (y < yBottom))
				{
					row = i;
					NotDone = false;
				}
			}
			else
				NotDone = false;
			i = i + 1;
		}
		if ((col > -1) && (row > -1))
		{
			element = "C:" + row + "," + col
		}

		if (!IsValidCell(element))
			element = ""
		return element
	}

	function IsOverItem(evt, fIncludeLinks)
	{
		var CurItem = GetSelectedElem(evt, fIncludeLinks);
		var BackgroundItem = GetBackgroundElem(evt);
		if (CurItem || BackgroundItem || IsBlueRoomArrow(evt))
			return true;
		return false;
	}

	function GetSelectedElem(evt, fIncludeLinks) 
	{
		var x = GetBrowserX(evt);
		var y = GetBrowserY(evt);

		return GetSelectedElemAtPoint(x, y, true, fIncludeLinks);
	}

//**************************Mouse Button Functions*****************************
// Functions for mouse down, mouse move and mouse up
	function OnMouseDown(evt) 
	{
		evt = EventSetup( evt );

		source = null
		selectedObj = null
		LaunchedFile = false;

		if (MenuOnDisplay)
		{
			if (!isOverMenu && currentMenu!=null) 
			{
				hideAll();
				if (menuItem)
					restoreSelectedDisplay(menuItem);

				return false;
			}
		}
		else
		{
			selectedObj = GetSelectedElem(evt, IsMeetingSharePane)

			if (selectedObj && ObjectCanBeDragged(selectedObj)) 
			{
				source = selectedObj
				localDrag = true

				setSelectedDisplay(source);

				SourceX = GetBrowserX(evt);
				SourceY = GetBrowserY(evt);

				// set dragStartedInMap to true only if in map
				dragStartedInMap = IsInMap(SourceX,SourceY)
				dragStartedLocally = true

				// prevent further response to mouseDown
				EventStopPropagation( evt );
				return false;
			}

			if (IsMouseMenu(evt) && IsOverItem(evt, false))
			{
				return false;
			}

			if (document.layers)    // Netscape 4
			{
				// Test for floating buttons
				if (!OnButtonMouseDown(evt))
					return false;
			}
		}
	}

	function GetServerPrefix(FacilityURLName)
	{
		var ServerPrefix = eval("document.Items." + FacilityURLName + ".value");
		return ServerPrefix;
	}
	

	// Dragging an element
	function OnMouseMove(evt) 
	{
		evt = EventSetup( evt );

		// No drag and drop in the meeting pane
		if (IsMeetingSharePane)
			return false;

		if (MenuOnDisplay)
		{
			return false;
		}
		else if (source && localDrag)
		{
			selectedObj = GetSelectedElem(evt, true)
			// If there is a control 
			if (UsePlugin)
			{
				if (ShouldBeginDrag(evt))
				{
					// Clear the localDrag flag so BeginDrag is only called once
					localDrag = false;

					var FacilityURLName = "";
					FacilityURLName = GetFacilityURLNameFromID(source.name);
					var ServerPrefix = "";
					if (FacilityURLName.length > 0)
						ServerPrefix = eval("document.Items." + FacilityURLName + ".value");

					var MenuObjID = RemoveFacilityURLNameFromID( source.name );

					ERPageAddInCtrl.BeginDrag(ServerPrefix, FacilityURLName, document.location, MenuObjID);
				}
			}
			else
			{
				DragOver(GetBrowserX(evt), GetBrowserY(evt));
			}

			// prevent further response to dragging
			EventStopPropagation( evt );
			return false;
		}
	}

// Handles document-wide mouse up events
	function OnMouseUp(evt) 
	{
		evt = EventSetup( evt );
		
		if (evt.which != undefined)
		{
			// if this is a context menu (3), we should handle via the OnContextMenu function.
			// Some browsers (like Netscape) will try this handler *before* OnContextMenu
			if (evt.which == 3)
				return true;
		}

		var passEvent = false;
		dragStartedInMap = false;
		dragStartedLocally = false;

		if (MenuOnDisplay && !isOverMenu)
			return false;

		// Did the user start on an item
		selectedObj = GetSelectedElem(evt, true);

		if (IsValidItem(source, IsMeetingSharePane))
		{
			// Did the user let go on the same object they start on
			if (!IsValidItem(selectedObj, true) || (source.name != selectedObj.name))
			{
				// No - treat it as a drop
				restoreSelectedDisplay(source)
				HandleDrop (evt);
				passEvent = true
			}
			else if (IsIMIcon(selectedObj.name))
			{
				// Display a menu for left click too
				DisplayMenu (evt);
				passEvent = true;
			}
			else if (IsMouseMenu(evt))
			{
				if (IsMeetingSharePane && !UsePlugin)
				{
					// do not display pop-up here
					return false;
				}
				else
				{
					// Display a menu now if the browser doesn't support
					// the onContextMenu event.
					DisplayMenu (evt);
					passEvent = true;
				}
			}
			else
			{
				// If the user clicks on a file - view it (unless previewable)
				var menuID = source.name.charAt(0);
	
				if (menuID == EntDBInTemplateFolderMenu || 
					menuID == APDBInTemplateFolderMenu)
				{
					menuItem = source;
					ExecuteCommand("EditItem")
					return false;
				}
				else if (menuID == DBRowMenu)
				{
					menuItem = source;
					ExecuteCommand("ViewItem")
					passEvent = true;
					restoreSelectedDisplay(source)
				}
				else if (((menuID == FileMenu) || (menuID == VersionedFileMenu) ||
					(menuID == CompanionFileMenu) || (menuID == VersionedCompanionFileMenu) ||
					(menuID == DMFileMenu) || IsMeetingSharePane)) 
				{
					
					if (IsMeetingSharePane)
					{
						if (!TestShareFile(CanPresent(source.name)))
							return false;

						if (CanPresent(source.name))
						{
							UploadPresention(source.name.substr (3));
							return false;
						}
					}

					if (HasPreview(source.name))
					{
						menuItem = source;
						LaunchedFile = true;
						ExecuteCommand("PreviewItem") 
						passEvent = true;
						restoreSelectedDisplay(source)
					}
					else
					{
						// Let the browser display files when offline without the plugin
						if (IsIE && !navigator.onLine && !UsePlugin)
						{
							return true;
						}

						// Let the browser display files when not using the plug-in and on the site search
						// page, in order to resolve back button issues
						if (!UsePlugin && TCAPageType == SiteSearchPage)
						{
							if (IsIE)
							{
								return true;
							}
							else
							{
								return SiteSearchViewFile( source.name.substr(3) );
							}
						}
							
						menuItem = source;
						LaunchedFile = true;
						ExecuteCommand(IsMeetingSharePane ? "ViewShareFileItem" : "ViewFileItem") 
						passEvent = true;
						restoreSelectedDisplay(source)
					}
				}
				else if (IsNS)
				{
					// For non-control mode, we have to consume the mouse down 
					// otherwise the browser stays in selection mode.  
					// Therefore we need to manually navigate
					if (evt.target.href)
					{
						menuId = source.name.charAt(0);
						if (menuId == NewWindowLinkMenu)
							window.open (evt.target.href);
						else
							document.location = evt.target.href;
					}
					restoreSelectedDisplay(source)
				}
			}
		}
			// Not an item check for target for menu popup
		else if (IsMouseMenu(evt) && 
			(IsInItemBox(GetBrowserX(evt), GetBrowserY(evt)) || IsOverItem(evt, false)) )
		{
			if ((TCAPageType == FacilitySearchPage) || (TCAPageType == RoomSearchPage))
			{
				return false;
			}
			else if (!selectedObj || IsApprovalStepName(selectedObj.name) || IsBlueRoomArrowName(selectedObj.name) || ObjectIsRecycleBin(selectedObj))
			{
				DisplayMenu(evt);
				passEvent = true;
			}
			else
			{
				return false;
			}
		}
		else if (document.layers)   // Netscape 4
		{
			return OnButtonMouseUp( evt );
		}
		
		source = null;
		selectedObj = null;

		if (passEvent)
		{
			EventStopPropagation( evt );
			return false;
		}
	}

	// In IE the left button will also generate a click - if we have displayed a
	// menu we need to cancel the click event as well
	function OnClick(evt)
	{
		evt = EventSetup( evt );

		if (MenuOnDisplay || LaunchedFile)
		{
			EventStopPropagation( evt );
			return false;
		}
	}

	// Modern browsers send this event after MouseUp in response to right-click.
	function OnContextMenu(evt) 
	{
		if (MenuOnDisplay)
			return false;

		evt = EventSetup( evt );

	    if (evt.target.name && evt.target.name.charAt(1) && evt.target.name.charAt(4) == '_')
	    {
	        var target = evt.target;
			var x = 0, y = 0;

			do			
			{
				x += target.offsetLeft;
				y += target.offsetTop;
				target = target.offsetParent;
			}
			while (target != null);
			
			// show menu in center of icon IMG
			var useThisTarget;
			if (evt.target.firstChild)
				useThisTarget = evt.target.firstChild
			else
				useThisTarget = evt.target
			x += useThisTarget.offsetWidth / 2;
			y += useThisTarget.offsetHeight / 2;
			
			if (!DisplayMenuXY(evt, x, y, useThisTarget))
				// no menu to display
				return true;
			EventStopPropagation( evt );
			return false
	    }

		if (IsOverItem( evt, false ))
		{
			DisplayMenu( evt );
			return false;
		}
		
		return true;
	}

	function OnAddFiles(Files, x, y)
	{
		if (IsNS)
			y = y + window.pageYOffset;
		selectedObj = GetSelectedElemAtPoint(x, y, true, true);
	}

	// same as GetURLTarget, but returns an "!" if drop is outside of the item box or map
	function GetURLTargetForAddIn(x, y)
	{
		var dragNDropOK = true
	
		if (pageType == "RecycleBin")
		{
			if (dragStartedInMap == true)
			{
				if (!IsInMap (x,y) && !IsInRecycleBinBox(x,y))
				{
					dragNDropOK = false;
				}
			}
			else
			{
				if (!IsInMap (x,y))
				{
					var selObj;
					selObj = GetSelectedElemAtPoint(x, y, true, true)
					if (!IsValidItem(selObj, true))
						dragNDropOK = false;
				}
			}
		}
		else if (pageType == "Calendar")
		{
			if ((dragStartedInMap == true) || dragStartedLocally == false)
			{	// an item from desktop, or the map
				if (!IsInMap(x,y) && source != null)
				{
					var selMenuID;
					selMenuID = source.name.charAt(0);
					if (selMenuID != CalendarEventMenu)
					{
						dragNDropOK = false;
					}
				}
			}
		}
		else if (isVersionedFilePage && IsInVersionsArea(x,y))
		{
			// [24919] No drop on items in version page item box
			dragNDropOK = false;
		}
		else if (IsMeetingSharePane)
		{
			// [37167] No drop on items in meeting share pane
			dragNDropOK = false;
		}
		else
		{
			if (!IsInMap (x,y) && !IsInItemBox(x,y))
			{
				var selObj;
				selObj = GetSelectedElemAtPoint(x, y, true, true)
				if (!IsValidItem(selObj, true))
					dragNDropOK = false;
			}
		}

		if (dragNDropOK == false)
		{
			return "!";
		}
		else
		{
			return GetURLTarget(x, y);
		}
	}

	function GetURLTarget(x, y)
	{
		selectedObj = GetSelectedElemAtPoint(x, y, true, true);
		var target = "";
		if (selectedObj)
		{
			target = selectedObj.name;
		}
		return target;
	}

	function GetURL(x, y, target)
	{
		if (IsNS)
		{
			target[0] = GetURLTarget(x, y);
		}
		else
		{
			target = GetURLTarget(x, y);
		}
	}

	function DragAndDrop(x, y, room, id)
	{
		// Force conversion of BSTR parameters as JavaScript strings (required for Netscape)
		var sroom = "" + room;
		var sid = "" + id;

		HandleDropXY (x, y, sroom, sid);
	}

	function Navigate (url)
	{
		if (url != "")
			document.location = url;
		else
			document.location = document.location;
	}

	function DragOver(x, y)
	{
		selectedObj = GetSelectedElemAtPoint(x, y, true, true);

		if (IsValidItem(selectedObj, true))
		{
			if (!dragObj || (dragObj.name != selectedObj.name))
			{
				restoreDragItems();
				dragObj = selectedObj;
				dragitem = GetSelectedLinks (selectedObj);
				setSelectedDisplay(dragitem);
				setSelectedDisplay(dragitem2);
			}
		}
		else
		{
			dragObj = null;
			if (dragitem && (dragitem != source))
			{
				restoreDragItems();
			}
		}
	}

	function ClearIntercomSparkle()
	{
		if ( typeof(document.images.btnIntercom) != "undefined" ) 
		{
			var newSource = document.images.btnIntercom.src;
			var index = newSource.lastIndexOf("S.gif");
			if ( index != -1 )
			{
				newSource = newSource.substr(0, index);
				newSource = newSource + ".gif";
				document.images.btnIntercom.src = newSource;
			}
		}
	}

//**************************Dialog event processing****************************
// Dialog event methods
function SubmitHandler(btnName)
{
	for ( var i = 0; i < gSubmitHandlers.length; i++ )
	{
		gSubmitHandlers[i](btnName);
	}

	return false;
}

function ClientSideVerifyHandler(btnName)
{
	var retVal = true;
	for ( var i = 0; i < gClientSideVerify.length; i++ )
	{
		retVal = retVal && gClientSideVerify[i](btnName);
	}

	return retVal;
}

function DisplayErrorPopupQuery(message)
{
	gErrorMessage = message;
	DisplayErrorPopup();
}

function DisplayErrorPopup()
{
	window.alert( gErrorMessage );
	// DBRow validation can set focus to failed control
	if (typeof(gFocusControl) != "undefined")
	{
		if (gFocusControl.length >0){
			try {
				// this doesn't work for richtext
				var theControl = eval("window.document." + gFocusControl);
				theControl.focus();
			}
			catch(ex) {
				// control couldn't take focus (rtf?)
			}
		}
	}

}

function InitHandler()
{
	if (document.layers) 
	{
		visible = 'show';
		hidden = 'hide';
		nsMenuLayerMap = new Array();
	} else 
	{
		visible = 'visible';
		hidden = 'hidden';
	}

	allcookies = document.cookie;  //  in function InitHandler
	InitDynamicVariables();
	client = GetCookieValue(gCookieName, gClientChoiceCookieFieldName);
	if (allcookies.length > 0)
	{
		if (IsIE && navigator.onLine)
		{
			var currentPageModTag = GetCookieValue(gSessionCookieName, gPageModTagCookieFieldName);
			if ( currentPageModTag == '' )
				currentPageModTag = pageModTag;

			if ((currentPageModTag != pageModTag) && !IsMeetingKeepAlive) // don't refresh the meeting keep alive window, bug 35570
			{
				var lowerLocation = location.href;
				lowerLocation = lowerLocation.toLowerCase();
				if (GetCookieValue(gSessionCookieName,gRefreshPageCookieFieldName) != lowerLocation)
				{
					SetCookieValue(gSessionCookieName, gRefreshPageCookieFieldName, lowerLocation, gCookieDomain, false);

					location.replace(location.href);
				}
			}
			else
            {
                //  don't set any cookie field if we are about to view DlgLogout.asp
                //  otherwise the session cookie will reappear and thus undo its removal by the ERServer ISAPI filter
                var url=""+document.location;
                if ( url.indexOf("DlgLogout.asp") == -1 )
				    SetCookieValue(gSessionCookieName,gRefreshPageCookieFieldName, "none", gCookieDomain, false);
            }
		}
	}
	else
	{
		alert (gCannotReadCookiesStr)
	}

	var cookieValue = new String( GetSubCookie(gShowErrorPopUpCookieFieldName) );
	if (cookieValue.indexOf("1") == 0)
	{
		SetCookieValue(gSessionCookieName, gShowErrorPopUpCookieFieldName, "0", gCookieDomain, false);
		DisplayErrorPopup();
	}

	for ( var i = 0; i < gInitHandlers.length; i++ )
	{
		gInitHandlers[i]();
	}
}

function GetSubCookie(name)
{
	var pos = document.cookie.indexOf( name + "=" );
	var start = pos + name.length+1;
	var end = document.cookie.indexOf(";", start);
	var value = 0;
	if (pos != -1)
	{
		if (end == -1)
			value = document.cookie.substring(start, document.cookie.length);
		else
			value = document.cookie.substring(start, end);
	}
	return value;
}

function IsValidObjName (Name)
{
	if ((Name.indexOf("/") != 0) && (Name.indexOf("#") != 0) &&
		(Name.indexOf(":") == -1) && (Name.indexOf("=") == -1) && 
		(Name.indexOf(" ") == -1) && (Name.indexOf(".") == -1))
		return true;
	return false;
}

function HandleGroupChange()
{
	window.setTimeout("ERBodyFormClickHandler('Group')", 100);
	return true;
}


function HandleQueryChange()
{
	window.setTimeout("ERBodyFormClickHandler('Query')", 100);
	return true;
}

function HandleGanttViewType()
{
	window.setTimeout("ERBodyFormClickHandler('GanttViewType')", 100);
	return true;
}

function RoomPresenceAdjust()
{
	var onLine = true
	if (typeof(navigator.onLine) != "undefined" &&
		navigator.onLine == false)
	{
		onLine = false
	}

	if (IsIE)
	{
		var Obj1 = eval ("document.all.memberGifs")
		if ((!onLine) && (Obj1 != null))
			Obj1.style.visibility="hidden"
	}
}

var inSubmitCommand = 0;
function SubmitCommand(formName, btnName, param1, param2, param3, selID)
{
// don't allow this to be re-entrant; it breaks in Mozilla 
// when a command in item box's TaskBar is double-clicked (bug 35645)
	if (inSubmitCommand)
		return false;
	else
		inSubmitCommand = 1
		
	SubmitCommandCore(formName, btnName, param1, param2, param3, selID)

	// reset the flag
	inSubmitCommand = 0
	
	return false
}

function SubmitCommandCore(formName, btnName, param1, param2, param3, selID)
{
	if (!ClientSideVerifyHandler(btnName))
		return false;

	gAllowButtonMouseOut = false;
	var cmpString = new String(formName);
	var bIsItems = (cmpString.indexOf("Items") != -1);	

	OnERFormSubmit();
	SubmitHandler(btnName);
	var formAction = "document." + formName + ".action";
	var sessionKey = eval("document." + formName + ".SessionKey.value");
	eval(formAction + " = AppendCommand("+formAction+",'"+btnName+"','"+param1+"','"+param2+"','"+param3+"','"+selID+"','"+sessionKey+"');");
	eval(formAction + " = PersistPopUpContext(" + formAction + ");");

	if (UsePlugin)
	{
		if ((btnName == "CopyItem") || (btnName == "CutItem")  ||
			(btnName == "CopyLinkToItem") || (btnName == "PasteItem"))
		{
			iRes = HandleClientClipboard(btnName, formName);
			if (iRes == 0)
				return false;
		}
	}

	if (bIsItems)
	{
		if (!ContainsPageStr(eval(formAction)) && selID.length == 0)
			eval(formAction + "= "+formAction+" + ERGetSelectedRows();");
	}

	var cmpString = new String( document.location );

	DoEval( "document." + formName + ".submit();" );

	return false;
}

function ERLogoutClickHandler(link,context)
{
    if (!UsePlugin)
        return true;

    var cleanedFiles;

    //  Keep these in sync with constants defined in TCAPageSiteSettings.cpp
    var kMinPluginMajorForLogout = 496;
    var kMinPluginMinorForLogout = 1;
    var kMinPluginVersionForLogout = (kMinPluginMajorForLogout<<8)|kMinPluginMinorForLogout;

    cleanedFiles = 0;
    if (GetClientVersion(UsePlugin) >= kMinPluginVersionForLogout)
    {
        //  Logout method will pop up any necessary dialogs regarding cache file deletion
        var status = ERPageAddInCtrl.Logout(context);
        if (status != 0)
            return false;
        cleanedFiles = 1;
    }

    var linkHref = (typeof(link) == "object") ? link.href : link;
    document.location = linkHref + '&CLF=' + cleanedFiles;
    return false;
}

function ERBodyFormClickHandler(btnName)
{
	return SubmitCommand("BodyForm", btnName, "", "", "", "");
}

function ERBodyForm2ClickHandler(btnName)
{
	return SubmitCommand("BodyForm2", btnName, "", "", "", "");
}

function ERItemsClickHandler(btnName)
{
	return SubmitCommand("Items", btnName, "", "", "", "");
}

function ERMapClickHandler(btnName)
{
	return SubmitCommand("Map", btnName, "", "", "", "");
}

// Return the selected items include the sSelectedName if its not in the list
// This function will throw if the selected items are from different 
// facilities, because multi-select across facilities (and potentially
// accross servers) is not allowed
function GetSelectedItems(sSelectedName, formName)
{
	var bHasCheckedProperty, bIsChecked;
	var sIDs, fAddSelected, sSelectedID, fixedUpID;
	var FacilityURLName, lastFacilityURLName;

	var sIDs = "";
	if (sSelectedName.length == 0)
		fAddSelected = false;
	else
	{
		lastFacilityURLName = GetFacilityURLNameFromID(sSelectedName);
		lastFacilityURLName.toLowerCase();
		fAddSelected = true;
	}
	var formLength = eval("document." + formName  + ".elements.length");

	for (var i=0;i < formLength;i++)
	{
		bHasCheckedProperty = new String( typeof( eval("document." + formName + ".elements[i].checked")) );
		if (bHasCheckedProperty == "boolean") 
		{
			bIsChecked = eval("document." + formName  + ".elements[i].checked");
			if (bIsChecked)
			{
				// If this is the selected item, do not add it
				var itemName = new String( eval("document." + formName + ".elements[i].name") );
				if (itemName == sSelectedID)
					fAddSelected = false;

				var IsValidName = true;

				if (formName == "BodyForm")
				{
					var rowHandleType = new String(typeof( eval("document." + formName + ".HAA" + itemName )));
					if (rowHandleType == "undefined")
						IsValidName = false;
				}
				
				if (formName == "Items")
				{
					if (itemName.charAt(0) != 'A')
						IsValidName = false;
				}

				if (IsValidName &&
					(itemName.indexOf('_') != -1) && 
					(itemName.indexOf('{') == -1)) // ignore Instant Meetings
				{
					if (sIDs.length != 0)
						sIDs = sIDs + "'";

					if (lastFacilityURLName == "")
					{
						lastFacilityURLName = GetFacilityURLNameFromID( itemName );
					}
					else
					{
						FacilityURLName =  GetFacilityURLNameFromID( itemName );
						FacilityURLName.toLowerCase();
						if (FacilityURLName.length > 0)
						{
							if ( FacilityURLName.indexOf( lastFacilityURLName ) == -1 ||
								FacilityURLName.length != lastFacilityURLName.length)
							{
								DisplayErrorPopupQuery(gSelectItemsFromSameRoomForSearchErrStr);
								return "";
							}
						}
					}

					sIDs = sIDs + "0A" + RemoveFacilityURLNameFromID( itemName );
				}
			}
		}
	}

	if (fAddSelected)
	{
		if (sIDs.length != 0)
			sIDs = sIDs + "'";

		fixedUpID = 
		sIDs = sIDs + RemoveFacilityURLNameFromID( sSelectedName );
	}

	return sIDs;
}

function HandleClientClipboard(btnName, formName)
{
	var sMenuObjIDs = "";
	if (btnName != "PasteItem")
		sMenuObjIDs = GetSelectedItems("", formName, false);

	var fBrowserOffline = false;
	if (IsIE && !navigator.onLine)
		fBrowserOffline = true;

	iRes = 1

	var FacilityURLName = "";
	var ServerPrefix = "";

	if (sMenuObjIDs.length)
	{
		if (!ContainsMultipleIDs(sMenuObjIDs ))
		{		
			FacilityURLName = GetFacilityURLNameFromID(sMenuObjIDs);
			if (FacilityURLName.length > 0)
				ServerPrefix = eval("document.Items." + FacilityURLName + ".value;");
		}
		iRes = ERPageAddInCtrl.ExecuteVerb(btnName, ServerPrefix, FacilityURLName, sMenuObjIDs, "", fBrowserOffline);
	}

	return iRes;
}

var kMaxSelectedItemsOnURL = 90;

function ERGetSelectedRows()
{
	var sSelectedRows = "";
	var sResult = "";
	var selCount = 0;

	for (i=0; i < document.Items.elements.length; i++)
	{
		if (document.Items.elements[i].type == "checkbox" && document.Items.elements[i].checked == true)
		{
			selCount++;
			sSelectedRows = sSelectedRows + "&" + "SelID=" + document.Items.elements[i].value;
		}
	}
	sResult = "&SelCount=" + selCount;
	if (selCount <= kMaxSelectedItemsOnURL)
		sResult = sResult + sSelectedRows;
	return sResult;
}

function ContainsPageStr(sTestURL)
{
	var eRoomRootPattern = /\/eroom\//gi  // find all matches, case-insensitive
	var PagePattern = /page/gi
	var SubmitPattern = /submit/gi
	var PageCommandsPattern = /commands/gi
	var FormDispatcherPattern = /formdispatcher/gi

	// if the eroom virtual root is found in the URL, OR
	// "page" is found in the URL, but "submit" is not OR
	// the string "commands.asp" is not found in the URL
	// this URL refers to an eRoom page
	
	var sTest;
	
	if (sTestURL.indexOf(".asp") == -1)
	{
		// this must be a page, because
		// there is no .asp in the URL
		return true;
	}

	sTest = sTestURL.substr(0, sTestURL.indexOf(".asp"));
	

	if ((sTest.search(eRoomRootPattern) != -1) || 
		((sTest.search(PagePattern) != -1) && 
		(sTest.search(SubmitPattern) == -1)) && 
		(sTest.search(PageCommandsPattern) == -1) && 
		(sTest.search(FormDispatcherPattern)))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function PersistPopUpContext(LinkHref)
{
	var addParam = LinkHref.indexOf("InPopUpWindow=TRUE");
	var hasParam = location.href.indexOf("InPopUpWindow=TRUE");
	var hasQuestionMark = LinkHref.indexOf("?", 0);
	var retVal;

	retVal = LinkHref
	if (addParam == -1 && hasParam != -1)
	{
		if (hasQuestionMark == -1)
			retVal = retVal + "?InPopUpWindow=TRUE";
		else
			retVal = retVal + "&InPopUpWindow=TRUE";
	}
	return retVal;
}

function LaunchDialogInNewWindow(link)
{
	var linkHref;
	if (typeof(link) == "object")
		linkHref = link.href;
	else
		linkHref = link;
				
	linkHref = PersistPopUpContext(linkHref)
	var onLine = true;
	if (typeof(navigator.onLine) != "undefined" &&
		navigator.onLine == false)
	{
		onLine = false;
	}

	if (onLine && typeof(document.BodyForm) != "undefined")
	{
		if (typeof(link) == "object") 
		{
			link.href = linkHref;
		}
		
		launchBrowser(linkHref, null, null)

		return false;
	}
	return true;
}

function ERBodyFormLinkClickHandler(link)
{
	var linkHref;
	if (typeof(link) == "object")
		linkHref = link.href;
	else
		linkHref = link;
				
	linkHref = PersistPopUpContext(linkHref)
	var onLine = true;
	if (typeof(navigator.onLine) != "undefined" &&
		navigator.onLine == false)
	{
		onLine = false;
	}

	if (onLine && typeof(document.BodyForm) != "undefined")
	{
		if (typeof(link) == "object") 
		{
			link.href = linkHref;
		}

		document.location = linkHref;

		return false;
	}
	return true;
}	

function ERItemsLinkClickHandler(link)
{
	link.href = PersistPopUpContext(link.href)
	var onLine = true;
	if (typeof(navigator.onLine) != "undefined" &&
		navigator.onLine == false)
	{
		onLine = false;
	}
	if (onLine && typeof(document.Items) != "undefined")
	{
		var sTemp;
		sTemp = link.href.toLowerCase();
		if (sTemp.indexOf("/eroom/") == -1)
		{
			link.href = AppendWindowContextToQueryString(link.href, GetWindowName());
		}

		document.location = link.href;
		return false;
	}
	return true;
}	

function OnERFormSubmit()
{
	if (typeof(document.BodyForm) != "undefined")
	{
		document.BodyForm.ERWindowName.value = GetWindowName();
		if (!ContainsPageStr(document.BodyForm.action))
		{
			document.BodyForm.action = AppendWindowContextToQueryString(document.BodyForm.action, GetWindowName());
		}
	}

	if (typeof(document.Map) != "undefined")
	{
		document.Map.ERWindowName.value = GetWindowName();
		if (!ContainsPageStr(document.Map.action))
		{
			document.Map.action = AppendWindowContextToQueryString(document.Map.action, GetWindowName());
		}
	}

	if (typeof(document.Items) != "undefined")
	{
		document.Items.ERWindowName.value = GetWindowName();
		if (!ContainsPageStr(document.Items.action))
		{
			document.Items.action = AppendWindowContextToQueryString(document.Items.action, GetWindowName());
		}
	}

	if (typeof(document.MouseCommands) != "undefined")
	{
		document.MouseCommands.ERWindowName.value = GetWindowName();
		if (!ContainsPageStr(document.MouseCommands.action))
		{
			document.MouseCommands.action = AppendWindowContextToQueryString(document.MouseCommands.action, GetWindowName());
		}
	}

	return false;
}

//**************************Page Functions**************************************
// This code was generated in line on the pages

// Clear all BodyForm checkboxes containing the specified text
function ClearBodyFormCheckboxes(idPrefix)
{
	for(var i=0; i < document.BodyForm.elements.length; i++)
	{
		if (document.BodyForm.elements[i].type == "checkbox")
		{
			if ( document.BodyForm.elements[i].name.indexOf(idPrefix) >= 0)
			{
				document.BodyForm.elements[i].checked = false;
			}
				
		}
	}
}

	function BodyFormCheckAll()
	{
		var bIsCheckBox;
		for (var i=0;i < document.BodyForm.elements.length;i++)
		{
			bIsCheckBox = (document.BodyForm.elements[i].type=="checkbox");
			
			if (bIsCheckBox) 
			{
				
				if (document.BodyForm.elements[i].name)
				{
					if (document.BodyForm.elements[i].name.indexOf(kAllGroupID) != 0)
					{
						document.BodyForm.elements[i].checked= bBodyFormCheckAll;
					}
				}
			}
		}
		
		bBodyFormCheckAll = !bBodyFormCheckAll;
		if (!bBodyFormCheckAll)
		{
			//	special case code for DlgChooseMembers
			if (document && document.BodyForm && document.BodyForm.AccessControlScope)
				document.BodyForm.AccessControlScope[2].checked = "on";
		}
		return false;
	}

	function ItemsCheckAll()
	{
		var bHasCheckedProperty;
		for (var i=0;i < document.Items.elements.length;i++)
		{
			bHasCheckedProperty = new String( typeof(document.Items.elements[i].checked) );
			if (bHasCheckedProperty == "boolean") 
			{
				document.Items.elements[i].checked= bItemsCheckAll;
			}
		}
		bItemsCheckAll = !bItemsCheckAll;
		return false;
	}

	function ScrollToComment()
	{
		var i = 0;
		for(; i < document.anchors.length; i++)
		{
			if ( document.anchors[i].name == "firstunread")
			{
				if (IsNS && version < 5)
					window.scrollTo(0, document.anchors[i].y );
				else
				{
					var yOffset = 0;
					var ref;
					
					ref = document.anchors[i].offsetParent;
					yOffset = document.anchors[i].offsetTop;
					while( ref )
					{
						yOffset = yOffset + ref.offsetTop;
						ref = ref.offsetParent;
					}
					window.scrollTo(0, yOffset);
				}
				break;
			}
		}
		
		return false;
	}

	function UnreadHook()
	{
		if (bScrollToFirstUnread)
		{
			ScrollToComment();
		}
	}

	// function is used by the large member ui to keep the radio button in synch with the text box focus
	function SelectMemberOrGroup(bPeople)
	{
		if(bPeople)
			document.BodyForm.LookType[0].checked="on";
		else
			document.BodyForm.LookType[1].checked="on";

	}


//**************************Date Picker**************************************
// The following code is used by the popup date picker.

//***************************Window Management Functions**********************************
// Window Management functions
function InitWindow()
{
	if ((window.name.indexOf("eRw") != 0 && window.name != ""))
	{
		var LastWindowName = window.name;
		// if the window name is on the querystring, grab it from there
		var wQString = "&ERWindowName=";
		var pos = window.location.href.indexOf(wQString);
		if (pos != -1)
		{
			var start = pos + wQString.length;
			var end = window.location.href.indexOf("&", start);
			var value = 0;
			if (end == -1)
				window.name = window.location.href.substring(start, window.location.href.length)
			else
				window.name = window.location.href.substring(start, end);
		}
		else if(document.BodyForm && document.BodyForm.ERWindowName && document.BodyForm.ERWindowName.value)
		{
			// the window name isn't correct and we don't have it on the query string
			// get it from the bodyform
			window.name=document.BodyForm.ERWindowName.value;
		}
	}
}

function GetParameter (str, param)
{
	// Get the value of the param in the string
	var pos = str.indexOf(param);
	if (pos != -1)
	{
		var start = pos + param.length;
		var end = str.indexOf("&", start);
		start = start + 1;
		if (end == -1)
			return str.substring(start, str.length)
		else
			return str.substring(start, end);
	}
}

function ClearWindowName()
{
	window.name="Unnamed";
	
	// could also append the old window name to 
	// a form field so that we can clean up old window sessions

	// this should be done so that we can more acurately invalidate sessions
}

function AppendWindowContextToQueryString(theURL, windowName)
{
	var retURL = "";
	if (theURL.indexOf("ERWindowName") == -1)
	{
		if (!ContainsPageStr(theURL))
		{
			if (theURL.indexOf("?") == -1)
				retURL = "?";
			else
				retURL = "&";
			
			retURL = retURL + "ERWindowName=" + windowName;
		}
		retURL = theURL + retURL;
	}
	else
	{
		// if the window name is on the querystring, replace it
		var wQString = "&ERWindowName=";
		var pos = theURL.indexOf(wQString);
		if (pos != -1)
		{
			var start, end, thePattern;
			start = pos + wQString.length;
			end = theURL.indexOf("&", start);
			if (end == -1)
				end = theURL.length;

			// replace querystring parameters
			thePattern = eval("/ERWindowName=" + theURL.substring(start, end) + "/gi");
			retURL = theURL.replace(thePattern, "ERWindowName=" + windowName);

			// replace querystring parameters embedded in other querystring parameters
			thePattern = eval("/ERWindowName%3D" + theURL.substring(start, end) + "/gi");
			retURL = retURL.replace(thePattern, "ERWindowName%3D" + windowName);
		}
	}

	if (theURL.indexOf("ERClickInMap") == -1)
	{
		if (theURL.indexOf("?") == -1)
			retURL = "?";
		else
			retURL = "&";
		
		retURL = retURL + "ERClickInMap=" + (gClickInMap ? "TRUE" : "FALSE");
		retURL = theURL + retURL;
	}
	
	return retURL;
}

function GetWindowName()
{
	InitWindow();
	return window.name;
}

function AppendCommand(theURL, command, param1, param2, param3, selectedItemDocID, sessionKey)
{
	var retURL = theURL;
		
	if (ContainsPageStr(retURL))
		return retURL;

	if ( retURL.indexOf("&command=") != -1)
		return retURL;

	if (retURL.indexOf("?") == -1)
		retURL = retURL + "?";
	else
		retURL = retURL + "&";

	retURL = retURL + "command=" + command;
	
	if (param1.length > 0)
		retURL = retURL + "&param1=" + param1;
	if (param2.length > 0)
		retURL = retURL + "&param2=" + param2;
	if (param3.length > 0)
		retURL = retURL + "&param3=" + param3;  

	if (selectedItemDocID.length > 0)
		retURL = retURL + "&SelCount=1&SelID=" + selectedItemDocID
		
	retURL = retURL + "&SessionKey=" + sessionKey

	return retURL;
}

function AppendPopUpContext(LinkHref)
{
	var addParam = LinkHref.indexOf("InPopUpWindow=TRUE");
	var hasQuestionMark = LinkHref.indexOf("?", 0);
	var retVal;
	retVal = LinkHref
	if (addParam == -1)
	{
		if (hasQuestionMark == -1)
			retVal = retVal + "?InPopUpWindow=TRUE&ERParentWindow=" + GetWindowName();
		else
			retVal = retVal + "&InPopUpWindow=TRUE&ERParentWindow=" + GetWindowName();
	}
	return retVal;
}

function launchPopUp(link, width, height, useScrollbars)
{
	var linkHref;
	if (typeof(link) == "object")
		linkHref = link.href;
	else
		linkHref = link;

	var onLine = true;
	if (typeof(navigator.onLine) != "undefined" &&
		navigator.onLine == false)
	{
		onLine = false;
	}
	linkHref = AppendPopUpContext(linkHref)
	var value = new Date();      
	var subdlgName = "eRw" + value.getTime();
	
	// Append the URL information if it isn't already there.
	// Sometimes the info can alread be there if a popup window was already launched
	// and the page hasn't Refreshed.

	linkHref = AppendWindowContextToQueryString(linkHref, subdlgName);

	var subdialog;

	var upperX, upperY, browserProps;

	browserProps = "location=no,resizable=yes,toolbar=no,menubar=no,height=" + height +",width=" + width + ",scrollbars=";
	if (useScrollbars)
		browserProps = browserProps + "yes";
	else
		browserProps = browserProps + "no";

	if (!IsNS)
	{
		upperX = Math.floor( (window.screen.width - width)/2 );
		upperY = Math.floor( (window.screen.height - height)/3 );
		browserProps = browserProps + ",left=" + upperX + ", top=" + upperY;
	}
	else
	{
		upperX = Math.floor( window.screenX + (window.outerWidth - width)/2 );
		upperY = Math.floor( window.screenY + (window.outerHeight - height)/3 );
		browserProps = browserProps + ",screenX=" + upperX + ",screenY=" + upperY;
	}

	subdialog = launchBrowser( linkHref, subdlgName, browserProps);

	// This is a hack to close the popup window if the user chose "Stay Offline".
	// It would be better to force the "do you want to go online" question to be
	// asked before opening the popup window, so that we could skip the popup
	// entirely if the user said no.  But I couldn't figure out a way to do that.
	var onLine = true;
	if (typeof(navigator.onLine) != "undefined" &&
		navigator.onLine == false)
	{
		onLine = false;
	}
	if (!onLine)
		subdialog.close();

	return false;
}

function launchDialogInPlace(windowURL)
{
	window.location.href = AppendWindowContextToQueryString(windowURL, GetWindowName());
}

function launchBrowser(link, windowName, browserProps)
{
	var linkHref;
	var newBrowser;

	if (typeof(link) == "object")
	{
		linkHref = link.href;
	}
	else
	{
		linkHref = link;
	}

	// If you pass an empty browser properties string in IE, 
	// then IE has reasonable defaults in terms of what it will show
	// (eg. toolbar, menubar, etc. will show by default). If you
	// pass an empty string in Netscape, it will default to 
	// showing nothing (no toolbar, no status bar, etc.). 
	// To get around this, in Netscape, if you don't pass anything in the
	// window.open call then it will open with the toolbar, menubar,
	// etc.
	
	if (typeof(windowName) == "undefined")
	{
		windowName = "";
	}
	
	if (typeof(browserProps) == "undefined")
	{
		browserProps = "";
	}
	
	if ((windowName == "") && (browserProps == ""))
	{
		newBrowser = window.open(linkHref);
	}
	else if ((windowName != "") && (browserProps == ""))
	{
		newBrowser = window.open(linkHref, windowName);
	}
	else if ((windowName == "") && (browserProps != ""))
	{
		newBrowser = window.open(linkHref, "", browserProps);
	}
	else
	{
		// All parameters supplied.
		newBrowser = window.open(linkHref, windowName,  browserProps);
	}

	return newBrowser;
}

// Launch the file with objID specified - use the plugin if it exists
function LaunchFile(objID)
{
	if (UsePlugin)
	{
		// get the corresponding image item since the execute command wants
		// an object
		for (var i = document.images.length - 1; i >=0; i--) 
		{
			testObj = document.images[i]
			if (objID == testObj.name.substr(3))
			{
				menuItem = testObj;
				break;
			}
		}

		var command = "ViewFileItem";
		if (IsMeetingSharePane)
		{
		//	does this path ever get used? -mpw
			if (!TestShareFile(CanPresent(menuItem.name)))
				return false;

			if (CanPresent(menuItem.name))
			{
				UploadPresention(menuItem.name.substr (3));
				return false;
			}
			command = "ViewShareFileItem";
		}
		else if (HasPreview(menuItem.name))
		{
			command = "PreviewItem";
		}

		ExecuteCommand(command)
		return false;
	}

	return true;
}

function Preview (objID)   // for click handlers
{
	return SubmitCommand("Items", "PreviewItem", "", "", "", objID);
}


function isParentWindowOpen()
{
	var bParentOpen = false;

	if (IsNS)
	{
		// In Netscape, window.opener.closed works properly.
		if (window.top.opener.closed)
		{
			bParentOpen = false;
		}
		else
		{
			bParentOpen = true;
		}
	}
	else
	{
		// In IE, window.opener.closed always returns false, so we
		// have to do a different check to determine whether the parent
		// window is still open.
		if ( typeof(window.top.opener) == "undefined" ) 
		{
			bParentOpen = false;
		}
		else if ( ( typeof(window.top.opener.location) == "undefined" ) || ( typeof(window.top.opener.location) == "unknown" ) )
		{
			bParentOpen = false;
		}
		else if ( typeof(window.top.opener.location.href) == "unknown")
		{
			bParentOpen = false;
		}
		else
		{
			bParentOpen = true;
		}
	}

	return bParentOpen;
}

isLoaded = false;

var MenuCreatedArray = new Array();
for(i=0; i < NumMenuItems; i++) 
{
	MenuCreatedArray[i]=false;
}

if (!window.imgHspace) imgHspace=0;

function initVars() 
{
	isOverMenu = false;
	currentMenu = null;
}

initVars();

function MenuMouseOver() {isOverMenu = true;}
function MenuMouseOut() {isOverMenu = false;status = "";}
function MenuSelectStart() {return false;}

var currentKBMenuItem = null;
function MenuOnKeyDown(evt)
{
	if (!MenuOnDisplay)
		return;
		
	evt = EventSetup( evt )
	
	if (evt.keyCode == 27) //ESC
	{
		if (currentKBMenuItem)
			currentKBMenuItem.onmouseout();
		hideAll();
		if (menuItem)
			// need to set focus back to element that started menu up
			menuItem.parentNode.focus()
	}
	else if (evt.keyCode ==  9)   //Tab
	{
		// don't let menu lose focus
		EventStopPropagation( evt )
		return false;
	}
	else if (evt.keyCode == 40) // down arrow
	{
		if (!currentKBMenuItem)
			currentKBMenuItem = this.firstChild;
		else
		{
			currentKBMenuItem.onmouseout();
			if (currentKBMenuItem.nextSibling)
				// get next menu item
				currentKBMenuItem = currentKBMenuItem.nextSibling;
			else
				// start at top of menu
				currentKBMenuItem = this.firstChild;
		}
		currentKBMenuItem.onmouseover();
		EventStopPropagation( evt )
		return false;
	}
	else if (evt.keyCode == 38) // up arrow
	{
		if (!currentKBMenuItem)
			currentKBMenuItem = this.lastChild;
		else
		{
			currentKBMenuItem.onmouseout();
			if (currentKBMenuItem.previousSibling)
				// get previous menu item
				currentKBMenuItem = currentKBMenuItem.previousSibling;
			else
				// start at bottom of menu
				currentKBMenuItem = this.lastChild;
		}
		currentKBMenuItem.onmouseover();
		EventStopPropagation( evt )
		return false;
	}
	else if (evt.keyCode == 13) // ENTER!
	{
		if (currentKBMenuItem)
			currentKBMenuItem.onmouseup();
	}
	return true;
}

function StopMovementKeys( evt )
{
	// suppress the up/down arrows so browser window doesn't scroll
	// while user is navigating the pop-up menu
	
	// suppres tab so focus stays on menu
	evt = EventSetup( evt )
	
	if ((evt.keyCode == 40) || // down arrow
		(evt.keyCode == 38) || // up arrow
		(evt.keyCode ==  9))   //Tab
	{
		EventStopPropagation( evt )
		return false;
	}
	else
		return true;
}

function makeMenu(menuCount)
{
	isLoaded = false;

	//	prevent right-click from coming up
	window.document.onmousedown = OnMouseDown

	//	theMenu is the background, and border of the menu
	theMenu = MakeLayer (eRoomMenuName + menuCount, window);

	theMenu.onmouseover = MenuMouseOver;
	theMenu.onmouseout = MenuMouseOut;
	theMenu.onkeydown = MenuOnKeyDown;
	theMenu.onkeypress = StopMovementKeys;
	theMenu.onkeyup = StopMovementKeys;
	theMenu.KeepInWindow = KeepInWindow;
	theMenu.EnableChoices = EnableChoices;
	theMenu.className = "contextmenu";
	theMenu.onselectstart = MenuSelectStart;

	for (i=0; i< NumMenuItems; i++)
	{
		if (MenuChoicesArray[i])
		{
			AddMenuItem(theMenu, MenuArray[i], menuCount);
			isLoaded = true;
		}
	}

	if (theMenu.clip)
		theMenu.clip.bottom = theMenu.nextMenuEntryTop + MenuBorderMargin;
}

// Get Preview version of menu given file non-preview menu
function GetPreviewMenuID(menuId)
{
	var newID = '';
	if (menuId==FileMenu)
		newID=FileMenu_Preview;
	else if(menuId==VersionedFileMenu)
		newID=VersionedFileMenu_Preview;
	else if(menuId==CompanionFileMenu)
		newID=CompanionFileMenu_Preview;
	else if(menuId==VersionedCompanionFileMenu)
		newID=VersionedCompanionFileMenu_Preview;
	else if(menuId==MapVersionedFileMenu)
		newID=MapVersionedFileMenu_Preview;
	else if(menuId==MeetingShareFileMenu)
		newID=MeetingShareFileMenu_Preview;
	else if(menuId==MeetingSharePresentFileMenu)
		newID=MeetingSharePresentFileMenu_Preview;
	else if(menuId==DMFileMenu)
		newID=DMFileMenu_Preview
	else
		newID=menuId;  // give then they original

	return newID;
}

// dlm: get rid huge if/else. Calculate menu index from letter
function GetMenuIndexFromMenuID(menuID)
{
	var menuChar = menuID.charAt(0);
	var iIndex;
	
	if (menuChar.toUpperCase( ) == menuID.charAt(0))
	{
		// upper case
		iIndex = menuChar.charCodeAt(0) - "A".charCodeAt(0);   // calculate letter offset (A==0)
	}
	else
	{
		// it's lower case
		menuChar = menuID.charAt(0);
		iIndex = menuChar.charCodeAt(0) - "a".charCodeAt(0) + 26;   // calculate letter offset (A==0)
	}

	return iIndex;
}

function popUpXY(menuID,x,y, InMap, bHasPreview)
{
	var iIndex = GetMenuIndexFromMenuID(menuID);
	if (bHasPreview)    // Has Preview: Get the "preview" version's index instead.
		iIndex = GetMenuIndexFromMenuID(GetPreviewMenuID(menuID));

	xClient = x; // Save client coordinates
	yClient = y;

	xPos = (IsNS) ? x : (x + document.body.scrollLeft);
	yPos = (IsNS) ? y : (y + document.body.scrollTop);


	if (!MenuCreatedArray[iIndex])
	{
		makeMenu(iIndex);

		if (isLoaded)
			MenuCreatedArray[iIndex] = true;
		else
			return;
	}

	popMenu(eRoomMenuName + iIndex, xPos, yPos);
}

function ShiftTo(currentMenu, xPos, yPos) 
{
	if (currentMenu.style)
	{
		currentMenu.style.left = xPos;
		currentMenu.style.top = yPos;
	}
	else
	{
		currentMenu.left = xPos;
		currentMenu.top = yPos;
	}

	currentMenu.KeepInWindow();
}

function popMenu(menuName, xPos, yPos)
{
	if (!isLoaded)
		return true;

	hideAll();

	CanEditItem = false; // this needs to figured out for real

	if (document.layers)    // Netscape 4
		document.releaseEvents(Event.MOUSEUP);

	currentMenu = GetMenuFromName(menuName);

	if (currentMenu)
	{
		currentMenu.EnableChoices(CanEditItem);

		if (currentMenu.style)
			currentMenu.style.visibility = visible;
		else
			currentMenu.visibility = visible;

		ShiftTo(currentMenu, xPos, yPos)
	
		if (IsIE)
			currentMenu.focus();
		else
			currentMenu.firstChild.focus();
	}

	MenuOnDisplay = true;
	return false;
}

function hideAll() 
{
	for(i=0; i < NumMenuItems; i++) 
	{
		if (MenuCreatedArray[i])
		{
			currentMenu = GetMenuFromName(eRoomMenuName + i);
			
			if (currentMenu)
			{
				if (currentMenu.style)
					currentMenu.style.visibility = hidden;
				else
					currentMenu.visibility = hidden;
			}
		}
	}
	MenuOnDisplay = false;
	if (currentKBMenuItem)
	{
		currentKBMenuItem.onmouseout()
		currentKBMenuItem = null;
	}
    if (IsNS)
        document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP)
}

function CloseWindowIfOffline(theWindow)
{
	if (typeof(navigator.onLine) == 'undefined' || navigator.onLine)
		return;
	theWindow.close();
}

function HandleIntercomSubmit()
{
	window.top.frames[1].document.commentform.message.value = window.top.frames[2].document.commentform.message.value; 
	window.top.frames[2].document.commentform.message.value = "";
	// clear the window name for the frame we are submitting, so that we
	// do not poll this window in IntercomHidden.asp until it reloads successfully
	// in order to avoid race conditions and JS errors
	window.top.frames[1].name = '';
	window.top.frames[1].document.commentform.submit();
	return false;
}

function InitWriteInHandler()
{
	// register event callbacks
	if (IsNS)
		document.captureEvents(Event.KEYUP);

	document.onkeyup = ERWriteUpKeyHandler;
}

function ERWriteUpKeyHandler(evt)
{
	evt = EventSetup( evt );

	var Target = evt.target
	var eventName = Target.name;

	if ((typeof(eventName) != "undefined"))
	{
		if (eventName == "SearchFName" ||
			eventName == "SearchLName" ||
			eventName == "SearchOrg" ||
			eventName == "SearchEmail")
		{
			if (Target.value != "")
				document.BodyForm.SearchType[0].checked=true;
		}
		else if (eventName == "SearchGroup")
		{
			if (Target.value != "")
				document.BodyForm.SearchType[1].checked=true;
		}
		else if (eventName == "NewLoginName")
		{
			if (Target.value != "")
				document.BodyForm.LoginConflict[1].checked=true;
		}
		else if (eventName == "RPSPort")
		{
			// Server settings page, reverse proxy port edit box.
			if (document.BodyForm.RPSPort.value != "")
			{
				document.BodyForm.ReverseProxy.checked=true;
				document.BodyForm.RPSUsesNonstandardPort.checked=true;
			}
			else
			{
				document.BodyForm.RPSUsesNonstandardPort.checked=false;
			}
		}
		else if (eventName == "PortNumber")
		{
			// Server settings page, reverse proxy port edit box.
			if (document.BodyForm.PortNumber.value != "")
			{
				document.BodyForm.UseRevProx.checked=true;
				document.BodyForm.RevProxUseNonStdPort.checked=true;
			}
			else
			{
				document.BodyForm.RevProxUseNonStdPort.checked=false;
			}
		}
	}
}

function ReverseProxyChecked(checkBoxName)
{
	// This function is called from the server settings
	// page. It handles auto checking and clearing of
	// various controls for the reverse proxy settings.
	obj = eval("document.BodyForm." + checkBoxName);

	if (checkBoxName == "ReverseProxy")
	{
		if (obj.checked)
		{
			document.BodyForm.UseAlias.checked = true;
			document.BodyForm.UseAlias.disabled = true;

			document.BodyForm.RPSUsesSSL.disabled = false;
			document.BodyForm.RPSUsesNonstandardPort.disabled = false;
		}
		else
		{
			document.BodyForm.UseAlias.checked = false;
			document.BodyForm.UseAlias.disabled = false;

			document.BodyForm.RPSUsesSSL.checked=false;
			document.BodyForm.RPSUsesSSL.disabled = true;

			document.BodyForm.RPSUsesNonstandardPort.checked=false;
			document.BodyForm.RPSUsesNonstandardPort.disabled = true;

			document.BodyForm.RPSPort.value="";
		}
	}
	else if (checkBoxName == "RPSUsesNonstandardPort")
	{
		if (obj.checked)
		{
			// Do nothing.
		}
		else
		{
			// Clear the port number.
			document.BodyForm.RPSPort.value="";
		}
	}
}

function CreateDocHandler(checkBoxName, bDisableLinkToDM, bDisableTrackVersionsCheckBox)
{
	// This function is called from the create document
	// page. It handles auto checking and clearing of
	// various controls for the Documentum settings.
	
	// radio buttons:
	// FromDesktop: Upload a file from my computer
	// FromDM: Add a file from the Content Server
	// CreateNewDoc: Create a new file in eRoom
	
	// check boxes:
	// TrackVersions
	// LinkToDM
	// UploadSeveral
	// ReleaseLock
	
	var obj;
	obj = eval("document.BodyForm." + checkBoxName);

	if (checkBoxName == "LinkToDM")
	{
		var IsDisabled = false;
		if ( (typeof(obj) != "undefined") && obj.checked)
		{
			IsDisabled = true;
		}
		var cnd = document.getElementById('CreateNewDoc');
		if ( (cnd != null) && (typeof(cnd.checked) != "undefined") && cnd.checked)
		{
			if ( (typeof(obj) != "undefined") && obj.checked)
			{
				if (typeof(document.BodyForm.TrackVersions) != "undefined")
				{
					document.BodyForm.TrackVersions.checked=true;
					document.BodyForm.TrackVersions.disabled=IsDisabled;
				}
				if (typeof(document.BodyForm.UploadSeveral) != "undefined")
				{
					document.BodyForm.UploadSeveral.checked=false;
					document.BodyForm.UploadSeveral.disabled=IsDisabled;
				}
			}
			else
			{
				if (typeof(document.BodyForm.TrackVersions) != "undefined")
					document.BodyForm.TrackVersions.disabled=IsDisabled;
			}
		}
		else
		{
			if (typeof(document.BodyForm.TrackVersions) != "undefined")
				document.BodyForm.TrackVersions.disabled=IsDisabled;
			if (typeof(document.BodyForm.UploadSeveral) != "undefined")
				document.BodyForm.UploadSeveral.disabled=IsDisabled;
		}
	}
	else 
	{
		if (checkBoxName == "FromDesktop" || checkBoxName == "AddNewDoc")
		{
			if (checkBoxName == "AddNewDoc")
			{
				if (typeof(document.BodyForm.TrackVersions) != "undefined")
					document.BodyForm.TrackVersions.disabled=false;
				if (typeof(document.BodyForm.LinkToDM) != "undefined")
					document.BodyForm.LinkToDM.disabled=false;
				document.BodyForm.Filedata.disabled=true;
			}
			else
				document.BodyForm.Filedata.disabled=false;
	
			if (typeof(document.BodyForm.TrackVersions) != "undefined" && checkBoxName == "FromDesktop")
			{
				if (bDisableTrackVersionsCheckBox == " DISABLED")
					document.BodyForm.TrackVersions.disabled=true;
				else
					document.BodyForm.TrackVersions.disabled=false;
			}			
			if (typeof(document.BodyForm.UploadSeveral) != "undefined")
			{
				if (checkBoxName == "AddNewDoc")
				{
					document.BodyForm.UploadSeveral.disabled=true;
					document.BodyForm.UploadSeveral.checked=false;
				}
				else
					document.BodyForm.UploadSeveral.disabled=false;
			}
			if (checkBoxName == "AddNewDoc")
				return;
				
			var obj;
			obj = eval("document.BodyForm.LinkToDM");
			if (typeof(obj) != "undefined")
			{
				if (!obj.checked)
				{
					if (typeof(document.BodyForm.TrackVersions) != "undefined")
					{
						if (bDisableTrackVersionsCheckBox == " DISABLED")
							document.BodyForm.TrackVersions.disabled=true;
						else
							document.BodyForm.TrackVersions.disabled=false;
					}
				}
				if (typeof(document.BodyForm.LinkToDM) != "undefined")
				{
					if (bDisableLinkToDM == "True")
						document.BodyForm.LinkToDM.disabled=true;
					else
						document.BodyForm.LinkToDM.disabled=false;
				}
				if (typeof(document.BodyForm.BrowseBtn) != "undefined")
				{
					document.BodyForm.BrowseBtn.disabled=true;
					document.BodyForm.Filedata.disabled=false;
					document.BodyForm.TargetPath.disabled=true;
				}
			}
		}
		else
		{
		//	checkBoxName == "FromDM"
			if (typeof(document.BodyForm.TrackVersions) != "undefined")
			{
				document.BodyForm.TrackVersions.disabled=true;
				document.BodyForm.TrackVersions.checked=true;
			}
			if (typeof(document.BodyForm.LinkToDM) != "undefined")
			{
				document.BodyForm.LinkToDM.disabled=true;
				document.BodyForm.LinkToDM.checked=true;
			}
			if (typeof(document.BodyForm.UploadSeveral) != "undefined")
			{
				document.BodyForm.UploadSeveral.disabled=true;
				document.BodyForm.UploadSeveral.checked=false;
			}
			if (typeof(document.BodyForm.BrowseBtn) != "undefined")
			{
				document.BodyForm.BrowseBtn.disabled=false;
				document.BodyForm.Filedata.disabled=true;
				document.BodyForm.TargetPath.disabled=false;
			}
		}
	}
}


// If a user checks a keyword, then make select
// the 'Any of the following' radio button.
function MultiChoiceKeywordCheckBoxSelected()
{
	var rbAnyOfTheFollowing;
	var rbAllOfTheFollowing;

	rbAnyOfTheFollowing = GetAnyOfTheFollowingRadioButton();
	rbAllOfTheFollowing = GetAllOfTheFollowingRadioButton();

	if ((rbAnyOfTheFollowing.checked) || (rbAllOfTheFollowing.checked))
	{
		// If either the 'Any of the following' or 'All of the following'
		// checkboxes are checked, then do nothing.
	}
	else
	{
		rbAnyOfTheFollowing.checked = true;
	}

	return false;
}

// If the user checks the 'Any', 'None' or 'All'
// radio button, then uncheck any keyword
// choices that may have been selected.
function MultiChoiceKeywordRadioButtonSelected()
{
	var rbAnyOfTheFollowing;
	var rbAllOfTheFollowing;

	rbAnyOfTheFollowing = GetAnyOfTheFollowingRadioButton();
	rbAllOfTheFollowing = GetAllOfTheFollowingRadioButton();

	if ((rbAnyOfTheFollowing.checked) || (rbAllOfTheFollowing.checked))
	{
		// If either the 'Any of the following' or 'All of the following'
		// checkboxes are checked, then do nothing.
	}
	else
	{
		var bIsCheckBox;
		for (var i=0;i < document.BodyForm.elements.length;i++)
		{
			bIsCheckBox = (document.BodyForm.elements[i].type=="checkbox");
			if (bIsCheckBox) 
			{
				// Uncheck all keyword checkboxes.
				document.BodyForm.elements[i].checked = false;
			}
		}
	}

	return false;
}

function GetAnyOfTheFollowingRadioButton()
{
	// The 'Any of the following' radio button is the 3rd element in the radio
	// button array. If the order of the radio buttons change, then the index
	// in the function must be changed.
	var rbAnyOfTheFollowing;

	rbAnyOfTheFollowing = document.BodyForm.RadioChoices[3];

	return rbAnyOfTheFollowing;
}

function GetAllOfTheFollowingRadioButton()
{
	// The 'All of the following' radio button is the 4th element in the radio
	// button array. If the order of the radio buttons change, then the index
	// in the function must be changed.
	var rbAllOfTheFollowing;

	rbAllOfTheFollowing = document.BodyForm.RadioChoices[4];

	return rbAllOfTheFollowing;
}

function MemberCheckBoxSelected(mbrPrefix, MemberId)
{
	var i=0;
	if (document.BodyForm.RadioButtons)
	{
		while(typeof(document.BodyForm.RadioButtons[i]) != "undefined" )
		{
			if (document.BodyForm.RadioButtons[i].value.indexOf("List") != -1 ||
				document.BodyForm.RadioButtons[i].value.indexOf("(adminplus)") != -1)
			{
				document.BodyForm.RadioButtons[i].checked = "on";
				break;
			}
			i++;
		}
	}


	var cmd;
	var bUndefinedCtrl;
	
	cmd = "typeof(document.BodyForm.s" + MemberId + ");";
	if (eval(cmd) == "undefined")
		return true; // only link checkbox values if the selected member checkbox exists


	if (MemberId.indexOf("-1") != -1)
	{
		var id1, id2;
		if (mbrPrefix == "s")
		{
			id1 = "s-1";
			id2 = "-1";
		}
		else
		{
			id1 = "-1";
			id2 = "s-1";
		}

		var i2;
		for (i = 0; i < document.BodyForm.elements.length - 1; i++)
		{
			var bChecked;
			if (document.BodyForm.elements[i].name == id1)
			{
				bChecked = document.BodyForm.elements[i].checked;
				for (i2 = 0; i2 < document.BodyForm.elements.length - 1; i2++)
				{
					if (document.BodyForm.elements[i2].name == id2)
						document.BodyForm.elements[i2].checked = bChecked;
				}			
			}
		}
		return true;
	}
	
	var bFound;	
	for (i = 0; i < document.BodyForm.elements.length - 1; i++)
	{
		if (document.BodyForm.elements[i].name == MemberId)
		{
			if (mbrPrefix == "s")
			{
				cmd = "document.BodyForm.s" + MemberId + ".checked;";
				if ( eval(cmd) )
					document.BodyForm.elements[i].checked = true;
				else
					document.BodyForm.elements[i].checked = false;
			}
			else
			{
				if (document.BodyForm.elements[i].checked)
					cmd = "document.BodyForm.s" + MemberId + ".checked = true;"
				else
					cmd = "document.BodyForm.s" + MemberId + ".checked = false;"

				eval(cmd);
			}
			break;
		}
	}

	return true;
}

function ViewRow(docID)
{
	document.BodyForm.action = AppendCommand(document.BodyForm.action, "ViewItem", "", "", "", docID, document.Items.SessionKey.value);
	document.BodyForm.submit();
	return false;
}

function ObjectIsRecycleBin(object)
{
	if (object && typeof(object.name) != "undefined" && object.name.substr(0,1) == "I")
		return true;
	else
		return false;
}

function ObjectCanBeDragged(object)
{
	if (IsApprovalStepName(object.name))
		return false;

	return !ObjectIsRecycleBin(object);
}

function repErr(x)
{
	if (repErrInit)
	{
	    x = gURLPrefix + x; // Relative URL won't work here.
	    
		with( document )
		{
			open();
			write('<html><head><title>eRoom</title></head><frameset rows="100,0" frameborder=no><frame src="',x,'"></frameset></html>');
			close();
		}
	}
}

function dpLaunchDatePicker(sDateFieldName, sDateImgName, sWeekStartDay)
{
	// Set up an absolute URL here. Cannot use a relative URL
	// because, unlike IE, Netscape will not use the value in the 
	// base tag to prefix the relative URL.
	sURL =	gURLPrefix + 
			"/" + 
			gDialogRoot + 
			"DatePicker.asp?dialogRoot=" + gDialogRoot + 
			"&dateFieldName=" + sDateFieldName + 
			"&dateImgName=" + sDateImgName + 
			"&weekStartDay=" + sWeekStartDay + 
			"&monthsOfYear=" + monthsOfYear + 
			"&daysOfWeek=" + daysOfWeek + 
			"&dateFormat=" + sDateFormat;

	// Function to launch date picker.
	// sDateFieldName is the name of the text field into which
	// the date will be set.
	// sImgDateName is the name of the image of which the x, y
	// coordinates are used to calculate where to place the
	// date picker (Netscape only).
	var hDateTextControl;
	var iDatePickerX = 0;
	var iDatePickerY = 0;
	var sPosString = "";
	var bFound = false;
	var appVersion;

	// To enable right mouse click menu (to do a view source, for example), change
	// 'menubar=no' to 'menubar=yes'.
	var sFeatures = "location=no,resizable=yes,toolbar=no,menubar=no,scrollbars=no,status=no";

	// Determine x & y coordinates to draw calendar. For Netscape
	// use x & y coordinates of image passed to function. For IE
	// use the bounding rectangle of the date text field.
	if (IsNS)
	{
		// Include menubar height in x, y calculations.
		var iMenuBarHeight = window.outerHeight - window.innerHeight;

		iDatePickerX = window.document.images[sDateImgName].x + window.screenX;
		iDatePickerY = window.document.images[sDateImgName].y + window.screenY + iMenuBarHeight;

		sPosString = ',screenX=' + iDatePickerX + ',screenY=' + iDatePickerY;

		sFeatures += sPosString + ',width=175,height=175';
	}
	else
	{
		// To avoid looping, the form name could have been
		// passed to this function but in the spirit of loose 
		// coupling between the datepicker and the parent window,
		// this was not done. 
		// Looping could also be avoided by using the syntax
		// 'window.opener.document.all[sDateFieldName]', but the
		// (x, y) coordinates returned using this syntax are different 
		// from the ones returned by looping through all the forms.
		for (i = window.document.forms.length - 1; i >=0; i--)
		{
			for (j = window.document.forms[i].elements.length - 1; j >= 0; j--)
			{
				if (sDateFieldName == window.document.forms[i].elements[j].name)
				{
					// Found the edit control where the selected date will be displayed.
					hDateTextControl = window.document.forms[i].elements[j];
					bFound = true;
					break;
				}
			}

			if (bFound)
			{
				// Break out of outer loop.
				break;
			}
		}

		if (IsIEMac)
			rect = 0,0,0,0;
		else
			rect = hDateTextControl.getBoundingClientRect();

		iDatePickerX = rect.left;
		iDatePickerY = rect.bottom;

			iDatePickerX += window.screenLeft;
			iDatePickerY += window.screenTop;

		sPosString = ',left=' + iDatePickerX + ',top=' + iDatePickerY;
		sFeatures += sPosString + ',width=175,height=175';
	}

	window.open(sURL, sDateFieldName, sFeatures); 
}

function SetupPageMenuChoices(MenuID, InMap) 
{
	if (MenuID == RecycleBinMenu) 
	{
		if (!HasCoordinatorRights)
		{
			MenuChoicesArray [AccessControl] = false;
			MenuChoicesArray [EmptyRecycleBin] = false;
			MenuChoicesArray [ViewItem] = false;
			return;
		}
	}

	if (pageType == "RecycleBin")
	{
		if (!InMap) 
		{
			for (var i = 0; i < NumMenuItems; i++) 
				MenuChoicesArray [i] = false;

			MenuChoicesArray [DeleteItem] = true;
			MenuChoicesArray [CopyItem] = true;
			MenuChoicesArray [Restore] = true;
			return;
		}
	}

	for (var i = 0; i < NumMenuItems; i++)
		MenuChoicesArray [i] = true;

	if (pageType == "DatabaseTemplatesPage")
	{
		MenuChoicesArray[AddFile] = false;
		MenuChoicesArray[SaveSettings] = false;
	}

	if ((TCAPageType == FacilitySearchPage) || 
		(TCAPageType == RoomSearchPage))
	{
		MenuChoicesArray [SaveSettings] = false;
		MenuChoicesArray [PasteItem] = false;
		MenuChoicesArray [CreateItem] = false;
		MenuChoicesArray [AddFile] = false;
	}

	if (isVersionedFilePage && !InMap)
	{
		MenuChoicesArray [CreateItem] = false;
		MenuChoicesArray [AddFile] = false;
		MenuChoicesArray [CustomFields] = false;
		MenuChoicesArray [TrackVersions] = false;
		MenuChoicesArray [ShowVersions] = false;
		MenuChoicesArray [AccessControl] = false;
		MenuChoicesArray [Notification] = false;
		MenuChoicesArray [PublishToDocumentum] = false;
	}
	
	if (!showCustomFields)
		MenuChoicesArray [CustomFields] = false;

	if (!showPublishToDocumentum && (MenuID != DMFileMenu))
		MenuChoicesArray [PublishToDocumentum] = false;

	if (!showGoToDocumentum)
	{
		MenuChoicesArray [GoToDocumentum] = false;
		MenuChoicesArray [GoToDmProperties] = false;
	}

	if (bIsObserver)
	{
		MenuChoicesArray [EditItem] = false;
		MenuChoicesArray [EditFileItem] = false;
		MenuChoicesArray [RenameItem] = false;
		MenuChoicesArray [DeleteItem] = false;
		MenuChoicesArray [PasteItem] = false;
		MenuChoicesArray [PublishToDocumentum] = false;
	}

	if (isDiscussionPage)
	{
		MenuChoicesArray [CreateItem] = false;
		MenuChoicesArray [AddFile] = false;
	}
	else
		MenuChoicesArray [AddTopic] = false;
	
	if (IsSingleConnectedSet)
		MenuChoicesArray [CreateItem] = false;

	if (TCAPageType == ERUPage)
	{
		if (!CanAddTo)
		{
			if (!InMap)
			{
				if (IsMeetingsListPage)
				{
					MenuChoicesArray [DeleteItem] = false;
				}
					
				MenuChoicesArray [SaveSettings] = false;
				MenuChoicesArray [CutItem] = false;
				MenuChoicesArray [PasteItem] = false;
				MenuChoicesArray [CreateItem] = false;
				MenuChoicesArray [AddFile] = false;
				MenuChoicesArray [AddTopic] = false;
				MenuChoicesArray [CreateEvent] = false;
			}
		}
	}

	// Need the enhancement to share a file
	if (!gUseEnhanced)
		MenuChoicesArray [ShareFile] = false;

	// Can only share or enter meetings if the room allows meetings
	if (!IsUsingRTMeetingServer)
	{
		MenuChoicesArray [ShareFile] = false;
		MenuChoicesArray [EnterMeeting] = false;
	}
}

function ValidateClientControl()
{
	var ClientVersion = GetClientVersion(UsePlugin);

	if (ClientVersion == 0)
	{
		// Radar #47591
		// If version = 0 then plugin control is either not
		// installed or is disabled by IE's ActiveX Opt-in feature.
		//
		// If ShowInstallDlg is true, then the user has selected
		// thickclient via the choose client page that is displayed
		// when the client choice is not in the eRoom cookie. This
		// page is displayed before the login page.
		// If GoDirectlyToInstallDlg is true, then the user selected
		// to use the plugin via their My Members page. We no longer
		// go directly to the install page when GoDirectlyToInstallDlg
		// is true because the plugin may be installed but disabled by
		// the ActiveX Opt-in feature, so going to the install page
		// will try to install the plugin again. We go to the choose
		// client page instead so that if the plugin is disabled,
		// then the yellow information bar will be displayed which
		// will give the user the chance to enable the plugin.
		//if (ShowInstallDlg || GoDirectlyToInstallDlg)
		if (ShowInstallDlg)
		{
			repErr("/eRoomASP/Install.asp");
		}
		else
		{
			// We're here if the thickclient choice was in the cookie and
			// the plugin is not installed.
			repErr("/eRoomASP/DlgChooseClient2.asp?reason=NewInstall&frames=yes");
		}
		
		return false;
	}
	else if (ClientVersion < gMinPluginVersion)
	{
		if (GoDirectlyToInstallDlg)
			repErr("/eRoomASP/Install.asp");
		else
			repErr("/eRoomASP/DlgChooseClient2.asp?reason=UpgradeInstall&frames=yes");
		
		return false;
	}
	repErrInit = false;
	return true;
}

//function returns true if the input character is a number false otherwise or decimal point
function IsValidInputChar(decimalSeparator, theChar)
{
	if ((theChar >= '0' && theChar <= '9') || (theChar == decimalSeparator))
		return true;
	else
		return false;
}

//removes non-numeric characters from a string		
function parseInput(name, decimalSeparator)
{
	var sInput = new String("");
	var i = 0;
	while(name.charAt(i))
	{
		if (IsValidInputChar(decimalSeparator, name.charAt(i)) &&
		    (name.charAt(i) != decimalSeparator || sInput.indexOf(decimalSeparator) == -1 ))
			sInput += name.charAt(i);
	
		i++
	}
	return sInput;
}

// eRoom url names must be ASCII letters, numbers, '_', or '-'
function IsValidURLChar(theChar)
{
	return ((theChar >= 'a' && theChar <= 'z') ||
			(theChar >= 'A' && theChar <= 'Z') ||
			(theChar >= '0' && theChar <= '9') ||
			(theChar == '_')				   ||
			(theChar == '-')) ? true : false;
}

function GenerateURL (displayName)
{
	var urlName = new String("");
	
	var i = 0;

	while (displayName.charAt(i))
	{
		if (IsValidURLChar(displayName.charAt(i)))
			urlName += displayName.charAt(i);

		i++
	}

	return urlName;
}

function OnSelectProvisioningType(type)
{
	if (type == 1)
	{
		document.BodyForm.UseProvGroupsForCreation.disabled = false;
	}
	else
	{
		document.BodyForm.UseProvGroupsForCreation.checked = false;
		document.BodyForm.UseProvGroupsForCreation.disabled = true;
	}
	return true;
}

var numTries = 0;
function LoadNewSlidesIntoMeeting(closeWindowAfterLoad, redirURL, isIESun)
{
	numTries = 0
	window.setTimeout("LoadNewSlidesIntoMeeting2(" + closeWindowAfterLoad + ", '" + redirURL + "' , '" + isIESun + "' )", IsNS ? 500 : 10);
}

var previousSlideCount;
function LoadNewSlidesIntoMeeting2(closeWindowAfterLoad, redirURL, isIESun)
{
	var waitAmount = 10;

	// since different platforms are slower to loaded the applet, we customize the wait time
	if (IsNS || (isIESun.toLowerCase() == "true"))
	{
		waitAmount = 10000;
	}

	var originalSlideCount = document.applets.ExternalInfoApplet.getSlideCount()
	previousSlideCount = 0;
	window.setTimeout("LoadNewSlidesIntoMeeting3(" + originalSlideCount + "," + closeWindowAfterLoad + ", '" + redirURL +"' )", waitAmount);
}

function LoadNewSlidesIntoMeeting3(originalSlideCount, closeWindowAfterLoad, redirURL)
{
	document.applets.ExternalInfoApplet.loadNewSlides();
	window.setTimeout("WaitForSlidesToLoad(" + originalSlideCount + "," + closeWindowAfterLoad + ", '" + redirURL + "' )", IsNS ? 500 : 10);
}

function WaitForSlidesToLoad(originalSlideCount, closeWindowAfterLoad, redirURL)
{
	var done = false;

	var currentlyLoadedSlideCount = document.applets.ExternalInfoApplet.getSlideCount()
	if (originalSlideCount == currentlyLoadedSlideCount)
	{
	// 	nothing has loaded yet
	}
	else
	{
		if (previousSlideCount == 0)
		{
			previousSlideCount = currentlyLoadedSlideCount;
			// let's wait again, and see if any more slides load
		}
		else
		{
			if (previousSlideCount == currentlyLoadedSlideCount)
			{
				// it appears that no more slides are being loaded
				done = true;
			}
			else
			{
				previousSlideCount = currentlyLoadedSlideCount;
				// let's wait again, and see if any more slides load
			}
		}	
	}

	if (!done)
	{
		// keep waiting; slides have not yet loaded
		if (numTries < 20)
		{
			numTries++;
			window.setTimeout("WaitForSlidesToLoad(" + originalSlideCount + "," + closeWindowAfterLoad + ", '" + redirURL + "' )",500);
			return;
		}
		// we've waited long enough;
		// something is wrong, but don't get stuck in endless loop
	}

	// done waiting
	
	// the idea behind this waiting code is to wait for slides to load
	// before calling jumpToSlide.  Otherwise, the meeting pane is not
	// correctly activated and meeting window will remain blank
	document.applets.ExternalInfoApplet.jumpToSlide(originalSlideCount + 1)

	if (closeWindowAfterLoad)
	window.close();
	else
	{
		if (redirURL != "")
			window.location.replace( redirURL );
	}
}

// ---------------------------------------------------------------------
// borderOver
// UI animation: changes background images of eRoom map border and an adjacent cell
// ---------------------------------------------------------------------
function borderOver(bgImageMouseOver,feedbackCellId,bgImageMouseOverAdjacent){
	if (document.getElementById) {
		document.getElementById("mapBorder").style.backgroundImage="url('" + bgImageMouseOver + "')"; 
		document.getElementById(feedbackCellId).style.backgroundImage="url('" + bgImageMouseOverAdjacent + "')";
	}
}

// ---------------------------------------------------------------------
// borderDown
// UI animation: changes background color of eRoom map border
// ---------------------------------------------------------------------
function borderDown(bgColorMouseDown){
	if (document.getElementById) {
		document.getElementById("mapBorder").style.backgroundColor = bgColorMouseDown;
	}
}

// ---------------------------------------------------------------------
// borderCancel
// UI animation: restores border of eRoom map and adjacent cell to previous appearance
// ---------------------------------------------------------------------
function borderCancel(bgImage,bgColor,feedbackCellId){
	if (document.getElementById) {
		document.getElementById("mapBorder").style.backgroundImage="url('" + bgImage + "')"; 
		document.getElementById("mapBorder").style.backgroundColor = bgColor;
		document.getElementById(feedbackCellId).style.backgroundImage='none';
	}
}

// ---------------------------------------------------------------------
// eMouseOver and eMouseOut
// UI animation: used by buttons made via GenerateButton, InsertFunction, 
// InsertThinButton, InsertMapTab, InsertPresence 
// ---------------------------------------------------------------------
function eMouseOver(theButton, sClass){
	theButton.className=sClass;
}
function eMouseOut(theButton, sClass){
	if (gAllowButtonMouseOut){
		theButton.className=sClass;
	}
}

function OnChangeDateType()
{
	if (document.BodyForm.DateType.value == "any")
	{
		document.BodyForm.fromDate.value = "";
		document.BodyForm.toDate.value = "";
	}
}



// ---------------------------------------------------------------------

function ClickSubmitSettingsPage(curPageType, destPageType)
{
		if( (curPageType == ServerSettingsPage) || (curPageType == CommunitySettingsPage) || (curPageType == FacilitySettingsPage) 
										|| (curPageType == RoomSettingsPageFromRoom) ||  (curPageType == RoomSettingsPageFromFacility) )
		{	
			return ERBodyFormClickHandler("ClickSubmitSettingsPage" + destPageType);
			
		}
		else
		{
			return true;
		}

}

// ------------- add member dialog script -----------
// these methods are used to generate the initials and the login name
var ModifiedInitials
var ModifiedDisplayName
var DefaultDisplayName
var DefaultInitials
var ModifiedLoginName
var DefaultLoginName
var ModifiedDMLogin
var DefaultDMLogin

function ERCS_IsLetter(theChar)
{
	var retVal = true;
	
	if (theChar < 'A')
		retVal = false;
	else if (theChar > 'Z' && theChar < 'a')
		retVal = false;
	else if (theChar > 'z' && theChar < 128)
		retVal = false

	return retVal;
}

function ERCS_GenerateInitals(firstName, middleName, lastName)
{
	var initials = new String("");
	var allNames = new String("");
	var i = 0;
	var nextIsInitial = true;
	
	fullName = eval(gFirstName) + " " + middleName + " " + eval(gLastName);

	i=0;
	nextIsInitial = true;

	while (fullName.charAt(i))
	{
		if (ERCS_IsLetter(fullName.charAt(i)))
		{
			if (nextIsInitial)
			{
				initials += fullName.charAt(i);
				nextIsInitial = false;
			}
		}
		else
		{
			nextIsInitial = true;
		}
		i++;
	}

	return initials;
}

function ERCS_GenerateDisplayName(firstName, middleName, lastName)
{
	var displayName;

	displayName = eval(gFirstName);

	if (middleName.length)
	{
		if (displayName.length)
			displayName += " ";
		displayName += middleName;
	}

	if (eval(gLastName).length)
	{
		if (displayName.length)
			displayName += " ";
		displayName += eval(gLastName);
	}

	return displayName;
}

function ERCS_GenerateLoginName(firstName, middleName, lastName)
{
	var loginName;

	loginName = eval(gFirstName);

	if (middleName.length)
	{
		if (loginName.length)
			loginName += " ";
		loginName += middleName;
	}

	if (eval(gLastName).length)
	{
		if (loginName.length)
			loginName += " ";
		loginName += eval(gLastName);
	}

	return loginName;
}

function ERCS_MemberKeyHandler(evt)
{
	evt = EventSetup( evt );

	var eventName = evt.target.name;

	//	update initials
	if(!ModifiedInitials && 
		((eventName == "FirstName") ||
		(eventName == "MiddleName") ||
		(eventName == "LastName")))
	{
		document.BodyForm.Initials.value = ERCS_GenerateInitals(document.BodyForm.FirstName.value, document.BodyForm.MiddleName.value, document.BodyForm.LastName.value);
		DefaultInitials = document.BodyForm.Initials.value;
	}
	else if((eventName == "Initials") &&
			(DefaultInitials != document.BodyForm.Initials.value))
	{
		ModifiedInitials = true;
	}

	//	update display name
	if(!ModifiedDisplayName && 
		((eventName == "FirstName") ||
		(eventName == "MiddleName") ||
		(eventName == "LastName")))
	{
		document.BodyForm.DisplayName.value = ERCS_GenerateDisplayName(document.BodyForm.FirstName.value, document.BodyForm.MiddleName.value, document.BodyForm.LastName.value);
		DefaultDisplayName = document.BodyForm.DisplayName.value;
	}
	else if((eventName == "DisplayName") &&
			(DefaultDisplayName != document.BodyForm.DisplayName.value))
	{
		ModifiedDisplayName = true;
	}

	//	update LoginName, if it is enabled
	if (document.BodyForm.LoginName)
	{
		if(!ModifiedLoginName && 
			((eventName == "FirstName") ||
			(eventName == "MiddleName") ||
			(eventName == "LastName")))
		{
			document.BodyForm.LoginName.value = ERCS_GenerateLoginName(document.BodyForm.FirstName.value, document.BodyForm.MiddleName.value, document.BodyForm.LastName.value);
			DefaultLoginName = document.BodyForm.LoginName.value;
		}
		else if((eventName == "LoginName") &&
				(DefaultLoginName!= document.BodyForm.LoginName.value))
		{
			ModifiedLoginName = true;
		}
	}
	
	if (document.BodyForm.DMUsername && !ModifiedDMLogin)
	{
		if ( ( eventName == "LoginName" ) ||
		     ( !ModifiedLoginName && 
			   ( ( eventName == "FirstName" ) ||
	  		     ( eventName == "MiddleName" ) ||
			     ( eventName == "LastName" ) ) ) )
		{
			document.BodyForm.DMUsername.value = document.BodyForm.LoginName.value;
			DefaultDMLogin = document.BodyForm.LoginName.value;
		}
		else if ( (eventName == "DMUsername") && ( DefaultDMLogin != document.BodyForm.DMUsername.value ) )
		{
			ModifiedDMLogin = true;
		}
	}

	return true;
}

function ERCS_InitMemberKeyHandler()
{
	// clear out the globals
	ModifiedInitials = false;
	DefaultInitials = new String("");

	ModifiedDisplayName = false;
	DefaultDisplayName = new String("");
	GeneratedDisplayName = new String("");
	
	ModifiedLoginName = false;
	DefaultLoginName = new String("");

	ModifiedDMLogin = false;
	DefaultDMLogin = new String("");

	// register event callbacks
	if(IsNS) 
	{
		document.captureEvents(Event.KEYUP)
	}

	document.onkeyup = ERCS_MemberKeyHandler;

	// initialize values and flags
	DefaultInitials = document.BodyForm.Initials.value;
	if ((DefaultInitials != "") && 
		(DefaultInitials != ERCS_GenerateInitals(document.BodyForm.FirstName.value, document.BodyForm.MiddleName.value, document.BodyForm.LastName.value)))
	{
		ModifiedInitials = true;
	}

	if (document.BodyForm.LoginName)
	{
		DefaultLoginName = document.BodyForm.LoginName.value;
		if ((DefaultLoginName != "") && 
			(DefaultLoginName != ERCS_GenerateLoginName(document.BodyForm.FirstName.value, document.BodyForm.MiddleName.value, document.BodyForm.LastName.value)))
		{
			ModifiedLoginName = true;
		}

		if (document.BodyForm.DMUsername)
		{
			DefaultDMLogin = document.BodyForm.DMUsername.value;
			if ((DefaultDMLogin != "") && 
				(DefaultDMLogin != document.BodyForm.LoginName.value))
			{
				ModifiedDMLogin = true;
			}
		}	
	}	
	
    GeneratedDisplayName =
      ERCS_GenerateDisplayName(document.BodyForm.FirstName.value,
                               document.BodyForm.MiddleName.value,
                               document.BodyForm.LastName.value);

    if (document.BodyForm.DisplayName)
    {
    	DefaultDisplayName = document.BodyForm.DisplayName.value;
        if ((DefaultDisplayName != "") && (DefaultDisplayName != GeneratedDisplayName))
	   	    ModifiedDisplayName = true;
    }
    else
    {
    	DefaultDisplayName  = GeneratedDisplayName
  	    ModifiedDisplayName = true;
    }
}

// site search page
function SiteSearchViewFile( itemID )
{
	var nameType, linkName;
	var i = 0;
	var elementCount;
	elementCount = document.links.length;
	var itemInfo = itemID.split("/");
	var pattern = ".*/eRoomReq/Files/" + itemInfo[0] + "/.*/" + itemInfo[1] + ".*";
	var URLpattern = new RegExp(pattern) ;
	while ( i < elementCount )
	{
		if ( document.links[i].href.match( URLpattern ) != null)
		{
			path = document.links[i].href;
		}
		i++;
	}
	document.location = path;
	return false;
}	

// community settings, members tab
function GetDisabledCount()
{
	var DisabledCount = 0;
	if (document.BodyForm.AllCanCreateRooms[0].checked)
		DisabledCount++;
	
	if (document.BodyForm.AllCanModifyCML[0].checked)
		DisabledCount++;

	if (document.BodyForm.AllCanCreateGroup[0].checked)
		DisabledCount++;

	if (document.BodyForm.AllCanSetPassword[0].checked)
		DisabledCount++;
		
	return DisabledCount;
}

function UpdateRadioButtons(permissionID, type)
{
	var bIsAll;
	if (type.indexOf("all") != -1)
		bIsAll = true;
	else
		bIsAll = false;
	
	if (permissionID == 3)
	{
		document.BodyForm.AllCanCreateGroup[0].checked = bIsAll;
		document.BodyForm.AllCanCreateGroup[1].checked = !bIsAll;
		document.BodyForm.AllCanCreateGroup[0].disabled = bIsAll;
		document.BodyForm.AllCanCreateGroup[1].disabled = bIsAll;
	}	

	if (permissionID != 1)
	{
		if (GetDisabledCount() < 1 && !bIsAll)
		{
			document.BodyForm.AllCanViewMemberList[0].disabled = false;
			document.BodyForm.AllCanViewMemberList[1].disabled = false;
			document.BodyForm.AllCanViewMemberList[1].checked = true;
		}
		else
		{
			document.BodyForm.AllCanViewMemberList[0].checked = true;
			document.BodyForm.AllCanViewMemberList[0].disabled = true;
			document.BodyForm.AllCanViewMemberList[1].disabled = true;
		}
	}
	
	return true;
}

function PermGroupClickHandler(permissionID, buttonName, theMsg)
{
	var bDisabled;
	bDisabled = false;
	
	if (permissionID == 1)
	{
		if (document.BodyForm.AllCanCreateRooms[0].checked ||
			document.BodyForm.AllCanModifyCML[0].checked ||
			document.BodyForm.AllCanSetPassword[0].checked ||
			document.BodyForm.AllCanCreateGroup[0].checked)
		{
			bDisabled = true;
		}
	}
	
	if (permissionID == 4)
	{
		if (document.BodyForm.AllCanModifyCML[0].checked)
		{
			bDisabled = true;
		}
	}

	if (!bDisabled)
		return ERBodyFormClickHandler(buttonName);
	else
	{
		alert( theMsg )
		return false;
	}
}

function AdjustSitePasswordSettings()
{
	if (document.BodyForm.CanChangePswdLater.checked)
	{
		document.BodyForm.EnablePasswordRecovery.disabled = false;
		document.BodyForm.RecoveryFailCount.disabled = false;
	}
	else
	{
		document.BodyForm.EnablePasswordRecovery.disabled = true;
		document.BodyForm.EnablePasswordRecovery.checked = false;
		document.BodyForm.RecoveryFailCount.disabled = true;
	}	
}

// helper function used to determine if the base url passed in is the same
// as the base url currently displayed in the browser
function IsSameURLBaseInBrowser(sURLToMatch)
{
	var BrowserURL=""+document.location
	var BrowserBase=""
	var tmpURLPrefix=sURLToMatch.toLowerCase();
	BrowserBase=BrowserURL.substr(0, tmpURLPrefix.length).toLowerCase();
	return (tmpURLPrefix==BrowserBase);
}

// no-op function used to help localizers identify JavaScript text that needs to be localized.
function ERDisplayMsg(text)
{
	return text
}
    
// dashboard helper script
function DashOptionsSelectAll()
{	
	var elem, bCheck, tmpName;
	elem=document.BodyForm.elements;
	bCheck=document.BodyForm.AllFields.checked;
	for( var i=0; i < elem.length; i++)
	{
		if (elem[i].type == "checkbox")
			if (elem[i].name.indexOf("UseInDash") != -1)
				if (!elem[i].disabled)
				{
					elem[i].checked = bCheck;
					tmpName=elem[i].name.substr(9, elem[i].name.length);
					if(!isNaN(parseInt(tmpName)))
					{
						DisableControls(elem[i], "FieldCell"+tmpName);
					}
				}
	}
}

function DashOptionsHandleSelectAllCheckbox()
{	
	var elem, bCheck, tmpName;
	elem=document.BodyForm.elements;
	bCheck=true;
	for( var i=0; i < elem.length; i++)
	{
		if (elem[i].type == "checkbox")
			if (elem[i].name.indexOf("UseInDash") != -1)
				if (elem[i].disabled || !elem[i].checked)
				{
					bCheck=false;
					break;
				}
	}
	document.BodyForm.AllFields.checked=bCheck;
}
function DashboardSelectCheckbox(Checkbox)
{
	var Obj;
	Obj=document.getElementById(Checkbox);
	Obj.checked=true;
	return true;
}
function DisableChildren(Obj, bEnable)
{
	var i=0;
	for(i=0; i<Obj.children.length; i++)
	{
		if(Obj.children==null || Obj.children.length==0)
		{
			// break condition		
		}
		else if (Obj.children[i].type == "checkbox")
		{
			Obj.children[i].checked=bEnable;
			Obj.children[i].disabled=!bEnable;
		}
		else if(Obj.children[i].type == "text" || Obj.children[i].type == "image" || Obj.children[i].value)
		{
			Obj.children[i].disabled=!bEnable;
		}
		else
		{
			// don't care about this element
			// but may want to disable a child
			DisableChildren(Obj.children[i], bEnable);
		}
	}	
}

function DisableControls(cb, FieldID)
{
	var Obj;
	Obj=document.getElementById(FieldID);
	var i=0;
	DisableChildren(Obj, cb.checked);
}

//  Event handler to implement "side by side" combo box:  if
//  item with index == customIndex is selected, associated
//  editBox becomes visible; if item with index != customIndex
//  is selected, associated editBox is hidden, and value in
//  editBox is stored as value of selectList.options[customIndex].
//  If editBoxID is a string (onchange handler for selectList),
//     hides editBox if selectList.selectedIndex != customIndex
//     shows editBox if selectList.selectedIndex == customIndex
//  Else (onkeyup handler for editBox)
//     updates selectList.options[customIndex] with editBox.value
function UpdateComboBox( editBoxID, selectListID, customIndex )
{
    var editBox;
    var selectList;
    var bManipulateEditBox;
    var bManipulateSelectList;

    //  dereference selectList object
    if (typeof selectListID == "string")
    {
        selectList = document.getElementById(selectListID);
        bManipulateSelectList = true;
    }
    else
    {
        selectList = selectListID;
        bManipulateSelectList = false;
    }

    if ( selectList == null )
        return;

    //  dereference editBox object
    if (typeof editBoxID == "string")
    {
        editBox = document.getElementById(editBoxID);
        bManipulateEditBox = true;
    }
    else
    {
        editBox = editBoxID;
        bManipulateEditBox = false;
    }

    if ( editBox == null )
        return;

    if ( bManipulateEditBox )
    {
        //  Called as onchange handler for selectList
        editBox.value = selectList.options[selectList.selectedIndex].value;
        if ( selectList.selectedIndex == customIndex )
            editBox.style.visibility = "visible";
        else
            editBox.style.visibility = "hidden";
    }

    if ( bManipulateSelectList )
    {
        //  Called as onkeyup handler for editBox:
        //  remember as value associated with customIndex
        selectList.options[customIndex].value = editBox.value;        
    }
}

function ChangeAlertType(alertType)
{
	if (alertType == "AlertType:0")
	{
		// selecting email
		document.getElementById("memberswithIMonly").style.display = ''
		document.getElementById("memberswithEmailOnly").style.display = 'none'
		document.getElementById("noAlertableMembers").style.display = ''
	}
	else if (alertType == "AlertType:1")
	{
		// selecting IM
		document.getElementById("memberswithIMonly").style.display = 'none'
		document.getElementById("memberswithEmailOnly").style.display = ''
		document.getElementById("noAlertableMembers").style.display = ''
	}
	else
	{
		// selecting IM
		document.getElementById("memberswithIMonly").style.display = 'none'
		document.getElementById("memberswithEmailOnly").style.display = 'none'
		document.getElementById("noAlertableMembers").style.display = 'none'
	}
	return false;
}

function LinkMouseUp() 
{
	if (!MenuOverValidItem)
		return true;

	hideAll();

	var InfoIndex=this.linkText;  // the link text comtains the link index in the name of the selected menu item
	var Parts=menuItem.name.split("\t");
	
	if(Parts[InfoIndex]!="")
	{
		document.location=Parts[InfoIndex];
	}
	else
	{
		return true;	
	}
}


function launchWindowsMessenger(receiversIMAccountName)
{
	if ( !UsePlugin )
	{
		// show message about needing the plugin to do this
		alert(gNeedPluginForIMErrStr);
		return;
	}

	var retVal = document.ERPageAddIn.LaunchLCSClient(receiversIMAccountName);
	
	if ( retVal == 1 )
	{
		alert(gMSNNotInstalledErrStr);
	}
	else if ( retVal == 2 )
	{
		alert(gIMNotLoggedInErrStr);
	}
	else if ( retVal == 3 )
	{
		// some other error ocurred.
	}
}

function LaunchIMMouseUp() 
{
	if (!MenuOverValidItem)
		return true;

	hideAll();
	
	var InfoIndex=parseInt(this.linkText);  // the link text contains the link index in the name of the selected menu item
	var Parts=menuItem.name.split("\t");
	if(Parts[InfoIndex]!="" && Parts[InfoIndex + 1]!="")
	{
		var receiversIMAccountName = Parts[InfoIndex]
		var receiversIMClient = Parts[InfoIndex+1]
		
		if(receiversIMClient==1)
		{
			// aim client
			document.location="aim:goIM?screenname="+receiversIMAccountName;
			return false;
		}
		else if(receiversIMClient==2)
		{
			// msn client
			launchWindowsMessenger(receiversIMAccountName);
			return false;
		}
	}

	return true;	
}

function FirstStringEndsWithSecondString(firstString, secondString)
{
	var endOfFirstString = firstString.substring(firstString.length - secondString.length, firstString.length)
	return endOfFirstString == secondString;
}

function addFileExtension(filename, ext)
{
	var lowerfilename = filename.toLowerCase();
	var lowerext = ext.toLowerCase();
	
	if (!FirstStringEndsWithSecondString(lowerfilename, lowerext))
		// add extension
		filename += ext;			

	return filename;
}

function CreateDocOnClick(btnName)
{
	if (((btnName == "btnOK") || (btnName == "btnDefault")) && (document.getElementById("CreateNewDoc").checked))
	{
		// user is creating a new file
		// have the AddIn create one, and stuff
		// the base64 encoded value representing that file
		// into the hidden form field
		document.getElementById("HiddenNewFiledata").value =
				document.ERPageAddIn.NewEncodedFileFromExt(document.getElementById("NewItemMenu").value);

		var newFilename = addFileExtension(document.getElementById("NewFilename").value, document.getElementById("NewItemMenu").value)

		// update user's filename to have the correct file extension
		document.getElementById("NewFilename").value = newFilename;
	}
}

function addNewFileOption(optionName, optionValue)
{
	var newOpt  = new Option(optionName, optionValue);
	var selLength = document.getElementById("NewItemMenu").length;
	document.getElementById("NewItemMenu").options[selLength] = newOpt;
}

function VerifyCreateDocOnClick(btnName)
{
	var validEntry = true;
	if (((btnName == "btnOK") || (btnName == "btnDefault")) && (document.getElementById("CreateNewDoc").checked))
	{
		if (document.getElementById("NewFilename").value == "" )
		{
			DisplayErrorPopupQuery(gYou_must_supply_a_filenameStr)
			document.getElementById("NewFilename").focus()
			validEntry = false;
		}
		if (document.getElementById("NewItemMenu").value == "unselected")
		{
			DisplayErrorPopupQuery(gYou_must_supply_a_file_typeStr)
			validEntry = false;
		}
	}
	return validEntry;
}

function ClientSupportsFeature(feature)
{
	var SetCookieDomainFeatureVersion = 127544;	// SetCookieDomain() introduced in v7.3.3_497.56.

	var supports = false;
	var clientVersion = GetClientVersion(UsePlugin);

	switch(feature)
	{
		case "SetCookieDomain":
			supports = (clientVersion >= SetCookieDomainFeatureVersion) ? true : false;
			break;
		default:
			alert('ClientSupportFeature() - Unknown feature: ' + feature);
			break;
	}
	return supports;
}
