// Common routines used by iPathmaker

// Input text field name format MUST be: ITaabbb
// Input cell(TD) name format MUST be: TDaabbb
// Col header cell name format Must be: CHaa000
// Row header cell name format MUST be: RH00bbb
//   aa  -- Column
//   bbb -- Row

// Global variables.

// add by lianying 05/13/2005. bug id 997.
//var bDisableRightClickMenu = false;
//document.oncontextmenu = onRightClickMenu;
ff5 = navigator.appName == 'Netscape' ? true : false; //mozilla firefox
function onRightClickMenu()
{
    return bDisableRightClickMenu;
}

//var vObjHeader	; // add by xiahaobo 12/17/2004 ,bug id 2824, if use0.jsp unload then can't make the checkappletmessage run!
// add by xiahaobo 12/17/2004 ,bug id 2824, if use0.jsp unload then can't make the checkappletmessage run!

/*
if(typeof(window.top) != 'undefined')
{
	//vObjHeader = window.top.document.getElementById("txtAllCheckAppletMsg") ;//getElementById("txtAllCheckAppletMsg") ;
	//vObjHeader.value = "false" ;
}
*/

var bDebug	= false;						// Is it in debug mode?

var bPMWAppletHeaderFrame = false;		// variable to determine whether or not header frame is found when page is called.
var bInAction		= false;			// Is client processing previous action?
var bTimerEnabled 	= true;				// The indicator that if PMW should do scheduled tasks.
										// We have to disable the timer sometimes, such as waiting the response from server.
var bHasControl	  	= false;			// If user has control right on current tool
var bEditing		= false;			// If user is in editing mode.
var nSelectedRow	= 0;				// The row offset of current selected row
var nSelectedCol	= 0;				// The column offset of current selected row
var nRowOffset		= 0;				// The row that data starts.
										// In some tables, the row numbers of the column header part are differnt.
var nColOffset		= 0;				// The column that data starts
										// In some tables, the column numbers of the row header part are differnt.
var bLoaded			= false;			// If the page has been loaded completely.

var sCurrentUserId 		= "";			// Current user ID

var bKeepControl = false;

// Variables used for drop down box for user's group and project
var aProjNameList 	= new Array();
var aProjIDList 	= new Array();
var aGroupIDList 	= new Array();

// Variables used for remind users in my calendar
var aUGIDList2 	= new Array();
var aUGUserList = new Array();

// The current editing field. Used for refocus to the field after buddy list refresh
var editingField = null;

// add by lianying 05/19/05. bug id 953.
var myHelpWindow = null;

var bPopup = false;

// Check whether the user has control right on a tool or not
function hasControl()
{
	return bHasControl;
}

// Check whether the user is editing a cell or not
function isEditing()
{
	return bEditing;
}

// add by haifeng 02/17/2005. Check whether the page has been loaded completely.
function hasLoaded()
{
    return bLoaded;
}

// Write today's date string to window
function todaysdate()
{
	// Used for date
	today = new Date();
	var year = today.getFullYear();
	var monthnum = today.getMonth();
	var date = today.getDate();
	var day = today.getDay();

	document.write(aWeekString[day] + ", " + (aMonthStrings[monthnum]) +" "+ (date) + ", "+ (year));
}

// Ask PMWApplet to connect to server
// Param:	vUserId		The login ID of the user
function connect(vUserId)
{
    var myApplet = window.top.PMWApplet;  // add by  lianying 03/28/2005.
	if (myApplet.isConnected())
		return;

//	window.top.PMWApplet.bConnectViaSocket = false;

	myApplet.setUserId(vUserId);
	var bConnected = myApplet.connectToServer();

	if (bConnected)
	{
		sCurrentUserId = vUserId;
	}
	else
	{
		alert("We were unable to connect you to the server. Please try again.");
		document.location = "Start.jsp?Signout=1";
		myApplet.setUserId("");
	}
}

// Disconnect from the server
function disconnect()
{
	window.top.PMWApplet.disconnect();
}

// Delay applet
// Param: vDelay		delay time in mili-second
function delay(vDelay)
{
	window.top.PMWApplet.sleep(vDelay);
}

// Get the specified command data from the server.
// Usually we use it to get the return value after sending a command/request to server
// Param: 	vCmdId		command id
// 			vDelay		delay time in mili-second
function getCommandData(vCmdId, vDelay)
{
   var sRetVal = "";
 
   var msg=window.top.PMWApplet.getInnerparam(vCmdId);

	
	//	alert(msg.sData);
	 sRetVal=""+msg.sData;
   return sRetVal;
}

// Disable the timer
function disableTimer()
{
	bTimerEnabled = false;
}

// Enable the timer
function enableTimer()
{
	bTimerEnabled = true;
}

