var bHoldSelection = true;	// Retain selected items when reloading message list

/***************************************************************
* Credits: The following two functions are courtesy of Mozilla.org
***************************************************************/
function getOffsetTop(obj)
{
	var mOffsetTop = obj.offsetTop;
	var mOffsetParent = obj.offsetParent;
	
	while( mOffsetParent )
	{
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	
	return mOffsetTop;
}

/***************************************************************
* Credits: The following two functions are courtesy of Mozilla.org
***************************************************************/
function getOffsetLeft(obj)
{
	var mOffsetLeft = obj.offsetLeft;
	var mOffsetParent = obj.offsetParent;
	
	while( mOffsetParent )
	{
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	
	return mOffsetLeft;
}

/***************************************************************
* Relative to a parent
***************************************************************/
function getOffsetLeftEx(obj, parent)
{
	var mOffsetLeft = obj.offsetLeft;
	var mOffsetParent = obj.offsetParent;
	
	while( mOffsetParent || mOffsetParent !== parent )
	{
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	
	return mOffsetLeft;
}

/***************************************************************
* This is a bi-di friendly routine. Please use this if setXPosition
* is going to be used as well. Because setXPosition is bidi.
***************************************************************/
function getOffsetLeftBidi(obj)
{

	var bIE6or7 = gwwa.browser.name == "MSIE" && parseInt(gwwa.browser.mjrVer) <= 7;
	var bRTL = document.documentElement.dir.toLowerCase() == "rtl";
	var mOffsetLeft = 0;
	var mOffsetParent = obj.offsetParent;
	var lastParent = null;

	// Workaround for IE6 and IE7 bug where it returns the wrong offsetLeft when in RTL
	if (bRTL && bIE6or7)
	{
		obj.style.zoom = 1;
		mOffsetLeft = obj.offsetLeft;
		obj.style.zoom = 0;
		mOffsetLeft -= 3;
	}
	else
	{
		mOffsetLeft = obj.offsetLeft;
	}
		
	while( mOffsetParent )
	{
		lastParent = mOffsetParent;
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
	}

	// If it is right to left, get what would me the "right" coordinate
	if(lastParent && bRTL)
	{
		mOffsetLeft = lastParent.clientWidth - mOffsetLeft - obj.offsetWidth;
	}
	return mOffsetLeft;
}

/***************************************************************
* This is a bi-di friendly routine. It will set the "left" or "right" position
* based on the "dir" attribute of the document.
***************************************************************/
function setXPosition(obj, value)
{
	if( document.documentElement.dir.toLowerCase() == "rtl" )
	{
		obj.style.right = value + "px";
	}
	else
	{
		obj.style.left = value + "px";
	}
}

/***************************************************************
* This is a bi-di friendly routine. It will set the text-align
* to "left" in LTR mode, and "right" in RTL mode...
***************************************************************/
function setBidiTextAlign(element)
{
	element.style.textAlign = ( document.documentElement.dir.toLowerCase() == "rtl" ) ? "left" : "right";
}

/***************************************************************
* This is a bi-di friendly routine. It will set the text-align
* to "left" in LTR mode, and "right" in RTL mode...
***************************************************************/
function setTextAlignLeft(element)
{
	element.style.textAlign = ( document.documentElement.dir.toLowerCase() == "rtl" ) ? "right" : "left";
}

/***************************************************************
* This is a bi-di friendly routine. It will set the text-align
* to "right" in LTR mode, and "left" in RTL mode...
***************************************************************/
function setTextAlignRight(element)
{
	element.style.textAlign = ( document.documentElement.dir.toLowerCase() == "rtl" ) ? "left" : "right";
}

/***************************************************************
* This is a bi-di friendly routine. It will set the "left" or "right" position
* based on the "dir" attribute of the document.
***************************************************************/
function getBidiClientX(event)
{
	event = util.getEvent(event);

	return ( document.documentElement.dir.toLowerCase() == "rtl" ) ? 
				(document.documentElement.clientWidth - event.clientX ): 
				event.clientX;
}

/***************************************************************
* This is a bi-di friendly routine. It will set the "left" or "right" position
* based on the "dir" attribute of the document.
***************************************************************/
function getElementBidiOffsetLeft(element)
{
	return ( document.documentElement.dir.toLowerCase() == "rtl" ) ? 
				(element.parentNode.offsetWidth - element.offsetLeft) : 
				(element.offsetLeft);
}

/***************************************************************
* This is a bi-di friendly routine. It will set the "left" or "right" position
* based on the "dir" attribute of the document.
***************************************************************/
function getBidiOffsetLeft(element)
{
	var mOffsetLeft = getElementBidiOffsetLeft(element);
	var mOffsetParent = element.offsetParent;
	
	while( mOffsetParent )
	{
		mOffsetLeft += getElementBidiOffsetLeft(mOffsetParent);
		mOffsetParent = mOffsetParent.offsetParent;
	}
	
	return mOffsetLeft;
}

/***************************************************************
* 
***************************************************************/
function menuItemHover(event,hoverFlag)
{
	var eventSrc = ( window.event ) ? window.event.srcElement : event.currentTarget;
	
	if( eventSrc.id == "idNew" )
	{
		return;
	}

	/*				
		FIXME/TODO: We cannot hover over the gifs because their background is getting 
		messed up for IE and SAFARI. Serenity now!!! 
	*/
	if( gwwa.browser.name == "MSIE" || gwwa.browser.name == "SAFARI" || gwwa.browser.flavor == "SAFARI" )
	{
		if( eventSrc.tagName == "IMG" || eventSrc.className == "icon" )
		{
			return;
		}
	}

	if (eventSrc.style )
	{
		if( hoverFlag )
		{
			if( gwwa.browser.name == "SAFARI" || gwwa.browser.flavor == "SAFARI" )
			{
				eventSrc.style.color = "black";
				eventSrc.style.backgroundColor = "#B5D5FF";
			}
			else
			{
				eventSrc.style.color = "HighlightText";
				eventSrc.style.backgroundColor = "Highlight";
			}
		}
		else
		{
			eventSrc.style.color = "black";
			eventSrc.style.backgroundColor = "white";
		}
	}
}

/***************************************************************
* 
***************************************************************/
function menuItemOver(event)
{
	menuItemHover(event, 1);
}

/***************************************************************
* 
***************************************************************/
function menuItemOut(event)
{
	menuItemHover(event, 0);
}

/***************************************************************
* 
***************************************************************/
var popupDrn = 0;	
function showGwMenu(event, showFlag, drn, clientX, clientY, bDontChangeStyle)
{
	return showGwMenuEx(event, "idPopupMenu", showFlag, drn, clientX, clientY, bDontChangeStyle);
}

/***************************************************************
* 
***************************************************************/
function showGwMenuEx(event, id, showFlag, drn, clientX, clientY, bDontChangeStyle)
{
	var divPopupMenu = document.getElementById( id );
	popupDrn = drn;
	
	if( !divPopupMenu )
	{
		return true;
	}
	
	if( showFlag )
	{
		divPopupMenu.style.display = "block";
		
		setMenuPosition(event, divPopupMenu, clientX, clientY);
		
		if( !bDontChangeStyle )
		{
			divPopupMenu.className = "popup popupShow";
		}
		
		return false;
	}
	else
	{
		if( !bDontChangeStyle )
		{
			divPopupMenu.className = "popup popupHide";
		}

		return true;
	}
}

/***************************************************************
* 
***************************************************************/
function setMenuPosition(event, menu, clientX, clientY)
{
	var realX;
	var realY;
	
	if( !clientX )
	{
		clientX = event.clientX;
	}

	if( !clientY )
	{
		clientY = event.clientY;
	}

	if( gwwa.browser.name == "MSIE" )
	{
		realX = (document.documentElement.scrollLeft + clientX);
		realY = (document.documentElement.scrollTop + clientY);
	}
	else if( gwwa.browser.name  == "SAFARI" )
	{
		realX = clientX;
		realY = clientY;
	}
	else
	{
		realX = (self.pageXOffset + clientX);
		realY = (self.pageYOffset + clientY);
	}
	
	var bodyHeight;
	if( gwwa.browser.name == "SAFARI" || gwwa.browser.flavor == "SAFARI" )
	{
		bodyHeight = document.body.scrollHeight;
	}
	else
	{
		bodyHeight = document.documentElement.clientHeight;
	}
	
	if( bodyHeight  < ( realY + menu.offsetHeight ) )
	{
		menu.style.top = realY - menu.offsetHeight + "px";
	}
	else
	{
		menu.style.top = realY + "px";
	}
	
	var left;
	if( document.documentElement.dir.toLowerCase() == "rtl" )
	{
		if( realX < menu.offsetWidth )
		{
			left = realX;
		}
		else
		{
			left = realX - menu.offsetWidth;
		}
	}
	else
	{
		if( document.documentElement.clientWidth < ( clientX + menu.offsetWidth ) )
		{
			left = realX - menu.offsetWidth;
		}
		else
		{
			left = realX;
		}
	}
	
	menu.style.left = left + "px";
}

/***************************************************************
* This method is the event handler for 'onclick'
***************************************************************/
function handleNewDropDown(e, objForm)
{
	var divNewPopupMenu = document.getElementById( "idNewPopupMenu" );
	
	if( !divNewPopupMenu )
	{
		divNewPopupMenu = createMenu(newMenu);
	}
	
	//TODO: We probably should get rid of this first check here. Its just a 'fix'
	if( divNewPopupMenu.style.visibility == "" || divNewPopupMenu.style.visibility == "hidden" )
	{
		//--------------------------------------------
		// For IE 6, we must hide the select controls 
		// because they paint over the drop-down menus
		//--------------------------------------------
		// Commenting this line, this function is no longer needed. Check bug #485483
		//handleSelectControls( objForm, 0 );

		showNewPopupMenu(1);
	}
	else
	{
		//--------------------------------------------
		// For IE 6, we must hide the select controls 
		// because they paint over the drop-down menus
		//--------------------------------------------
		// Commenting this line, this function is no longer needed. Check bug #485483
		//handleSelectControls( objForm, 1 );

		showNewPopupMenu(0);
	}

	if( window.event )
	{
		window.event.cancelBubble = true;
	}
	else
	{
		e.stopPropagation();			
	}
}

/***************************************************************
@handleSelectControls
Description: 
Input: 
Output: 
Notes: 
***************************************************************/
function handleSelectControls ( objForm, bShowControl )
{
	//--------------------------------------------
	// For IE 6, we must hide the select controls 
	// because they paint over the drop-down menus
	//--------------------------------------------
	if( ( objForm ) && ( gwwa.browser.name == "MSIE" ) && 
		( parseInt(gwwa.browser.mjrVer) <= 6 ) ) 
	{
		var objControl = null;
		
		//------------------------------------------------
		// Loop through the select controls and toggle
		// the visibility depending on "bShowControl"
		//------------------------------------------------
		for( var i = 0; i < objForm.elements.length; i++ )
		{
			objControl = objForm.elements[ i ];
			
			if( objControl.type == "select-one" || objControl.type == "select-multiple" )
			{
				objControl.style.visibility = ( bShowControl ) ? "visible" : "hidden";
			}
		}
	}

}; // handleSelectControls

/***************************************************************
* more generic dropdown functions, should deprecate old ones
***************************************************************/
function handleDropDown(e, menutable, button)
{
	if(menutable.style.visibility == "" ||
           menutable.style.visibility == "hidden" ) {
		showPopupMenu(menutable, true, button);
	} else {
		showPopupMenu(menutable, false, button);
	}
	if(window.event) {
		window.event.cancelBubble = true;
	} else {
		e.stopPropagation();			
	}
	return;
}

/***************************************************************
* more generic dropdown functions, should deprecate old ones
***************************************************************/
function showPopupMenu(menutable, flag, button)
{
	if(flag) {
		menutable.style.display = "block";
		var posX = 0;
		if(getOffsetLeft(button) + menutable.offsetWidth < window.innerWidth) {
			posX = getOffsetLeft(button) + 5;
		} else {
			posX = window.innerWidth - menutable.offsetWidth;
		}
		setXPosition(menutable, posX);

		menutable.style.top = (getOffsetTop(button) +
					button.offsetHeight) + "px";
		menutable.style.visibility = "visible";
	} else {
		menutable.style.visibility = "hidden";
		menutable.style.display = "none";
	}
	return;
}

/***************************************************************
* This method does actual work of hiding or showing the popup menu
***************************************************************/
function showNewPopupMenu(flag)
{
	var divNewPopupMenu = document.getElementById( "idNewPopupMenu" );
	var objToolbarChangeItemType = document.getElementById( 'idNew' );
	
	if( !divNewPopupMenu )
	{
		divNewPopupMenu = createMenu(newMenu);
	}
	
	// This takes care of the "Selects and Iframes over a dynamic menu" issue in IE6
	if( ( gwwa.browser.name == "MSIE" ) && ( parseInt(gwwa.browser.mjrVer) <= 6 ) )
	{
		if (!divNewPopupMenu.iFrameLayer) {
			var iFrameLayer = document.createElement("iframe");
			iFrameLayer.style.position = "absolute";
			iFrameLayer.style.overflow = "hidden";
			iFrameLayer.style.borderWidth = "0px";
			iFrameLayer.style.top = "0px";
			iFrameLayer.style.left = "0px";
			iFrameLayer.style.visibility = "hidden";
			iFrameLayer.src = "";
			document.body.appendChild(iFrameLayer);
			divNewPopupMenu.iFrameLayer = iFrameLayer;
		}
                
	}
	
	if( flag )
	{
		var posX = getOffsetLeftBidi(objToolbarChangeItemType) + 5;
		setXPosition( divNewPopupMenu, posX );

		divNewPopupMenu.style.top = ( getOffsetTop(objToolbarChangeItemType) + objToolbarChangeItemType.offsetHeight ) + "px";
		divNewPopupMenu.style.visibility = "visible";
		divNewPopupMenu.style.display = "block";
		
		if( ( gwwa.browser.name == "MSIE" ) && ( parseInt(gwwa.browser.mjrVer) <= 6 ) && divNewPopupMenu.iFrameLayer)
        {
            divNewPopupMenu.iFrameLayer.style.height = divNewPopupMenu.offsetHeight + "px";
            divNewPopupMenu.iFrameLayer.style.width = divNewPopupMenu.offsetWidth + "px";
            divNewPopupMenu.iFrameLayer.style.top = divNewPopupMenu.style.top;
            setXPosition( divNewPopupMenu.iFrameLayer, posX );
            divNewPopupMenu.iFrameLayer.style.visibility = "visible";
        }
	}
	else
	{
		divNewPopupMenu.style.visibility = "hidden";
		divNewPopupMenu.style.display = "none";
		
		if( ( gwwa.browser.name == "MSIE" ) && ( parseInt(gwwa.browser.mjrVer) <= 6 ) && divNewPopupMenu.iFrameLayer)
        {
            divNewPopupMenu.iFrameLayer.style.visibility = "hidden";
        }
	}
}

/***************************************************************
* This method performs the action depending on what menu item has
* been 'selected'
***************************************************************/
function handleNewRequest(e, type, posted)
{
	//-------------------------------------------
	// Check if type is passed as an argument...
	// Ex: "New" in calendar mode should open a
	// compose dialog for group appointment type.
	//-------------------------------------------
	if( !type )
	{
		//-------------------------------------------
		// New version of newpm.inc actions will have
		// the menu item associtated with <tr> nodes.
		//-------------------------------------------
		var eventSrc = util.getEventSrc( e );
		
		//-------------------------------------------
		// HACK: Safari and IE return <td> as target
		// instead of <tr>, so get right target node
		//-------------------------------------------
		var tr = util.getParentNodeEx(eventSrc, "tr");
		
		if( tr.menuItem && tr.menuItem.id )
		{
			type = tr.menuItem.id;
		}
	}
	
	//-------------------------------------------
	// Open a Mail msg if nothing is specified
	//-------------------------------------------
	type = ( type ) ? ( type ) : ( 1 ) ;
		
	var sUrl = homeURL + "?User.context=" + userContext + "&action=Compose.Action&merge=xsend";
	
	if( posted === true )
	{
	    sUrl += "&Item.Compose.method=POST";
	}
	
	handleNewRequestEx(e, type, sUrl );
}

/***************************************************************
* This method performs the action depending on what menu item has
* been 'selected'
***************************************************************/
function handleNewRequestEx(e, type, sUrl)
{
	var thisEvent = ( e ) ? e : window.event;
	var eventSrc = getEventSrc(e);
	
	if( type >= 6 && type <= 10 )
	{
		sUrl = sUrl + "&Item.Compose.method=POST&Item.Folder.id=" + inc_folderId;
	}
	
	if( type == 1 || type == 6 )
	{
		sUrl = sUrl + "&Item.type=Mail";
	}
	else if( type == 2 || type == 7 )
	{
		sUrl = sUrl + "&Item.type=Appointment";
	}
	else if( type == 3 || type == 8 )
	{
		sUrl = sUrl + "&Item.type=Task";
	}
	else if( type == 4 || type == 9 )
	{
		sUrl = sUrl + "&Item.type=Note";
	}
	else if( type == 5 || type == 10 )
	{
		sUrl = sUrl + "&Item.type=Phone";
	}
	
	//--------------------------------------------
	// Note that we need to pass Item.dateStart
	// independent of the item type so that we
	// can use this info for filling the fields
	// when user changes item type to A/N/T.
	// With smart time-zone enabled/disabled, the 
	// appointment's start time will be the next 
	// hour (with respect to the user's current 
	// workstation time), and the user-selected 
	// time zone setting. Server's time will not 
	// used as the start time because of smart 
	// time-zone feature...)
	//--------------------------------------------
	sUrl += "&Item.dateStart=" + getNextHourTime();
	
	//-----------------------------------------------
	// type == 11 for creating a new calendar, use 
	// gwwa.multical.handleCalendarAction(). Note 
	// that the option 'Create Calendar' is displayed
	// only when user is within the calendar context.
	//-----------------------------------------------
	if( type == 11 )
	{
		gwwa.multical.handleCalendarAction();
	}
	else
	{
		popoutComposeEx( sUrl, "_blank" );
	}
	
	showNewPopupMenu(0);
	
	//Take the "hover" effect off, otherwise the next time they open the menu,
	//the last selected item will have the "hover" background/font colors.
	menuItemHover(thisEvent,0);
}

/***************************************************************
* This needs to be fixed if the current page plans to use the "bUseSame" option
* for more than one window. ViewWin is obviously not sufficient for tracking multiple windows
***************************************************************/
var uniqueUrl = 1;
function popout(url, targetWin, h, w, bTouchUrl, bUseSame, l, t )
{
	var ViewWin = null;

	if( bUseSame && ViewWin && !ViewWin.closed && ViewWin.name == targetWin )
	{
		ViewWin.focus();
	}
	else
	{
		if (bTouchUrl)
		{
			if (bTouchUrl == 1)
			{
				url += "&z=" + uniqueUrl;
				uniqueUrl++;
			}
		}

		if (h && h > 0)
		{
			height=h;
		}
		else
		{
			height = 600;
		}

		if (w && w > 0)
		{
			width=w;
		}
		else
		{
			width = 800;
		}

		if (screen.width > 0) 
		{
			var w = 480, h = 340;
			if (document.layers) 
			{
				w = window.innerWidth;
				h = window.innerHeight;
			} 
			else 
			{
				w = document.documentElement.clientWidth;
				h = document.documentElement.clientHeight;
			}
			
			if(l && l > -1 && t && t > -1){
				winLeft = l;
				winTop = t;
			}
			else{
				winLeft = (screen.width-width)/2;
				winTop = (screen.height-height)/2;
			}
			
			//if( navigator.userAgent.indexOf( "Microsoft Internet Explorer" ) != -1 )
			if( gwwa.browser.name == "MSIE" )
			{
				posLeft = "left";
				posTop = "top";
			}
			else
			{
				posLeft = "screenX";
				posTop = "screenY";
			}
			
			//var winLeft = Math.abs((w-width)/2)+window.screenX, winTop = (Math.abs((h-height)/2)+window.screenY)/1.5;
			//document.write(winLeft+' :: '+winTop);
			//document.write(w+' :: '+h);
		}

		if( bUseSame  )
		{
			ViewWin = window.open(url, targetWin, 'width='+width+',height='+height+',resizable=yes,menubar=yes,scrollbars=yes,status=yes,' + posLeft + '='+winLeft+',' + posTop + '='+winTop );
		}
		else
		{
			try{
				ViewWin = window.open(url, targetWin, 'width='+width+',height='+height+',resizable=yes,menubar=yes,scrollbars=yes,status=yes,' + posLeft + '='+winLeft+',' + posTop + '='+winTop );
			}
			catch(err){
				//To handle MSIE error and avoid PopUpBlockerWarning message
				ViewWin = "MSIE ERROR";
			}
		}

        // If we could not open the pop out window, post a pop up blocker warning
        if( ViewWin == null )
        {
            alert(inc_PopUpBlockerWarning + inc_Host);
        }
        else if( ViewWin != "MSIE ERROR" )
        {
			//Initialize Cookie.itemReadDimensions to fix some issues with loss of data on MSIE
			if(targetWin == "ItemView"){
				dimensions = width + "," + height + "," + winLeft + "," + winTop;
				writeCookie( "Cookie.itemReadDimensions", dimensions, 30 );
			}
		
            var objCaptionWindow = findCaptionWindowEx();

			//-------------------------------------------------------
			// Defect# 332814 (spalagiri):  Script Error appears when 
			// "More Information" link is clicked in the Login page.
			// Check for valid caption window object before using it.
			//-------------------------------------------------------
			if( objCaptionWindow )
			{
				// Post this window's information to the pop out window manager
				objCaptionWindow.openPopOutWindow(ViewWin);
			}
			
            /*---------------------------------------------------------------------------
            Have the focus() call happen in the window being loaded because if we do
            it here, and they click on another message before the first gets loaded,
            we wind up having javascript errors.
            -----------------------------------------------------------------------------*/
            if (window.focus)
            {
                ViewWin.focus();
            }

        }
    }
    
    return ViewWin;
    
}   // popout



/***************************************************************
* 
***************************************************************/
function getEventSrc(e)
{
	//IE does NOT pass the event object into the event handler method. We need
	//to retrieve that object from the 'window' object. 
	//KONQUEROR has partial support for window.event and is thus unreliable. We must
	//check for e.currentTarget FIRST and return that if its valid
	return ( e && e.currentTarget ) ? e.currentTarget : window.event.srcElement;
}

/***************************************************************
* getEvent
***************************************************************/
function getEvent(e)
{
	return ( window.event != null ) ? window.event : e;
}

/***************************************************************
* getEventTarget
***************************************************************/
function getEventTarget(e)
{
	return ( window.event != null ) ? window.event.srcElement : e.currentTarget;
}

/***************************************************************
* getEventType
***************************************************************/
function getEventType(event)
{
	return getEvent(event).type;
}

/***************************************************************
* returnFalse
***************************************************************/
function returnFalse(event)
{
	var thisEvent = getEvent(event);

	if( thisEvent.cancelable )
	{
		thisEvent.preventDefault();
	}

	if( thisEvent.stopPropagation )
	{
		thisEvent.stopPropagation();
	}

	if( window.event )
	{
		window.event.cancelBubble = true;

		window.event.returnValue = false;
	}

	return false;
}

/***********************************************************************
* Find the caption window. There are many ways the compose window can
* be launched from...
**********************************************************************/
function popoutComposeEx(url, targetWin, h, w, bTouchUrl, bUseSame )
{
	return popout(url, targetWin, h, w, bTouchUrl, bUseSame);
}

/***********************************************************************
 * Find the caption window so we can see if the 
 * frequent contacts have been cached or not. 
 * If not, then we will need to modify the URL, 
 * so we get the FCs
**********************************************************************/
function findCaptionWindow()
{
	var captionWindow = null;
	var mainWindow = getMainWindow();
	
	if( mainWindow )
	{
		captionWindow = mainWindow.frames[ "caption" ];
	}
	
	return captionWindow;
}

/***********************************************************************
*
**********************************************************************/
function findCaptionWindowEx()
{
	if( !window.captionWindow )
	{
		window.captionWindow = findCaptionWindow();
	}
	
	return window.captionWindow;
}

/***********************************************************************
 * 
**********************************************************************/
function getCacheStore()
{
	return getMainWindow();
}

/***********************************************************************
*
**********************************************************************/
function getMainWindow()
{
	var win = window;
	var loopCount = 0;

    //-------------------------------------------------------------
    // Defect 332814: Clicking on the Preview link of a published 
    // calendar notification was causing script error in CalPub UI,
    // because of webaccess-parent window and calpub-child window
    // relation. So return main window as null for CalPub user...
    //-------------------------------------------------------------
    if( !gwwa.user.isWebAccessUser )
    {
        return null;
    }

	try
	{
		while( win && win.name != userContext && loopCount < 25 )
		{
			loopCount++;

			if( win.parent && win.parent != win )
			{
				win = win.parent;
				continue;
			}
			
			if( win.opener )
			{
				win = win.opener;

				if( win.closed )
				{
					win = null;
					break;
				}
				
				continue;
			}
		}

		win = ( win && win.name === userContext ) ? win : null;
	}
	catch(e)
	{
		win = null;
	}

	return win;
}

/***********************************************************************
*
**********************************************************************/
/*
function xhandleMsglistPopupMenu(menuItem)
{
	var strUrl;
	var hiddenAction = document.MessageList.elements[ "Toolbar.button" ];
	var itemDrn = document.MessageList.elements[ "Undefined" ];
	itemDrn.value = popupDrn;
	
	var baseURL = homeURL + "?User.context=" + userContext + inc_providerString + inc_urlFolderType + inc_urlFolderRightsPost + inc_urlFolderRightsDelete;
					
	if( menuItem == 1 ) //reply
	{
		strUrl = baseURL + "&action=Item.Action&merge=xsend&Url.Item.Reply=1&Item.Read=&Item.Reply=sender&Item.drn=" + popupDrn;

		popout(strUrl, "_blank" );
	}
	else if( menuItem == 2 ) //forward
	{
		strUrl = baseURL + "&action=Compose.Action&merge=xsend&Item.Enclosure.id=" + popupDrn + "&Url.Enclosure.type=forward&Item.drn=" + popupDrn;

		popout(strUrl, "_blank" );
	}
	else if( menuItem == 3 ) //accept 
	{
		hiddenAction.name = "Item.Accept";
		bHoldSelection = false;
		
		if( !isItemSelected() )
		{
			itemDrn.name = "Item.drn";
		}
		
		document.MessageList.submit();
	}
	else if( menuItem == 4 ) //decline
	{
		hiddenAction.name = "Item.Decline";
		bHoldSelection = false;
		
		if( !isItemSelected() )
		{
			itemDrn.name = "Item.drn";
		}
		
		document.MessageList.submit();
	}
	else if( menuItem == 5 ) //complete
	{
		hiddenAction.name = "Item.Complete";
		bHoldSelection = false;
		
		if( !isItemSelected() )
		{
			itemDrn.name = "Item.drn";
		}
		
		document.MessageList.submit();
	}
	else if( menuItem == 6 ) //delete
	{
		hiddenAction.name = "Item.Delete";
		bHoldSelection = false;
		
		if( !isItemSelected() )
		{
			itemDrn.name = "Item.drn";
		}
		
		document.MessageList.submit();
	}
	else if( menuItem == 7 ) //readlater
	{
		hiddenAction.name = "Item.ReadLater";
		bHoldSelection = false;
		
		if( !isItemSelected() )
		{
			itemDrn.name = "Item.drn";
		}
		
		document.MessageList.submit();
	}
	else if( menuItem == 10 ) //markread
	{
		hiddenAction.name = "Item.MarkRead";
		bHoldSelection = false;
		
		if( !isItemSelected() )
		{
			itemDrn.name = "Item.drn";
		}
		
		document.MessageList.submit();
	}
	else if( menuItem == 11 ) //move
	{
		hiddenAction.name = "Folder.List";
		bHoldSelection = false;
		
		if( !isItemSelected() )
		{
			itemDrn.name = "Item.drn";
		}
		
		document.MessageList.submit();
	}
	else if( menuItem == 8 ) //properties
	{
		var sUrl = baseURL + "&action=Item.Action&Item.Properties=&Item.Read=&Url.Folder.type=&tab=1&Folder.name=&Folder.id=&merge=msgitem&Item.drn=" + popupDrn + "&Item.Enclosure.id=" + popupDrn;

		popout( sUrl, "ItemView" );
	}
	else if( menuItem == 9 ) //open
	{
		doPopout(popupDrn, "&Url.Folder.type=" + inc_folderType + inc_findUpdateList + inc_rightsDeleteAndPost + inc_sentValue, 0);
	}
	else
	{
		alert( "Unhandled menu item: " + menuItem );
	}
}
*/

var context = "mailbox";
var calendarAnchor = null;
/***********************************************************************
*
**********************************************************************/
function selectTab(contextName)
{
	document.getElementById("gw-tb-" + context).className = "unselected";
	document.getElementById("gw-tb-" + contextName).className = "selected";
	context = contextName;
	
	//-----------------------------------------------
	// If the context is calendar, then modify the
	// URL to add item-type filter selection in the
	// Month view. Note that the current view type
	// and the filters (appts, notes, tasks) will be
	// saved in the caption's cache when availble.
	//-----------------------------------------------
	if( contextName === "calendar" )
	{
		//---------------------------------------------
		// initialize calendarAnchor once & reuse later
		// Note that "this.href" was not working right!
		//---------------------------------------------
		if( !calendarAnchor )
		{
			calendarAnchor = document.getElementById('calendarTabAnchor');
			calendarAnchor.hrefOrig = calendarAnchor.href;
		}
		
		//------------------------------------------------
		// append filter selection params if view == MONTH
		//------------------------------------------------
		calendarAnchor.href = calendarAnchor.hrefOrig + getCalItemTypesFilterURL();
	}
}

/***********************************************************************
*
**********************************************************************/
function mouseOverTab(name) 
{
	var gwId = document.getElementById("gw-tb-" + name);
	
	if(gwId.className == "unselected") 
	{
		gwId.className = "hover";
	}
}

/***********************************************************************
*
**********************************************************************/
function mouseOutTab(name) 
{
	var gwId = document.getElementById("gw-tb-" + name);
	if(gwId.className == "hover") 
	{
		gwId.className = "unselected";
	}
}
/***************************************************************
* This method will change the number of days displayed in the
* <select> control depending on what month/year are selected
* Used by: Calendar, Compose...
***************************************************************/
listHas = 31;
EndlistHas = 31;
function changeMonth(thisForm, bDueDate)
{
	// This is the current control
	var ctrlCurrentControl; 
	var curList = 0;

	if( gwwa.browser.name == "MSIE" )
	{
		if (bDueDate == 1)
		{
			year = parseInt(thisForm.elements['Calendar.queryEndYear'].value, 10);
			month = parseInt(thisForm.elements['Calendar.queryEndMonth'].value, 10);
			day = parseInt(thisForm.elements['Calendar.queryEndDay'].value, 10);
			ctrlCurrentControl = thisForm.qendday;
		} // if
		else
		{
			year = parseInt(thisForm.elements['Calendar.queryYear'].value, 10);
			month = parseInt(thisForm.elements['Calendar.queryMonth'].value, 10);
			day = parseInt(thisForm.elements['Calendar.queryDay'].value, 10);
			ctrlCurrentControl = thisForm.qday;
		} // else
	}
	else if( gwwa.browser.name == "MOZILLA" || gwwa.browser.name == "FIREFOX" )
	{
		if (bDueDate == 1)
		{
			iSelDay = thisForm.elements['Calendar.queryEndDay'].options.selectedIndex;
			day = parseInt(thisForm.elements['Calendar.queryEndDay'].options[iSelDay].value, 10);
			ctrlCurrentControl = thisForm.elements['Calendar.queryEndDay'];

			iSelMonth = thisForm.elements['Calendar.queryEndMonth'].options.selectedIndex;
			month = parseInt(thisForm.elements['Calendar.queryEndMonth'].options[iSelMonth].value, 10);

			iSelYear = thisForm.elements['Calendar.queryEndYear'].options.selectedIndex;
			year = parseInt(thisForm.elements['Calendar.queryEndYear'].options[iSelYear].value, 10);
		} // if
		else
		{
			iSelDay = thisForm.elements['Calendar.queryDay'].options.selectedIndex;
			day = parseInt(thisForm.elements['Calendar.queryDay'].options[iSelDay].value, 10);
			ctrlCurrentControl = thisForm.elements['Calendar.queryDay'];

			iSelMonth = thisForm.elements['Calendar.queryMonth'].options.selectedIndex;
			month = parseInt(thisForm.elements['Calendar.queryMonth'].options[iSelMonth].value, 10);

			iSelYear = thisForm.elements['Calendar.queryYear'].options.selectedIndex;
			year = parseInt(thisForm.elements['Calendar.queryYear'].options[iSelYear].value, 10);
		} // else
	}
	else
	{
		alert( gwwa.browser.name );
	}

	curMonthDays = 31;
	if (month == 4 || month == 6 || month == 9 || month == 11)
	{
		curMonthDays = 30;
	}
	else if (month == 2)
	{
		isLeap = 0;
		if (year % 4 == 0)
		{
			isLeap = 1;
			if (year % 100 == 0 && year % 400 != 0)
			{
				isLeap = 0;
			}
		}
		
		if (isLeap == 1)
		{
			curMonthDays = 29;
		}
		else
		{
			curMonthDays = 28;
		}
	}

	if (bDueDate)
	{
		curList = EndlistHas;
	} // if
	else
	{
		curList = listHas;
	} // else

	if (curList > curMonthDays)
	{
		// Remove extra days
		iCurSelected = day;
		if( gwwa.browser.name == "MSIE" && ctrlCurrentControl )
		{
			iCurSelected = ctrlCurrentControl.selectedIndex;
		}
		else if( gwwa.browser.name == "MOZILLA" || gwwa.browser.name == "FIREFOX" )
		{
			iCurSelected = ctrlCurrentControl.options.selectedIndex;
		}
	
		for (i = curList; i > curMonthDays; i--)
		{
			if( gwwa.browser.name == "MSIE" && ctrlCurrentControl )
			{
				if (iCurSelected == i-1)
				{
					ctrlCurrentControl.options[iCurSelected].selected = false;
					ctrlCurrentControl.options[i-2].selected = true;
					iCurSelected = i-2;
				}
				
				ctrlCurrentControl.options.remove(i-1);
			}
			else if( gwwa.browser.name == "MOZILLA" || gwwa.browser.name == "FIREFOX" )
			{
				if (iCurSelected == i-1)
				{
					ctrlCurrentControl.options[iCurSelected].selected = false;
					ctrlCurrentControl.options[i-2].selected = true;
					iCurSelected = i-2;
				}
				ctrlCurrentControl.options[i-1] = null;
			}
		}
	}
	else if (curList < curMonthDays)
	{
		// add additional days
		for (i = curList+1; i <= curMonthDays; i++)
		{
			if( gwwa.browser.name == "MSIE" && ctrlCurrentControl )
			{
				var newElem = document.createElement("OPTION");
				newElem.text = i;
				newElem.value = i;
				ctrlCurrentControl.options.add(newElem);
			}
			else if( gwwa.browser.name == "MOZILLA" || gwwa.browser.name == "FIREFOX" )
			{
				iCurSelected = ctrlCurrentControl.options.selectedIndex;
				len = ctrlCurrentControl.options.length;
				ctrlCurrentControl.options[len] = new Option(i, i, false, false);
				ctrlCurrentControl.options[iCurSelected].selected = true;
			}
		}
	}

	if (bDueDate)
	{
		EndlistHas = curMonthDays;
	} // if
	else
	{
		listHas = curMonthDays;
	} // else
}

/********************************************
* Set the focus in username field on the login
* page...
********************************************/
function setFocus()
{
	document.getElementById('username').focus();
	document.getElementById('username').select();
}


/********************************************
* 
********************************************/
function showOptions(event)
{

	var button = document.getElementById( "SettingsButton" );
	var obj = document.getElementById( "Options" );
	
	if( obj.className == "optionsVisible" )
	{
		obj.className = "optionsHidden";
		button.value = inc_SettingsStr_closed;
	}
	else
	{
		obj.className = "optionsVisible";
		button.value = inc_SettingsStr_open;
	}

}


/********************************************
* 
********************************************/
function readLoginSettings()
{	
	// See if a cookie is set for the login settings. Set the form if
	// the user wanted to remember the settings or if the bTempSave 
	// parameter is true.
	var userSettingsCookie = readCookie( "Cookie.User.settings" );
	var aSettings = {};

	// Parse the values out of the cookie string
	if( userSettingsCookie && userSettingsCookie.length > 0 )
	{
		var pairs= userSettingsCookie.split("&");
		var keyval;
		var i= 0;
		for ( ; i < pairs.length; i++)
		{
			keyval= pairs[i].split( "=" );
			aSettings[keyval[0]] = unescape(keyval[1]);
		}
	}

	// We only need to set things if the bTempSave parameter or
	// SaveSettingsCheckbox parameter is present
	if( aSettings['bTempSave'] == "1" || aSettings['SaveSettingsCheckbox'] == "1" )
	{

		// If present, set to low bandwidth
		if( aSettings['LowBandwidthRadio'] == "1" )
		{
			document.getElementById("User.settings.speed.low").checked = true;
		}
		
		// If present, set to simple interface
		if( aSettings['SimpleCheckbox'] == "1" )
		{
			document.getElementById("User.settings.simple").checked = true;
		}
		
		// Set the language
		if( document.getElementById("LangSelect") &&
			document.getElementById("LangSelect").value != aSettings['UserLanguage'] )
		{
			document.getElementById("LangSelect").value = aSettings['UserLanguage'];
			handleLangChange();
		}

		// If present, set to "remember my settings" checkbox
		if( aSettings['SaveSettingsCheckbox'] == "1" )
		{
			document.getElementById("User.settings.save").checked = true;
		}
		else
		{
			document.getElementById("User.settings.save").checked = false;
		}

		// If present, set options hidden
		if( aSettings['OptionsHidden'] == "1" && document.getElementById("Options").className == "optionsVisible" )
		{
			showOptions(null);
		}

	}
	else if( aSettings['SaveSettingsCheckbox'] == "0" )
	{
		document.getElementById("User.settings.save").checked = false;
	}


}	// readLoginSettings


/********************************************
* Save login settings to a cookie, "Cookie.User.settings"
* The bTempSave is parameter is set to true if this is to be saved temporarily
* (as in updating the login screen due to a language change) and not "permanently"
* as if the "remember my settings" checkbox was checked.
********************************************/
function saveLoginSettings( bTempSave )
{
	var UserLanguage = document.getElementById("LangSelect");
	var SimpleCheckbox = document.getElementById("User.settings.simple");
	var LowBandwidthRadio = document.getElementById("User.settings.speed.low");
	var SaveSettingsCheckbox = document.getElementById("User.settings.save");
	var OptionsHidden = document.getElementById("Options");

	var sCookie = "";

	if( SaveSettingsCheckbox.checked )
	{
		sCookie = "&SaveSettingsCheckbox=1";
	}
	else
	{
		sCookie = "&SaveSettingsCheckbox=0";
	}

	if( UserLanguage && UserLanguage.value && UserLanguage.value != "" )
	{
		sCookie += "&UserLanguage=" + UserLanguage.value;
	}

	if( bTempSave )
	{
		sCookie += "&bTempSave=1";
	}

	if( OptionsHidden.className == "optionsHidden" )
	{
		sCookie += "&OptionsHidden=1";
	}
	
	if( SimpleCheckbox.checked )
	{
		sCookie += "&SimpleCheckbox=1";
	}

	if( LowBandwidthRadio.checked )
	{
		sCookie += "&LowBandwidthRadio=1";
	}

	document.cookie = "Cookie.User.settings=" + sCookie + ";expires="+(new Date(new Date().getTime()+31104000000)).toGMTString()+";path=/;";;

}	// saveLoginSettings

/********************************************
* Fix up the parameters passed to the server when attempting to login
********************************************/
function fixSettings()
{
    var SimpleCheckbox = document.getElementById("User.settings.simple");
    var LowBandwidthRadio = document.getElementById("User.settings.speed.low");
    var SaveSettingsCheckbox = document.getElementById("User.settings.save");
    var SummerDate = new Date();
    var WinterDate = new Date();
    var CurrentGMTOffset = new Date().getTimezoneOffset();

    if (SimpleCheckbox.checked)
    {
        document.getElementById("UserInterface").value = "simple"; 
    }

    if (LowBandwidthRadio.checked)
    {
        document.getElementById("LowBandwidth").value = "1"; 
    }

    SummerDate.setTime(Date.parse("July 1, " + SummerDate.getFullYear()));
    WinterDate.setTime(Date.parse("January 1, " + SummerDate.getFullYear()));

	document.getElementById("WorkstationOffsetAvailable").value = "1"; 
	document.getElementById("WorkstationGMTOffset").value = (-1 * CurrentGMTOffset).toString();
    document.getElementById("WorkstationHasDaylight").value = ((SummerDate.getTimezoneOffset() !== WinterDate.getTimezoneOffset()) ? "1" : "0");
    document.getElementById("WorkstationIsDaylight").value = ((CurrentGMTOffset < Math.max(WinterDate.getTimezoneOffset(), SummerDate.getTimezoneOffset())) ? "1" : "0");

    // Save the user settings
    saveLoginSettings(false);

}

/***************************************************************
* 
***************************************************************/
function doPopout(drn, moreUrl, bIsDraft, bIsEditPost)
{
	var sTarget;
	var strUrl;
	if( bIsDraft )
	{
		strUrl = homeURL + "?action=Item.Compose&User.context=" + userContext + "&Item.drn=" + drn + "&merge=xsend" + moreUrl;
		sTarget = drn;
	}
	else if( bIsEditPost )
	{
		strUrl = homeURL + "?action=Item.EditPost&User.context=" + userContext + "&Item.drn=" + drn + "&Item.Compose.method=POST&Item.Folder.id=" + inc_folderId + "&merge=xsend" + moreUrl;
		sTarget = drn;
	}
	else
	{
		strUrl = homeURL + "?action=Item.Read&User.context=" + userContext + "&Item.drn=" + drn + "&merge=msgitem" + moreUrl;
		sTarget = "ItemView";
	}

	popout(strUrl, sTarget);
	return false;
}

/***********************************************************************
 * A helper function for trimming a given string
 **********************************************************************/
function trim(s)
{
	return s.replace( /^\s*|\s*$/g, "" );
}

/***********************************************************************
 * A helper function for trimming a given string
 **********************************************************************/
function modifyItemPosition(thArray, currentIndex, futureIndex)
{
	//-----------------------------------------------
	//
	//-----------------------------------------------
	if( currentIndex > futureIndex )
	{
		//-----------------------------------------------
		//
		//-----------------------------------------------
		var col = thArray[currentIndex];

		//-----------------------------------------------
		//
		//-----------------------------------------------
		for( var i = currentIndex; i > futureIndex; i-- )
		{
			thArray[i] = thArray[i - 1];
		}
		
		//-----------------------------------------------
		//
		//-----------------------------------------------
		thArray[futureIndex] = col;
	}
	//-----------------------------------------------
	//
	//-----------------------------------------------
	else if( currentIndex < futureIndex )
	{
		//-----------------------------------------------
		//
		//-----------------------------------------------
		var col = thArray[currentIndex];

		//-----------------------------------------------
		//
		//-----------------------------------------------
		for( var i = currentIndex; i < futureIndex - 1; i++ )
		{
			thArray[i] = thArray[i + 1];
		}
		
		//-----------------------------------------------
		//
		//-----------------------------------------------
		thArray[futureIndex - 1] = col;
	}
}

/***************************************************************
* 
***************************************************************/
function getPreferences()
{
	var json = null;
	var cookie = readCookie( "Cookie.prefs" );
	
	if( cookie && trim( cookie ).length > 0 )
	{
		json = eval( cookie );
	}

	return ( json ? json : {} );
}

/***************************************************************
* 
***************************************************************/
function deleteCookie(name)
{
	writeCookie(name, 0, -180);
}

/***************************************************************
* 
***************************************************************/
function writeCookieEx(name, value)
{
	var cookie = getPreferences();

	cookie[name] = value;	
	
	writeCookie( "Cookie.prefs", cookie.toSource(), 30 );
}

/***************************************************************
* 
***************************************************************/
function readCookieEx(name) 
{
	return getPreferences()[name];
}

/***************************************************************
* 
***************************************************************/
function writeCookie(name, value, days)
{
	var expiry = new Date();
	expiry.setTime( expiry.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
	document.cookie = name + "=" + value + ";expires=" + expiry.toGMTString();
}

/***************************************************************
* 
***************************************************************/
function readCookie(name) 
{
	var cks = document.cookie.split(';');

	for( var i = 0; i < cks.length; i++ ) 
	{
		var c = cks[i];

		while( c.charAt(0) == ' ' )
		{
			c = c.substring(1,c.length);
		}

		if( c.indexOf( name + "=" ) == 0 )
		{
			return c.substring( name.length + 1, c.length );
		}
	}

	return null;
}

/***************************************************************
* 
***************************************************************/
function createMenu(menu) 
{
	var table = document.createElement("table");
	var tbody = document.createElement("tbody");
	
	//-----------------------------------------------
	//
	//-----------------------------------------------
	table.id = menu.id;
	table.className = "popup popupHide";

	//-----------------------------------------------
	//
	//-----------------------------------------------
	for( var i = 0; i < menu.menuItems.length; i++ )
	{
		addMenuItem(tbody, menu.menuItems[i], menu.onclickHandler);
	}

	//-----------------------------------------------
	//
	//-----------------------------------------------
	table.appendChild(tbody);
	document.body.appendChild(table);

	//-----------------------------------------------
	// save the original onclick handler on the menu 
	// created (will be used by the smart menus later)
	//-----------------------------------------------	
	table.onclickHandler = menu.onclickHandler;

	return table;
}

/***************************************************************
* 
***************************************************************/
function addMenuItem(tbody, menuItem, onclickHandler)
{
	var tr = document.createElement("tr");
	tbody.appendChild(tr);
	
	//-----------------------------------------------
	//
	//-----------------------------------------------
	setEventHandlers(tr, onclickHandler);
	
	//-----------------------------------------------
	//
	//-----------------------------------------------
	var tdIcon = document.createElement("td");
	tdIcon.className = "icon";
	tr.appendChild(tdIcon);

	//---------------------------------------------
	// Actions like "Open", "Properties", etc does
	// not have images associated with the action,
	// hence create the image element when needed
	//---------------------------------------------
	if( menuItem.imgSrc )
	{
		var img = document.createElement("img");
		img.src = inc_templatesImagesUrl + menuItem.imgSrc;
		img.alt = menuItem.title;
		
		img.title = menuItem.title;

		menuItem.imgWidth = ( menuItem.imgWidth >= 0 ) ? menuItem.imgWidth : "16";
		img.width = menuItem.imgWidth;

		menuItem.imgHeight = ( menuItem.imgHeight >= 0 ) ? menuItem.imgHeight : "16";
		img.height = menuItem.imgHeight;

		tdIcon.appendChild(img);
	}

	if( menuItem.imgSrc2 )
	{
		var img = document.createElement("img");
		img.src = inc_templatesImagesUrl + menuItem.imgSrc2;
		img.alt = menuItem.title;
		img.title = menuItem.title;
		img.width = "8";
		img.height = "16";

		tdIcon.appendChild(img);
	}
	
	//-----------------------------------------------
	//
	//-----------------------------------------------
	var tdText = document.createElement("td");
	tr.appendChild(tdText);

	//-----------------------------------------------
	//
	//-----------------------------------------------
	var text = document.createTextNode(menuItem.title);
	tdText.appendChild(text);
	
	//-----------------------------------------------
	//
	//-----------------------------------------------
	tr.menuItem = menuItem;
	menuItem.tr = tr;
	
	return tr;
}

/***********************************************************
*
***********************************************************/
enableMenuItem = function( menuItemTR )
{
	if( menuItemTR.onclickHandler )
	{
		menuItemTR.onclick = menuItemTR.onclickHandler;
	}

	menuItemTR.onclickHandler = null;
	menuItemTR.onmouseout = menuItemOut;
	menuItemTR.onmouseover = menuItemOver;
	menuItemTR.style.color = "black";
	menuItemTR.childNodes[1].style.color = "black";
	
	//---------------------------------------------------
	// If the <tr> was made hidden in disableMenuItem(),
	// then reset the class to make it visibible agian.
	//---------------------------------------------------
	showMenuItem( menuItemTR );
}

/***********************************************************
*
***********************************************************/
disableMenuItem = function( menuItemTR, hideAction )
{
	if(menuItemTR.onclick)
	{
		menuItemTR.onclickHandler = menuItemTR.onclick;
	}
	
	menuItemTR.onclick = null;
	menuItemTR.onmouseout = null;
	menuItemTR.onmouseover = null;
	menuItemTR.style.color = "gray";
	menuItemTR.childNodes[1].style.color = "gray";

	//---------------------------------------------------
	// Majority of the actions in item right-click popup 
	// are not applicable to most items. Graying out is 
	// less appealing than hiding the action in the menu.
	//---------------------------------------------------
	if( hideAction )
	{
		hideMenuItem( menuItemTR );
	}
}

/***********************************************************
*
***********************************************************/
showMenuItem = function( menuItemTR )
{
	//---------------------------------------------------
	// If the <tr> was made hidden in disableMenuItem(),
	// then reset the class to make it visibible agian.
	//---------------------------------------------------
	util.removeClass( menuItemTR, "hideAction" );
}

/***********************************************************
*
***********************************************************/
hideMenuItem = function( menuItemTR )
{
	//---------------------------------------------------
	// Majority of the actions in item right-click popup 
	// are not applicable to most items. Graying out is 
	// less appealing than hiding the action in the menu.
	//---------------------------------------------------
	util.addClass( menuItemTR, "hideAction" );
}

/***************************************************************
* 
***************************************************************/
function setEventHandlers(tr, onclickHandler)
{
	//-----------------------------------------------
	//
	//-----------------------------------------------
	tr.onmouseover = menuItemOver;
	tr.onmouseout = menuItemOut;
	tr.onclick = onclickHandler;
}

/***************************************************************
* 
***************************************************************/
function getNextHourTime( /*Long*/ startTime )
{
	//-------------------------------------------
	// default to user's work station time if a 
	// specific start time is unavailable...
	//-------------------------------------------
	if( startTime === undefined )
	{
		startTime = new Date();
	}
	else // specific start time is available
	{
		startTime = new Date( startTime );		
		
		//--------------------------------------------
		// update specific date's hour to current hour
		// Ex: 00:00:00 GMT to 4:00:00 GMT
		//--------------------------------------------
		var calNow = new Date();
		startTime.setUTCHours( calNow.getUTCHours(), 0, 0 );
	}

	//------------------------------
	// apply user's time zone offset
	//------------------------------
	startTime.setTime( ( startTime.getTime() ) + ( 1000 * gwwa.user.timezoneOffset ) );	
	
	//------------------------------------------------------
	// shift time to next hour (reset minutes and seconds
	// explicitly, otherwise original values will be used)
	//------------------------------------------------------
	startTime.setUTCHours( ( startTime.getUTCHours() + 1 ), 0, 0 );
	
	return startTime.getTime();
}

/***********************************************************
* This function modified the "Calendar" tab anchor's href
* to include the item-type filter selection in Month view
* as they are saved in the caption windows's cache. This
* common func is used by gwwa.gcal.getCalendarRequestURL()
* in gcal.js file.
***********************************************************/
getCalItemTypesFilterURL = function()
{
	var sURL = "";
	
	//------------------------------------------------
	// retrieve calendar's most recent view from cache
	//------------------------------------------------
	var currentCalView = getCachedObject( "currentCalView" );

	//-----------------------------------------------------------
	// Calendar's current view will be set right after first time
	//-----------------------------------------------------------
	if( currentCalView && currentCalView.toUpperCase() === "MONTH" )
	{
		//-----------------------------------------
		// retrieve month view's filters from cache
		//-----------------------------------------
		var itemTypeFilters = getCachedObject( "itemTypeFilters" );

		//---------------------------------------------------
		// check if at least filter is selected, otherwise
		// Provider has to return with empty item list vector
		//---------------------------------------------------
		if( itemTypeFilters.appts || itemTypeFilters.notes || itemTypeFilters.tasks ) 
		{
			// APPOINTMENT
			if( itemTypeFilters.appts )
			{
				sURL += "&Calendar.queryMessageType=APPOINTMENT";
			}

			// TASK
			if( itemTypeFilters.tasks )
			{
				sURL += "&Calendar.queryMessageType=TASK";
			}

			// NOTE
			if( itemTypeFilters.notes )
			{
				sURL += "&Calendar.queryMessageType=NOTE";
			}
		}
		else
		{
			//---------------------------------------------
			// All filters are unselected, set the empty
			// param so that we can distinguish between
			// clicking on Calendar tab verses all filters
			// unselected scenarios
			//---------------------------------------------
			sURL += "&Calendar.queryMessageType=";
		}
	} // end if

	return sURL;

}; // getCalItemTypesFilterURL

/***********************************************************
*
***********************************************************/
function userLogout()
{
	var logoutURL = homeURL + "?User.context=" + userContext + "&action=User.Logout&merge=login";
	var callback = { success: handleUserLogout, failure: handleUserLogout, argument: null };

	deleteCookie( "NJSCN" );

	YAHOO.util.Connect.asyncRequest( 'GET', logoutURL, callback ); 
}

/***********************************************************
*
***********************************************************/
function handleUserLogout()
{
}

/*****************************************************
*
*****************************************************/
function cloneObject( obj ) 
{
	for ( property in obj ) 
	{
		if (typeof obj[property] == 'object') 
		{
			this[property] = new cloneObject( obj[property] );
		}
		else
		{
			this[property] = obj[property];
		}
	}
}

/*****************************************************
*
*****************************************************/
function cloneArray( objArray )
{
	var clonedArray = [ ];
	if ( objArray )
	{
		for( var i = 0; i < objArray.length; i++ )
		{
			clonedArray[i] = new cloneObject( objArray[i] );
		}
	}
	
	return clonedArray;
}

function detectParentFrame()
{
	var parentFrame = window.self;
	var childFrame;
	try{
		while( parentFrame.webaccFrame && parentFrame != childFrame )
		{
			childFrame = parentFrame;
			parentFrame = parentFrame.parent;				
		}	
	}catch(e){
		//If an error occurs is because we can't obtain the parent frame name because we don't have permissions,
		// this means we are not in the webaccess frame anymore.
	}	
	
	window.document.loginForm.target = childFrame.name;
}