// Processes messages gets from server.
function checkAppletMessage()
{
	var bAllowCheckAppletMsg;			//add by xiahaobo 12/17/2004 ,bug id 2824, if use0.jsp unload then can't make the checkappletmessage run!
//	bAllowCheckAppletMsg = vObjHeader.value	;

	var myApplet = window.top.PMWApplet;
	if (bAllowCheckAppletMsg=="true")
	{
		if (!bTimerEnabled)
		{
			window.setTimeout("checkAppletMessage()", 1000, "JAVASCRIPT" );
			return;
		}

		var temp = 0;
		// Read the message queue from the front, instead of the rear.
		var nMsg = 0;	//index of the current message being processed
		var nCount = myApplet.getJSMessageCount();

		disableTimer();

		for(var j = 0; j < nCount; j++)
		{
			var msg  = myApplet.getJSMessage(nMsg);

			if (msg == null)
				break;
			var bProcessed = true;
			if (msg.nMsgId == COMMAND_REFRESH)
			{
				if (!isEditing() && bLoaded)
					reloadPage();
				else
					bProcessed = false;
			}
			else if (msg.nMsgId == COMMAND_REFRESH_PATHWAY)
			{
				if (isEditing())
					bProcessed = false;
				//// modify by haifeng 12/02/2004,bug id 887. for not refresh window when it's not pathway page. such as HyperLink add page
				//	else if (window.top.PMWApplet.getToolType() == TOOL_PATHWAY )
				else if (myApplet.getToolType() == TOOL_PATHWAY && myApplet.getHelpIndex() == "Pathway")
						reloadPage(); // use a cover method in  Pathway.js
			}
			else if (msg.nMsgId == COMMAND_REFRESH_PROJINFO)
			{
				if (isEditing())
					bProcessed = false;
				else if (myApplet.getToolType() == TOOL_PROJECTINFORMATION)
						reloadPage();
			}
			else if ((msg.nMsgId == COMMAND_REFRESH_TEAMMEMBER))
			{
				if (isEditing())
					bProcessed = false;
				else
					refreshIfAtPage("TeamMember.jsp");
			}
			// add by linliming 05/12/2005, task id 1132.
			else if ((msg.nMsgId == COMMAND_REFRESH_CONTACT))
			{
				if (isEditing())
					bProcessed = false;
				else
					refreshIfAtPage("Contact0.jsp");
			}

			// add by linliming 05/13/2005, task id 1131.
			else if ((msg.nMsgId == COMMAND_REFRESH_SCORECARD))
			{
				if (isEditing())
					bProcessed = false;
				else
					refreshIfAtPage("ScoreCard0.jsp");
			}

			// add by linliming 05/13/2005, task id 1129.
			else if ((msg.nMsgId == COMMAND_REFRESH_FORUM))
			{
				if (isEditing())
					bProcessed = false;
				else
					refreshIfAtPage("Forum_Home.jsp");
			}

			// add by linliming 05/31/2005, task id 1130.
		   else if(msg.nMsgId == COMMAND_REFRESH_NEWS)
		   {
		        if(isEditing())
		        {
		        	bProcessed = false;
		        }
		        else
		        	refreshIfAtPage("News0.jsp");
		   }

			else if ((msg.nMsgId == COMMAND_REFRESH_ACTIONITEM))
			{
				if (isEditing())
					bProcessed = false;
				else
					refreshIfAtPage("ActionItem.jsp");
			}
			else if ((msg.nMsgId == COMMAND_REFRESH_DISCUSSION))
			{
				if (isEditing())
					bProcessed = false;
				else
					refreshIfAtPage("ChatManagement.jsp");
			}
                        // add by lianying 05/17/2005. bug id 1126.
                        else if (msg.nMsgId == COMMAND_REFRESH_CALMONTH)
            		{
                		if (isEditing())
					bProcessed = false;
				else
					refreshIfAtPage("CalMonth.jsp");
            		}
			else if ((msg.nMsgId == COMMAND_REFRESH_FILEMANAGEMENT))
			{
				if (isEditing())
					bProcessed = false;
				else
					refreshIfAtPage("FileManagement.jsp");
			}
			else if (msg.nMsgId == COMMAND_REFRESH_PROJNAME)
			{
				window.top.refreshProjectName();
			}
			else if (msg.nMsgId == COMMAND_REFRESH_UG_NAME)
			{
				window.top.refreshUGName();
			}
			else if (msg.nMsgId == COMMAND_REFRESH_BUDDY_LIST)
			{
				window.top.refreshBuddyList();
			}
			else if (msg.nMsgId == COMMAND_REFRESH_MY_BUDDY_LIST)
			{
				window.top.refreshMyBuddyList();
			}
			else if (msg.nMsgId == COMMAND_UPDATE_CONTROLLER)
			{
				var sController = msg.sData;
				window.top.PMWApplet.setController(sController);
				updateController();
			}
			else if (msg.nMsgId == COMMAND_OPENFLOORMODE)
			{
				openFloorStatus(strToInt(msg.sData), true);
			}
			else if (msg.nMsgId == COMMAND_UPDATE)
			{
				updateCell(msg);
			}
			else if (msg.nMsgId == COMMAND_UPDATE_FF_QUESTION)
			{
				updateFFQuestion(msg);
			}
			else if (msg.nMsgId == COMMAND_CHOOSE_VOTER)
			{
				updateVoterSelection(msg, true);
			}
			else if (msg.nMsgId == COMMAND_UNCHOOSE_VOTER)
			{
				updateVoterSelection(msg, false);
			}
			else if (msg.nMsgId == COMMAND_CB_REFRESH_RESULT)
			{
				refreshResult(msg);
			}
			else if (msg.nMsgId == COMMAND_BS_OPENMODE_ADDROW)
			{
				addIdeaFromBuddy(msg);
			}
			else if (msg.nMsgId == COMMAND_BS_ADDIDEA)
			{
				addIdeaFromBuddy(msg);
			}
			else if (msg.nMsgId == COMMAND_DD_BSBS)
			{
				adjust_DD_BSBS(msg);
			}
			else if (msg.nMsgId == COMMAND_DD_BSAFF)
			{
				adjust_DD_BSAFF(msg);
			}
			else if (msg.nMsgId == COMMAND_DD_AFFAFF)
			{
				adjust_DD_AFFAFF(msg);
			}
			else if (msg.nMsgId == COMMAND_DD_AFFHAFFH)
			{
				adjust_DD_AFFHAFFH(msg);
			}
			else if (msg.nMsgId == COMMAND_DD_AFFBS)
			{
				adjust_DD_AFFBS(msg);
			}
			else if (msg.nMsgId == COMMAND_DD_AFFHBS)
			{
				adjust_DD_AFFHBS(msg);
			}
			else if (msg.nMsgId == COMMAND_BS_SET_IDEAID)
			{
				setIdeaId(msg);
			}
			else if (msg.nMsgId == COMMAND_CB_SELECTALL)
			{
				updateAllVoters(msg, true);
			}
			else if (msg.nMsgId == COMMAND_CB_DESELECTALL)
			{
				updateAllVoters(msg, false);
			}
			else if (msg.nMsgId == COMMAND_REFRESH_CHAT_USER_NUMBER)
			{
				refreshChatOnlineNum(msg);
			}
			else if (msg.nMsgId == COMMAND_OPEN_INVITED_CHAT)
			{
				window.top.displayInvitedChat(strToInt(msg.sData));
			}
			else if (msg.nMsgId == COMMAND_WARN_DELETE_GROUP)
			{
				alert(msg.sData);
			}
			else if (msg.nMsgId == COMMAND_WARN_DELETE_PROJECT)
			{
				alert(msg.sData);
			}
			else if (msg.nMsgId == COMMAND_REMOVE_DUP_USER)
			{
				onForcedLogOut(2);

				//add by xiahaobo 12/07/2004 ,bug id 2664
				//if the user be removed then the Event Message must be Killed, so add "return"
				myApplet.deleteJSMessage(nMsg);
				return ;
			}
			else if (msg.nMsgId == COMMAND_CB_RESETUP)
			{
				self.location.href="CB_Setup.jsp?ToolId=" + msg.nToolId;
			}
			else if (msg.nMsgId == COMMAND_WARN_DELETE_GROUPUSER)
			{
				//nRow is group id, sData is group name.
				 // add by xiahaobo , bug id 2922, 05/20/2005
				if (msg.nCol == 0)
				{
					if (msg.nRow == strToInt(myApplet.getUGId()))
					{
						alert("You have been deleted from this Group: " + msg.sData);
						reloadUser0();
					}
				}
				else
				{
					if (msg.nRow == strToInt(myApplet.getUGId()))
						refreshIfAtPage("ViewUGMembers.jsp");
				}
/*				else
				{
					alert("You have been deleted from this Group: " + msg.sData);
				}
*/
			}
			else if (msg.nMsgId == COMMAND_WARN_DELETE_PROJECTUSER)
			{
				//nCol is project id, sData is project name.
				if (msg.nRow == 0)
				{
					alert("You have been deleted from this Project: " + msg.sData);
					if (msg.nCol == strToInt(myApplet.getProjectId()))
					{
					         // modify by xiahaobo ,bug id 2922 ,05/20/2005
						//reloadUser0();
						window.location.href="Group0.jsp?GroupId=" + this.top.PMWApplet.getUGId();
					}
					else
					{
						refreshIfAtPage("User0.jsp");
						refreshIfAtPage("Group0.jsp");
					}
				}
				else
				{
					if (myApplet.getToolType() == TOOL_TEAMMEMBERS)
						reloadPage();
				}
			}
			else if (msg.nMsgId == COMMAND_NEW_TEAMMEMBER)
			{
				alert("You have been selected as a team member of the Project: " + myApplet.getProjectName());
				//refreshIfAtPage("User0.jsp");
				refreshIfAtPage("Group0.jsp");
			}
			else if (msg.nMsgId == COMMAND_UPDATE_MEETINGINFO)
			{
				updateMeetingInfo(msg);
			}
			else if (msg.nMsgId == COMMAND_UPDATE_MEETINGMISC)
			{
				updateMeetingMisc(msg);
			}
			else if (msg.nMsgId == COMMAND_UPDATE_MEETINGMEMBERS)
			{
				updateMeetingMembers(msg);
			}
			else if	(msg.nMsgId == COMMAND_UPDATE_MEETINGAI)
			{
				updateMeetingAI(msg);
			}
			else if (msg.nMsgId == COMMAND_UPDATE_MEETINGTOOL)
			{
				updateMeetingTool(msg);
			}
			else if (msg.nMsgId == COMMAND_INSERT_ROW_MS)
			{
				insertManualStepRow(msg);
			}
			else if (msg.nMsgId == COMMAND_UPDATE_MANUALSTEP)
			{
				updateMeetingTool(msg);
			}
			else if (msg.nMsgId == COMMAND_DELETE_ROW_MS)
			{
				deleteMeetingRow(msg);
			}
			else if (msg.nMsgId == COMMAND_UPDATE_COLWIDTH)
			{
				onUpdateColWidth(msg);
			}
			else if (msg.nMsgId == COMMAND_DA_CHANGE_BREAKS)
			{
				changeDASerieBreaks(msg);
			}
			else if (msg.nMsgId == COMMAND_SETVIEWSTATUS)
			{
				updateViewStatus(msg);
			}
			// communication broken.
			else if (msg.nMsgId == COMMAND_DISCONNECTED)
			{
				alert("Your connection to the server has been interrupted. Please log in again.");

				//If user lost connection, forced out and use default logo and disapper info section in header.
				//top.Working.window.top.showInfoSection(false);
				//top.Working.window.top.doChangeLogoDefault();
				onForcedLogOut(1);
			}
			else if (msg.nMsgId == COMMAND_CB_UPDATE_VOTEMODE){
				updateVoteMode(msg);
			}
			else if (msg.nMsgId == COMMAND_FMEA_UPDATE_ACTION){
				updateFmeaIcon(msg);
			}
			else if (msg.nMsgId == COMMAND_CB_SHOW_VOTERLIST){
				showVoterList(msg);
			}
			// add by haifeng 09/09/2004,bug id 5408
			else if (msg.nMsgId == COMMAND_CB_SHOW_UNSELECTEDMEMBER){
				showUnselectedMember(msg);
			}
			else if (msg.nMsgId == COMMAND_CHANGE_TM_PRIVILEGES)
			{
				if (msg.sData == myApplet.getUserId())
				{
					window.top.nTMPrivileges = msg.nRow;
					updateButtonStatus();

					if (hasControl() && (msg.nRow == TM_PRIVILEGES_VIEWER))
					{
						alert("Your project privileges have been changed to: Viewer");
						releaseControl();
					}
				}
			}
			else if (msg.nMsgId == COMMAND_AI_ADD_NOTE)
			{
				updateAICommentIcon(msg);
				updateAICommentStuts(msg); //add by linliming ,04/26/2005, bug id 979.
			}
			else if (msg.nMsgId == COMMAND_SET_BS_NEWIDEAIDS)
			{
				setIdeaIDs("workingArea", msg);
			}
			else if (msg.nMsgId == COMMAND_SET_AF_NEWIDEAIDS || msg.nMsgId == COMMAND_SETHEADERID)
			{
				setIdeaIDs("affinityArea", msg);
			}
			else if (msg.nMsgId == COMMAND_UPDATE_FMEAINFO || msg.nMsgId == COMMAND_UPDATE_FMEAPARTICIPANT)
			{
				updateFmeaInfo(msg);
			}
			else if (msg.nMsgId == COMMAND_UPDATE_FMEALIST)
			{
				updateFmeaList(msg);

				if((msg.nCol > 3) && (msg.nCol < 7))
					changeListNum(msg.nRow);
			}
			else if (msg.nMsgId == COMMAND_DELETE_ROW_FMEA)
			{
				removeListRow(msg.nRow);
			}
			else if (msg.nMsgId == COMMAND_UPDATE_RCA_ACTION)
			{
				updateActionList(msg);
			}
			else if (msg.nMsgId == COMMAND_FMEA_UPDATE_ACTION)
			{
				updateNoteIcon(msg);
			}
			else if ((msg.nMsgId == COMMAND_REFRESH_MEETING))	//add by xiahaobo,01/18/2005,bug id 578,description:if delete ,refresh meeting
			{
				if (bHasControl)				//whether user is editing
				{
					if(window.confirm("Another team member has changed one of the action items or one of agenda items. Do you want to reload this page?"))
						refreshIfAtPage("Meeting.jsp") ;
				}
				else
					refreshIfAtPage("Meeting.jsp");
			}
			else if ((msg.nMsgId == COMMAND_REFRESH_MEMBER))	//add by xiahaobo,01/18/2005,bug id 578,description:if delete ,refresh meeting
			{
				//refreshIfAtPage("ViewUGMembers.jsp");
				window.location.href= "ViewUGMembers.jsp?ugId=" + myApplet.getProjectId() ;
			}
			else
			{
				// In some cases, the message should be processed by another
				// routine, not this general routine.
				// For example, an action that requires response from server.
				bProcessed = false;
				//	alert("Un-handled message. Message = " + msg.nMsgId);
			}

			if (bProcessed)
			{
				myApplet.deleteJSMessage(nMsg);
			}
			else
			{
				nMsg++;
			}
		}
		enableTimer();
	}
	window.setTimeout("checkAppletMessage()", 1000, "JAVASCRIPT");
}

// Change Data Analyst Serie Breaks
// Param: 	msg		message recieved
function changeDASerieBreaks(msg)
{
}

// Update cell to the new value from server
// Param: 	msg		message recieved
function updateCell(msg)
{
	if (window.top.PMWApplet.getToolId() == msg.nToolId)
	{
		var sFieldName = "IT" + intToStr(msg.nCol, 2, "0") + intToStr(msg.nRow, 3, "0");
		document.getElementsByName(sFieldName)[0].value = msg.sData;
	}
}

// Update the controller
function updateController()
{
	var controller = document.getElementById("controller");
	if (controller == null)
		return;
//alert("window.top.PMWApplet.getController()="+window.top.PMWApplet.getController());
	controller.value = "Controller: " + window.top.PMWApplet.getController();
}


// This function was same as waitResult(). It is too slow to check the execute
// result for each action. If an action that relates to forward to another page,
// and that page will use the data that updataed by the action, please use
// waitResult(). Because I don't want to take out getResult() out from all
// JS pages.
function getResult()
{
	return true;
}

// Wait for the result from server
function waitResult()
{
	var sResult = getCommandData(COMMAND_SET_RESULT, 1000);
	if (sResult == RESULT_FAILED)
		return false;
	else
		return true;
}

// Handle row selecting
function onSelectRow(e)
{
	if(isEditing())
		return;

	// The event should be fired from TD or controls
	var current = getDragDropObject(e); //var current = event.srcElement;
	if (current.nodeName == "TR")//if (current.tagName == "TR")
		return;

	if(current.nodeName =="#text")
	{
		current = current.parentNode ;
	}

	// clear current selections
	if (nSelectedCol > 0)
		deselectCol("workingArea", nSelectedCol);

   	deselectRow("workingArea", nSelectedRow);

	// We require the format of the name

	var i = strToInt(current.id.substr(4, 3)); //var i = strToInt(current.name.substr(4, 3));
	if (i==0)
		return;

	nSelectedRow = i;

	selectRow("workingArea", nSelectedRow);
	updateButtonStatus();
}

// Handle column selecting
function onSelectCol(e)
{
	if (isEditing())
		return;

	// Clear selections
	if (nSelectedRow > 0)
		deselectRow("workingArea", nSelectedRow);

   	deselectCol("workingArea", nSelectedCol);

	//var current = event.srcElement;
	var current = getDragDropObject(e);
	var i = strToInt(current.id.substr(2, 2));
	if (i==0)
		return;

	nSelectedCol = i;
	selectCol("workingArea", nSelectedCol);

	// add by linliming, 08/05/2005, bug id 5410.
	var myTableBody = getTableBody("workingArea");
	//var nWidthNarrow = strToInt(myTableBody.childNodes[1].childNodes[nSelectedCol].width) + strToInt(COL_SHORTEN);
	//var nWidthWide = strToInt(myTableBody.childNodes[1].childNodes[nSelectedCol].width) + strToInt(COL_WIDEN);

	var nWidthNarrow = strToInt(getObjectWithoutComment(nSelectedCol, getObjectWithoutComment(1, myTableBody)).width) + strToInt(COL_SHORTEN);
	var nWidthWide   = strToInt(getObjectWithoutComment(nSelectedCol, getObjectWithoutComment(1, myTableBody)).width) + strToInt(COL_WIDEN);


	if((nWidthNarrow < strToInt(COL_SHORTEN)*(-1)) || (nWidthNarrow == strToInt(COL_SHORTEN)*(-1)))
	{
		bNarrowLimit = true;
	}
    else
    {
    	bNarrowLimit = false;
    }

    if((nWidthWide > (245+strToInt(COL_WIDEN)*23)) || (nWidthWide == (245+strToInt(COL_WIDEN)*23)))
    {
    	bWideLimit = true;
    }
    else
	{
		bWideLimit = false;
	}

	updateButtonStatus();
}

// Handle start editing event.
function onStartEditing(e)
{
	// Add by haifeng 09/27/2004 , bug id 5452
	if (!bLoaded)
	    return;

	if (((window.top.PMWApplet.getToolType() == TOOL_BRAINSTORM) || (window.top.PMWApplet.getToolType() == TOOL_AFFINITIES)) && bOpenFloorMode)
	{
		alert(MSG_OPEN_FLOOR_MODE_EDIT);
		return;
	}

	var current = getDragDropObject(e) ;//event.srcElement;

	if (!bHasControl && current.tagName != "B")
	{
		alert(MSG_NOT_HAVE_CONTROL);
		return;
	}

	if (current.tagName == "TD")
		return;

	editingField = current;

	deselectRow("workingArea", nSelectedRow);
	deselectCol("workingArea", nSelectedCol);

	current.disabled = false;
	current.focus();

	bEditing = true;
}

// modified by zhanghuajie 060328 ,for supporting FireFox
// Handle when user finish with cell editing
// Param: 	e 	the window event
function onEndEditing(e)
{
	onEndEditingWithLength(0,getDragDropObject(e));

	return true;
}

//modified by liuwei
function onEndEditingProject(e,ToolType)
{
	onEndEditingWithLengthNew(0,getDragDropObject(e),ToolType);

	return true;
}


// modified by zhanghuajie 060328 ,for supporting FireFox
// Send command to server to update and check the length of the input data; truncating String if needed
// Param: 	vLength 	maximum length allowed for input data. Don't check the length if vLength is 0.
function onEndEditingWithLength(vLength ,vObj)
{

	var current = vObj ;// event.srcElement;
	var row = strToInt(current.id.substr(4, 3)); //strToInt(current.name.substr(4, 3));
	var col = strToInt(current.id.substr(2, 2)); //strToInt(current.name.substr(2, 2));
	var s	= current.value;

	if(vLength == 0 && s.length > 2000)
	{
		alert("The maximum lenth of the field is 2000 characters. The data has been truncated.");
		s = s.substr(0, 2000);
		current.value = s;
	}

	if((vLength > 0) && (s.length > vLength))
	{
		alert("The maximum length of the field is " + vLength + " characters. The data will be truncated.");
		s = s.substr(0, vLength);
		current.value = s;
	}

    var myApplet = window.top.PMWApplet;    // add by lianying 03/28/2005.
	myApplet.setRow(row);
	myApplet.setCol(col);
	myApplet.setCellValue(s);
	if (!myApplet.submit(COMMAND_UPDATE))
	{
		alert(ERROR_UPDATE_DATA_FAILED);
		current.focus();
		return false;
	}

	bEditing = false;
	return true;
}




//modifid by liuwei
function onEndEditingWithLengthNew(vLength ,vObj,ToolType)
{

	var current = vObj ;// event.srcElement;
	var row = strToInt(current.id.substr(4, 3)); //strToInt(current.name.substr(4, 3));
	var col = strToInt(current.id.substr(2, 2)); //strToInt(current.name.substr(2, 2));
	var s	= current.value;

	if(vLength == 0 && s.length > 2000)
	{
		alert("The maximum lenth of the field is 2000 characters. The data has been truncated.");
		s = s.substr(0, 2000);
		current.value = s;
	}

	if((vLength > 0) && (s.length > vLength))
	{
		alert("The maximum length of the field is " + vLength + " characters. The data will be truncated.");
		s = s.substr(0, vLength);
		current.value = s;
	}


    var myApplet = window.top.PMWApplet;    // add by lianying 03/28/2005.
	myApplet.setRow(row);
	myApplet.setCol(col);
	myApplet.setCellValue(s);
	myApplet.setToolType(ToolType);
	if (!myApplet.submit(COMMAND_UPDATE))
	{
		alert(ERROR_UPDATE_DATA_FAILED);
		current.focus();
		return false;
	}

	bEditing = false;
	return true;
}









// Handle when user exiting editing cell
function onExitEditing()
{
	bEditing = false;
}

// modified by zhanghuajie 060328 ,for supporting FireFox
// Handle when user end editing cell in project level
// Param: 	e 	the window event
function onProjectEndEditing(e)
{
	if (onEndEditing(e))
	{
		window.top.PMWApplet.setToolId(0);

		//var current = event.srcElement;
		var current = getDragDropObject(e) ;
		if(document.uniqueID) { // IE Browse.
		   current.disabled = true;
		}else {
		  	 //document.getElementById("IT05" + nSelectedRowStr).style.display="none";
		  	 //document.getElementById("HI05" + nSelectedRowStr).style.display="";
		  	 if(current.id == document.getElementById("IT06" + nSelectedRowStr).id){
				    var selectedValue = current.value;
				    current.nextSibling.nextSibling.value = aRespList[selectedValue];
		  	}
		  	 current.style.display="none";
		  	 current.nextSibling.nextSibling.style.display="";

		  	 //document.getElementById("IT05" + nSelectedRowStr).focus();
		  	 //onSelectRow1(e);
		  }
	}
}


// modified by zhanghuajie 060328 ,for supporting FireFox
// This function works the same with onProjectEndEditing(), but instead it takes in specified vLength
// as parameter to check the length of the text.
// Param: 	vLength 	maximum length allowed for input data
// Param: 	e 	the window event
function onProjectEndEditingWithLength(e,vLength)
{
	if (onEndEditingWithLength(vLength,getDragDropObject(e)))
	{
		window.top.PMWApplet.setToolId(0);

		//var current = event.srcElement;

		var current = getDragDropObject(e);
		if(document.uniqueID)  // IE Browse.
		  current.disabled = true;
	  } else {
		  	 //document.getElementById("IT05" + nSelectedRowStr).style.display="none";
		  	 //document.getElementById("HI05" + nSelectedRowStr).style.display="";

		  	 current.style.display="none";
		  	 current.nextSibling.nextSibling.style.display="";

		  	 //document.getElementById("IT05" + nSelectedRowStr).focus();
		  	 //onSelectRow1(e);
		  }
}

// modified by zhanghuajie 060328 ,for supporting FireFox
// Handle when user exits cell editing in the project level
// Param: 	e 	the window event
function onProjectExitEditing(e)
{
	 //alert("begin onProjectExitEditing");
	// force the window to fire onChange when the mouse click on outside of the window.
	window.focus();
	window.top.PMWApplet.setToolId(0);

	var current = getDragDropObject(e) ;//event.srcElement;

	// release control when onblur.
	if (hasControl())
		releaseControl();

 	if(document.uniqueID) { // IE Browse.
	   current.disabled = true;
	}  else {
		  	 current.style.display="none";
		  	 current.nextSibling.nextSibling.style.display="";
	}
	bEditing = false;
}


// Initialize the tool with group ID, project ID, tool ID, and tool type
// Param: 	vGroupId		group id
//		 	vProjectId		project id
//			vToolId			tool id
//			vToolType		tool type
function initTool(vGroupId, vProjectId, vToolId, vToolType)
{
    var myApplet = window.top.PMWApplet;  //add by lianying 03/28/2005.
  
 //	if (vToolId != myApplet.getToolId())
//	{
		// Add by haifeng 09/29/2004, bug id 5426
		myApplet.setCol(999);
//alert("vToolType="+vToolType);		
		myApplet.setToolType(vToolType);
		myApplet.setLevel(vGroupId, vProjectId, vToolId);
		requestControl(false);
		
		// Add by haifeng 09/29/2004, bug id 5426		
		setTimeout("requestControl(false)",3000);
		myApplet.setCol(0);
/*	}
	else
	{		
		if(vToolType!=myApplet.getToolType())
		  myApplet.setToolType(vToolType);
		bHasControl = myApplet.getHasControl();
		updateControls();
	}	*/
}

// Request control
// Param: 	vDisplayMessage		is there message to display?(true or false)
//								(if true, it notifies both user who request control and user who has control)
function requestControl(vDisplayMessage)
{
	var sController = "";

	var myApplet = window.top.PMWApplet;
	//Check user privilege
	if (window.top.nTMPrivileges == TM_PRIVILEGES_VIEWER)
	{
		if (vDisplayMessage)
			alert(WARN_NO_PRIVILEGES);

		sController = "";
		bHasControl = false;
	}
	else
	{		
	    // Modify by haifeng 2005/02/23, for solve request control problem
        var aMsg = new Array();
        if (vDisplayMessage)
			aMsg = submitWithResult(COMMAND_REQUEST_CONTROL);
		else
			aMsg = submitWithResult(COMMAND_REQUEST_CONTROL_NO_PROMPT);

		if (aMsg[0].nMsgId == COMMAND_HTTP_SUCCESS)   //PMConstant.COMMAND_HTTP_SUCCESS
		{
			bHasControl = (aMsg[0].nStatus > 0);
			if (!bHasControl)
			{
				sController = aMsg[1].sData;
				if (vDisplayMessage && (sController != ""))
					alert(MSG_REQUEST_CONTROL_FAILED + sController + ". \nA request has been sent to the controller.");
			}
			else
			{
				sController = myApplet.getUserId();
			}
		}

	}
	myApplet.setController(sController);
	myApplet.setHasControl(bHasControl);
	updateControls();
}

// A dummy method that gives other methods a chance to do some specified processing after get control right.
function afterRequestControl()
{
}

// Use this function in Pathway level; it returns true or false
// Param: 	vDisplayMessage		is there message to display?(true or false)
//								(if true, it notifies only user who request control, it doesnot notify user who has control)
function requestControlWithResult(vDisplayMessage)
{
	if (window.top.nTMPrivileges == TM_PRIVILEGES_VIEWER)
	{
		alert(WARN_NO_PRIVILEGES);
		return false;
	}
    // Modify by haifeng 2005/02/23
    var aMsg = new Array();
    aMsg = submitWithResult(COMMAND_REQUEST_CONTROL_NO_PROMPT);

    if (aMsg[0].nMsgId != COMMAND_HTTP_SUCCESS)   //PMConstant.COMMAND_HTTP_SUCCESS
        return false;

    var myApplet = window.top.PMWApplet;  // add by lianying 03/28/2005.
    bHasControl = (aMsg[0].nStatus > 0);
    if (!bHasControl)
    {
        sController = aMsg[1].sData;
        if (vDisplayMessage && (sController != ""))
            alert(MSG_REQUEST_CONTROL_FAILED + sController + ". \nA request has been sent to the controller.");

        return false;
    }
    else
    {
        sController = myApplet.getUserId();
    }

	myApplet.setController(sController);
	myApplet.setHasControl(bHasControl);
	updateControls();
	return true;
}

// Release control
function releaseControl()
{
    var myApplet = window.top.PMWApplet;  // add by lianying 03/28/2005.
	if (!myApplet.submit(COMMAND_RELEASE_CONTROL))
		return;

	bHasControl = false;
	myApplet.setController("");
	myApplet.setHasControl(bHasControl);
	updateControls();
}

// Handles update the controller field message
function updateControls()
{
	updateButtonStatus();
	updateInputCellStatus();
	updateController();
}

// Update button status
function updateButtonStatus()
{
	try
	{
		if (typeof(document.getElementById('toolbar_zone')) != "undefined")
			return;

		updateControlButton();
	}
	catch(ex)
	{
		if (bDebug)
		{
			throw ex;
		}
		else
		{
			;
		}
	}

}

// Update input cell status
function updateInputCellStatus()
{
}

// Handles key pressed event.
// Param: 	myfield 	current field
// 			e			event
function onKeyPressed(myfield,e)
{
	var keycode;

	if (window.event)
	{
		keycode = window.event.keyCode;
		editingField = window.event.srcElement;
	}
	else if (e)
	{
		keycode = e.which;
		editingField = e.srcElement;
	}
	else
		return true;

	if (keycode == 13)
	   	return processEnter(myfield);
	else
		return true;

}

// Process press 'Enter' key event
// Param: 	myfield	current field
function processEnter(myfield)
{
	myfield.blur();
	return false;
}

// Move to focus the next column
// Param: 	myfield	current field
//			offset		the row offset
function moveToNextCell(myfield, offset)
{
	var nRow = strToInt(myfield.id.substr(4, 3));
	var nCol = strToInt(myfield.id.substr(2, 2));

	if (getRowFromField(myfield).nextSibling != null)
	{
		getTextArea("workingArea", nRow+offset, nCol+1, 0).focus();
	}
	else
	{
		myfield.blur();
	}

	return false;
}


// Get to the <tr> level position from the input parameter
// if it is not there already
// Param: 	myfield		current field
function getRowFromField(myfield)
{
	var current = myfield;
	while(current.tagName != "TR"){
		current = current.parentNode;
	}
	return current;
}


function onBasicButtonClick(itemId, itemValue)
{
	//if the page has header and  hasn't been loaded fully, don't react to button clicks.
	if (!bLoaded && bPMWAppletHeaderFrame)
		return true;
	var bProcessed = true;

    if (itemId == "idHome")
    {
        window.location.href="User0.jsp";
    }
    else if (itemId == "idBackToPrevious")
	{
		window.history.go(-1);
	}
	else if (itemId == "idBackToGroup")
	{
		window.location.href="Group0.jsp?GroupId=" + this.top.PMWApplet.getUGId();
	}
	else if (itemId == "idBackToGroups")
	{
		window.location.href="User0.jsp";
	}
	else if (itemId == "idPrint")
	{
		doPrint();
	}
	else if (itemId == "idHelp")
	{
		onShowHelp();
	}
	else if (itemId == "idSuggest")
	{
		showUserReport();
	}
	else if (itemId == "idReturn")
	{
		window.location.href="Pathway.jsp";
	}
	else if (itemId == "idClose")
	{
		window.close();
	}
	else if (itemId == "idControl")
	{
		if (bHasControl)
		{
			releaseControl();
		}
		else
		{
			// Add by haifeng 09/29/2004, bug id 5426
		    this.top.PMWApplet.setCol(999);

			requestControl(true);
			afterRequestControl();

			// Add by haifeng 09/29/2004, bug id 5426
		    this.top.PMWApplet.setCol(0);
		}
	 }
	 else
		 bProcessed = false;

	return bProcessed;
}





// This function handles the toolbar button events. It processes the basic toolbar events.
// Param: 	item	item that has been clicked
function onToolButtonClick(itemId, itemValue)
{
	//document.toolbar.setToolbarEnabled(false);
	//onBasicButtonClick(item);
	//document.toolbar.setToolbarEnabled(true);
	onBasicButtonClick(itemId, itemValue)
	updateButtonStatus();
}

// Refresh Chat Online number
// Param: msg	message received from server
function refreshChatOnlineNum(msg)
{
}

// Reload the User0.jsp page
function reloadUser0()
{
	top.Working.window.location.href="User0.jsp";
}

// Show help
function onShowHelp()
{
	window.top.displayHelp(window.top.PMWApplet.getHelpIndex());
}

// Show Live Help page
function onShowLiveHelp()
{
	doModal("LiveHelp.jsp?idx=3", this, 650, 550);
}

// Show the FAQ page
function onShowFAQ()
{
	doModal("FAQ.jsp?id=1", this, 600, 600);
}

// Refresh user if user at the certain page
// Param: 	vPage		page that need to refresh when user steps in
/*
function refreshIfAtPage(vPage)
{	
	var sTempURL = "" + window.top.Working.location;

	var nHome = sTempURL.indexOf(vPage);

	if ((nHome > 0) && bLoaded)
	{
		reloadPage();
	}
}
*/

// Forced to log out
// Param: 	vType	 the type of logout
function onForcedLogOut(vType)
{
	// close child windows
	window.top.closeChildWindows();

	// wait for a while when the chat windows are closing.
	window.setTimeout("logout(" + vType + ")", 1000, "JAVASCRIPT" );
}

// Log out
// Param: 	vType	 the type of logout
function logout(vType)
{
	window.top.resetHeaderLogo();
	window.location.href = "Start.jsp?Signout=" + vType;
}

// Set variable, bLoaded
function onLoadBase()
{
	//vObjHeader.value = "true" ;	// add by xiahaobo 12/17/2004 ,bug id 2824, if use0.jsp unload then can't make the checkappletmessage run!
	bLoaded = true;

        // add by lianying 05/13/2005. bug id 997.
    //bDisableRightClickMenu = true;

	/*
	if(typeof(window.top) != 'undefined' && window.top.PMWApplet != null)
    {
		
    }*/
}


function updateNoteIcon(msg)
{
	var NoteIcon = document.getElementById("NoteIcon" + msg.nRow);

	if ((NoteIcon != null))
	{
		if (isEmpty(msg.sData))
			NoteIcon.src = "image/tool/CBNotesEmpty.gif";
		else
			NoteIcon.src = "image/tool/CBNotesFull.gif";
	}
}

// Update control button
function updateControlButton()
{
	if (document.toolbar != null)
	{
		if (window.top.nTMPrivileges == TM_PRIVILEGES_VIEWER)
			document.toolbar.setButtonEnabled(false, "idControl");
		else
		{
			document.toolbar.setButtonEnabled(true, "idControl");
//			document.toolbar.setButtonPushed(bHasControl, "idControl");
		}
	}
}

// Refresh if user is at the given page
function refreshIfAtPage(vPage)
{
	var sTempURL = "" + this.top.Working.location;

	var nHome = sTempURL.indexOf(vPage);
	if (nHome > 0)
	{
		reloadPage();
	}
}


// Makes a column wider - currently used by Data Analyst
function onWidenColumn()
{
    var myTableBody = getTableBody("workingArea");

	var nWidth = getCurrentColWidth("workingArea", COL_WIDEN);

	//Submit and update with the new width
	submitCellWidth(nWidth);

	adjustColumnWidth("workingArea", nWidth, COL_WIDEN);
}

// Makes a column narrower - currently used by Data Analyst Tool
function onNarrowColumn()
{
	var bEnd = false;		//Check to see if column reach minimum size
    var myTableBody = getTableBody("workingArea");
	var nWidth = getCurrentColWidth("workingArea",  COL_SHORTEN);

	if(nWidth >= COL_SHORTEN *(-1))
	{
		if(!adjustColumnWidth("workingArea", nWidth, COL_SHORTEN))
		{
			//Submit and update with the new width
			submitCellWidth(nWidth);
		}
	}
}

// Updates column width to new value. The new column width is got from server
// Param: 	msg		message recieved
function onUpdateColWidth(msg)
{
	if (this.top.PMWApplet.getToolId() == msg.nToolId)
	{
		nSelectedCol = msg.nCol;
	    var myTableBody = getTableBody("workingArea");
	    var vWidth = msg.sData;

		adjustColumnWidth("workingArea", vWidth, 0);
	}
}

// Update drop down list for Project according to group info
// Param: 	groupId			the selected groupid
// 			projectId		the selected projectid
//			bMyCalEdit		is the page calling from, My Calender Editing page? 1 - yes, 0 - no
function onUpdateProjList(groupId, projectId, bMyCalEdit){
	//Get form name
	var frmName = "";
	if(bMyCalEdit == "1")
		frmName = document.frmInput;	//My Calendar Editing page use different form name
	else
		frmName = document.thisForm;

	var listcount = 0;

	for(i = 0; i < aProjIDList.length; i++){
		if(aGroupIDList[i] == groupId){
            // add by lianying 02/21/05. bug id 3690.
		    if (aProjIDList[i] != "")
			    listcount++;
		}
	}
	frmName.projList.options.length = listcount + 1;
	frmName.projList.options[0].value = "0";
	frmName.projList.options[0].text = "All";
	frmName.projList.options[0].selected = true;

	var count = 1;
	for(i = 0; i < aProjIDList.length; i++){
		if(aGroupIDList[i] == groupId)
		{
			if(projectId != '' && aProjIDList[i] == projectId)
			{
				document.thisForm.projList.options[count].selected = true;
			}
			if (aProjIDList[i]!='') // add by lianying 03/15/2005.
			{
				frmName.projList.options[count].value = aProjIDList[i];
				frmName.projList.options[count].text = aProjNameList[i];
				count++;
			}
		}
	}

	if(bMyCalEdit == "1")
	{
		count = 0;
		frmName.sRemindUsers.options.length = 0;
		for(i = 0; i < aUGUserList.length; i++)
		{
			if(aUGIDList2[i] == groupId)
			{
				frmName.sRemindUsers.options.length++;
				frmName.sRemindUsers.options[count].value = aUGUserList[i];
				frmName.sRemindUsers.options[count].text = aUGUserList[i];
				count++;
			}
		}
	}
}

// This function is used in my Event and my News to set userid where there is no header to get userid
// Param: 	userid		the user's id
function setUserId(userid)
{
	sCurrentUserId = userid;
}

// Submits column width to server
function submitCellWidth(vWidth)
{
    var myApplet = window.top.PMWApplet;  // add by lianying 03/28/2005.
	myApplet.setCol(nSelectedCol);
	myApplet.setCellValue(vWidth);
	if (!myApplet.submit(COMMAND_UPDATE_COLWIDTH))
	{
		alert(ERROR_UPDATE_DATA_FAILED);
		current.focus();
		return false;
	}

	return true;
}

// Paste data from clipboard to grid
function pasteFromClipboard()
{
	if (nSelectedRow < 0 || nSelectedCol < 1)
	{
		alert("Please click to select the place where you want the data to be pasted.");
		return;
	}

	var text = clipboardData.getData('Text');

	if (text==null || isEmpty(text))
		return;

	var myTable = getTableBody("workingArea");
	var numCols = myTable.childNodes[1].childNodes.length;
	var numRows = myTable.childNodes.length;
	var rowEnd, cellEnd, i, j;
	var rowText = "";
	var value = "";
	var textToSend = "";
	var bRowEnd;
	var bColEnd = false;

	for (i = nSelectedRow + nRowOffset; i < numRows; i++)
	{
		rowEnd = text.indexOf("\r\n");

		if (rowEnd != -1)
		{
			rowText = text.substring(0, rowEnd);
			text = text.substring(rowEnd+2);
		}
		else
		{
			rowText = text;
			text = "";
			bColEnd = true;
		}

		bRowEnd = false;

		for (j = nSelectedCol+1; j <= numCols; j++)
		{
			cellEnd = rowText.indexOf("\t");

			if (cellEnd != -1)
			{
				value = rowText.substring(0, cellEnd);
				rowText = rowText.substring(cellEnd+1);
			}
			else
			{
				value = rowText;
				rowText="";
				bRowEnd = true;
			}

			//paste the value
			getTextArea("workingArea", i, j, 0).value = value;

			if (value == "")
				value = " ";
			textToSend = textToSend + value;

			if (bRowEnd)
				break;

			if (j != numCols)
				textToSend = textToSend + "\t";
		}

		if (bColEnd)
			break;

		if (i != numRows-1)
			textToSend = textToSend + "\n";
	}

	var myApplet = this.top.PMWApplet;
	//send the value to server
	myApplet.setRow(nSelectedRow);
	myApplet.setCol(nSelectedCol);
	myApplet.setCellValue(textToSend);

	if (!myApplet.submit(COMMAND_PASTE))
	{
		alert(ERROR_UPDATE_DATA_FAILED);
		return false;
	}
}

// Update AI comment icon
// Param: 	msg		message recieved
function updateAICommentIcon(msg)
{
	var CommentIcon = document.getElementById("CommentIcon" + msg.nRow);

	if ((CommentIcon != null))
	{
		CommentIcon.src = "image/tool/CBNotesFull.gif";
	}
}

// Focus field
function onFocusField(e)
{
	editingField = getDragDropObject(e) ; //event.srcElement;
}

// Only check for applet message if header frame is found within that page.
// So we can use PMUtils.js in popped up windows now.

if(typeof(window.top) != 'undefined' && window.top.PMWApplet != null)
{
	bPMWAppletHeaderFrame = true;

}

// Dummy emthod. This method is used in BS.
function setIdeaIDs(v_sLocation, vMsg)
{

}
function setIdeaId(vMsg){}

// Update note icon
// Param: 	msg		message recieved
function updateFmeaIcon(msg)
{
	var actionIcon = document.getElementById("actionIcon" + msg.nRow);

	if ((actionIcon != null))
	{
		if (isEmpty(msg.sData))
			actionIcon.src = "image/tool/CBNotesEmpty.gif";
		else
			actionIcon.src = "image/tool/CBNotesFull.gif";
	}
}

// Add by haifeng 2005/02/23, for submit data and return value directly
function submitWithResult(vCommandID)
{
    var sResponse = "";
   
    var myApplet = window.top.PMWApplet;// add by lianying 03/28/2005.
	sResponse =  "" + myApplet.submitWithResult(vCommandID);
	
	var aStrFormat = getParams(sResponse);
	var aMsg = new Array();

	for (var i=0; i<aStrFormat.length; i++)
	{
	    aMsg[i] = myApplet.getParamObj(aStrFormat[i]);
	}

    if (isEmpty(sResponse) || (typeof(aMsg[0]) == 'undefined'))
    {
        aMsg[0] = myApplet.getDisconnectParamObj();

        alert("Your connection to the server has been interrupted. Please log in again.");
        //If user lost connection, forced out and use default logo and disapper info section in header.
        onForcedLogOut(1);
    }

	return aMsg;
}

/**
 * Return an array of PMWParams from a string
 *
 * @param	strFormat	the string format (may contain more than one param messages)
 * @return				the params in a Vector
 */
function getParams(strFormat)
{
    var params = new Array();
    var tempStr = "";
    var dividerLength = HTTP_MESSAGE_DIVIDER.length;
    var startIndex;
    var endIndex;

    endIndex = strFormat.indexOf(HTTP_MESSAGE_DIVIDER);
    startIndex = 0;

    while (endIndex > startIndex)
    {
        tempStr = strFormat.substring(startIndex, endIndex);
         if (!isEmpty(tempStr) )
            params[params.length] = tempStr;

        startIndex = endIndex + dividerLength;
        endIndex = strFormat.indexOf(HTTP_MESSAGE_DIVIDER, endIndex+1);
    }

    if (startIndex < strFormat.length)
    {
        tempStr = strFormat.substring(startIndex);
        if (!isEmpty(tempStr) )
            params[params.length] = tempStr;
    }

    return params;
}
// add by lianying 05/19/2005. bug id 953.
function doOpenHelpWindow(sPage)
{
    var url = "PathMakerHelp.jsp?HelpIndex="+sPage;

    if (myHelpWindow == null || myHelpWindow.closed)
        myHelpWindow = showModalLocation(url, this, 600, 420, 150, 150);
    else
    {
        myHelpWindow.close();
        myHelpWindow = showModalLocation(url, this, 600, 420, 150, 150);
    }
    window.opener.top.closeHelp();
}


// Desc:It should pop up a waring message when a user double clicks on a page without control rights.
// add by linliming , 06/22/2005, bug id 4675.
function onDoubleClickCell()
{
	if (!bHasControl)
	{
		alert(MSG_NOT_HAVE_CONTROL);
		return;
	}
}

// Desc:It should pop up a waring message when a user double clicks on a page without control rights.
// add by linliming , 06/22/2005, bug id 4675.
function onDoubleClickCellOnPopWindow()
{
	if (!window.dialogArguments.hasControl())
	{
		alert(MSG_NOT_HAVE_CONTROL);
		return;
	}
}

// empyt for toolbar
function onPostInitialization()
{

}
// modified by zhanghuajie 060328 ,for supporting FireFox
function getDragDropObject(e)
{
  if(document.uniqueID) {
		obj = window.event.srcElement ;//e.srcElement ;
  } else {
  	obj = e.target ; //e.explicitOriginalTarget ;
  }
	return obj ;
}

// add by zhanghuajie 060328 ,for supporting FireFox
// to return the parent window object of current window.
function getParentWinObj() {

	var vTempObj;
		if(document.uniqueID)// IE Browse.
		{
		    if(typeof(dialogArguments) == "undefined")
	            vTempObj = window.opener;
		    else
		    	vTempObj = dialogArguments;
		}
	    else
			vTempObj = window.opener;

 return vTempObj;
}

function debugMsg(para) {

   alert();

}

function copyToClipboardPublic(txt) { 	
    if(window.clipboardData)  
    {      	
        window.clipboardData.clearData();  
        window.clipboardData.setData("Text", txt);  
    }  
  /*  else if(navigator.userAgent.indexOf("Opera") != -1)  
    {  
        window.location = txt;  
    }  */
    else if (window.netscape)  
    { 
        try {  
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
        }  
        catch (e)  
        {  
            alert("Your browser's current settings don't allow ipathmaker to copy this data to your clipboard. \nHere's how to change your settings:\n 1) In your browser's address bar enter this text: 'about:config'.\n 2)Press 'enter'. to bring up a list of your browser's advanced settings.\n 3)Scroll down to this setting: 'signed.applets.codebase_principal_support'. \n 4)Right click on this line, and use the Toggle command to change it's value to True. \n 5) Then press the Back button on your browser's toolbar. You may have to log into ipathmaker again.");  
        }  
        var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);  
        if (!clip)  
            return;  
        var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);  
        if (!trans)  
            return;  
        trans.addDataFlavor("text/unicode");  
        var str = new Object();  
        var len = new Object();  
        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);  
        var copytext = txt;  
        str.data = copytext;  
        trans.setTransferData("text/unicode",str,copytext.length*2);  
        var clipid = Components.interfaces.nsIClipboard;  
        if (!clip)  
            return false;  
        clip.setData(trans,null,clipid.kGlobalClipboard);  
    }  
    return true;  
}  

function getClipboard() {
   if (window.clipboardData) {
      return(window.clipboardData.getData("Text"));
   }
   else if (window.netscape) {
      netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
      var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
      if (!clip) return;
      var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
      if (!trans) return;
      trans.addDataFlavor("text/unicode");
      clip.getData(trans,clip.kGlobalClipboard);
      var str = new Object();
      var len = new Object();
      try {
         trans.getTransferData("text/unicode",str,len);
      }
      catch(error) {
         return null;
      }
      if (str) {
         if (Components.interfaces.nsISupportsWString) str=str.value.QueryInterface(Components.interfaces.nsISupportsWString);
         else if (Components.interfaces.nsISupportsString) str=str.value.QueryInterface(Components.interfaces.nsISupportsString);
         else str = null;
      }
      if (str) {
         return(str.data.substring(0,len.value / 2));
      }
   }
   return null;
}

String.prototype.replaceAll = function(search, replace){
 var regex = new RegExp(search, "g");
 return this.replace(regex, replace);
} 

function fixStringForWordDoc(input) 
{	
	var swapCodes   = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230); // dec codes from char at
var swapStrings = new Array("-", "-", "'",  "'",  '"',  '"',  "*",  "...");  

    // debug for new codes
    // for (i = 0; i < input.length; i++)  alert("'" + input.charAt(i) + "': " + input.charCodeAt(i));
    
    var output = input;
    for (i = 0; i < swapCodes.length; i++) {
        var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g"); // hex codes
        output = output.replace(swapper, swapStrings[i]);
    }
    return output;
}
	
function onFixWordDocStr(obj)
{	
	var sStr = obj.value;
	obj.value = fixStringForWordDoc(sStr);		
}		

function get_Cookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}

function set_Cookie(c_name,value,expiredays)
{var exdate=new Date();exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

// this deletes the cookie when called
function delete_Cookie( name, path, domain ) {
if ( get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


function cookieEnabled()
{
	var Ret = true;
	var sTempCookieName = "test1";
	set_Cookie(sTempCookieName,"testCookie",1);
	var sCookie = get_Cookie(sTempCookieName);	
	if(sCookie != "")
	{		
		delete_Cookie(sTempCookieName, "", "");		
	}
	else
	{		
		Ret = false;
	}
	
	return Ret;	
}

// Displays help window with help index for some popup windows
// Param:	helpIndex		The index of the help page.
function showHelp(helpIndex)
{
	doModalLocation("PathMakerHelp.jsp?HelpIndex=" + helpIndex, this, 600, 420, 150, 150);	
}

function showUserReport()
{
	var url = window.location.href;

	if (url.indexOf("?")!=-1)
	{
		url = url.substring(0, url.indexOf("?"));
	}
	
	var myApplet = window.top.PMWApplet;
	var sLink = "UserReport.jsp?sUserId=" + myApplet.getUserId() +
						"&sUGId=" + myApplet.getUGId() +
						"&sProjectId=" + myApplet.getProjectId() +
						"&sToolId=" + myApplet.getToolId() +
						"&sURL=" + url;
			
	showModalLocation(sLink, this, 600, 480, 150, 150);		
}

function refreshOpener(vPage)
{		
	var sTempURL = "" + window.opener.top.Working.location;

	var nHome = sTempURL.indexOf(vPage);
	if (nHome > 0)
	{
		window.opener.reloadPage();
	}	
}	

function refreshOpenerHome()
{
	refreshOpener("User0.jsp");
}	

function refreshOpenerAI()
{
	refreshOpener("ActionItem.jsp");
}

function refreshOpenerNews()
{
	refreshOpener("News0.jsp");
}

function refreshOpenerCalendar()
{
	refreshOpener("CalMonth.jsp");
	refreshOpener("CalYear.jsp");
}
	
function onToolUnload()
{
	if (bHasControl && !bKeepControl)
	{			
		releaseControl();	
	}	
}	

// grid sorting
function sortGrid(vGrid, vInd, vSortOrder)
{			
		vGrid.sortRows(vInd, vGrid.fldSort[vInd], vSortOrder);
		vGrid.setSortImgState(true,vInd,vSortOrder); 
}		

function setSort(vPageIndex,index,vsortorder)
{
	var myApplet = null; 
	
	if(bPopup)
	{
		var oTempObj = getParentWinObj();
		myApplet = oTempObj.top.PMWApplet;	
	}		
	else	
		myApplet = window.top.PMWApplet;
		
	var sSortStr = myApplet.getSortStr();
	
	var nIndex = sSortStr.indexOf(vPageIndex);
	if(nIndex > -1)
	{
		//var sTemp = sSortStr.substring(nIndex);
		var nEnd = sSortStr.indexOf(";", nIndex);
	//	sTemp = sTemp.substring(0, nEnd+1);	
	//alert("aaa:"+sTemp+"ccc");	
	//	replaceString(sSortStr, trimString(sTemp), "");
		
		sSortStr = sSortStr.substring(0, nIndex) + sSortStr.substring(nEnd+1);
		
		//sSortStr.replaceAll(sTemp, "");
	//alert("bbb:"+sSortStr);		
/*	var sTest = "aaa,bbb;";
	var sTest2 = sTest + "ccc";
	
	sTest2= replaceString(sTest2, sTest, "");
	alert(sTest2);	*/
	}	
	
	sSortStr += vPageIndex+index+","+vsortorder+";";
	
	myApplet.setSortStr(sSortStr);
	
	//oSortIndex.put(vPageIndex, index);
	//oSortType.put(vPageIndex, type);
}

function getSort(vPageIndex, vGrid)
{	
	if(vGrid.getRowsNum() < 1 || isEmpty(vPageIndex))
		return;
	
	var myApplet = null; 
	
	if(bPopup)
	{
		var oTempObj = getParentWinObj();
		myApplet = oTempObj.top.PMWApplet;	
	}		
	else	
		myApplet = window.top.PMWApplet;	
	
	var sSortStr = myApplet.getSortStr();
//alert(vPageIndex);	
	var nIndex = sSortStr.lastIndexOf(vPageIndex);
	var nPageIndexLen = vPageIndex.length;
	//alert(sSortStr);
	//alert(nIndex);
	if(nIndex > -1)
	{
		var sTemp = sSortStr.substring(nIndex+nPageIndexLen);
		var nEnd = sTemp.indexOf(";");
		sTemp = sTemp.substring(0, nEnd);
	//alert(sTemp);	
		var aSort = strToArray(sTemp, ",");
		
		var nInd = strToInt(aSort[0]);
		var sSortOrder = aSort[1];
	//alert(nInd+"; "+ sSortOrder);	
		sortGrid(vGrid, nInd, sSortOrder);
		
	}	
}	

function attachAfterSorting(vGrid, vPageIndex)
{
	vGrid.attachEvent("onAfterSorting", function(index,type,vSortOrder){
             // alert(index+"; " +type+"; " +direction);
             setSort(vPageIndex,index,vSortOrder);
        });	
}	

function folderClicked(current, vId, vTitle)
{	
	var foldercontent = document.getElementById(vId);
	
	if (foldercontent.style.display=="none")
	{
		current.src="image/ProjectOpen.gif";
		current.alt="Hide " + vTitle;
		foldercontent.style.display=""				
	}
	else
	{
		current.src="image/ProjectClose.gif";
		current.alt="Show " + vTitle;
		foldercontent.style.display="none"			
	}
}
