//////////////////////////////////////////////////////////////////////////////
//
// Common.js
//
// Copyright (c) 2003 by iManage, Inc.  All Rights Reserved
//
//////////////////////////////////////////////////////////////////////////////
//
// DESCRIPTION:
// 	Various client-side utility functions
//

var IMAN_DATA_DELIMITOR = "{}";
var IMAN_DATA_TERMINATOR = "[]";
var EMAIL_PARTS_DELIM = ".";
var k2K = 2000
var DefaultNamespace = "x-schema:../includes/iwpl.xml";
var kMaxTitleLength = 64;
var kMaxEmailLength = 254;
var g_MaxDescriptionLimit = 250;
var kDescLookupLength = 15;
var kTitleDisplayLength = 40;
var kWorkSiteDialog ="worksite_dialog"

function iManageEnums() {
	// Access rights
	this.imRightNone = 0
	this.imRightRead = 1
	this.imRightReadWrite = 2
	this.imRightAll = 3

	this.nrRightNone = this.imRightNone
	this.nrRightRead = this.imRightRead
	this.nrRightReadWrite = this.imRightReadWrite
	this.nrRightAll = this.imRightAll
	
	// Page Access rights	
	this.nrNoAccess = this.nrRightNone
	this.nrReviewerAccess = this.nrRightRead
	this.nrContributorAccess = this.nrRightReadWrite
	this.nrEditorAccess = this.nrRightAll
	
	// Default Security
	this.nrPrivate = 88
	this.nrPublic = 80
	this.nrView = 86
	this.nrInherit = 73
}

var iEnums = new iManageEnums()

function BrowseTreeNodeEnums() {
	var obj = new Object()
	
	obj.None			= 0x00000000
	obj.Explorer		= 0x00000001
	obj.Worklist		= 0x00000002
	obj.CheckedOut		= 0x00000004
	obj.Database		= 0x00000008
	obj.VF_Pages		= 0x00000010
	obj.VF_Folders		= 0x00000020
	obj.Subscription	= 0x00000040
	obj.Workspace		= 0x00000080
	obj.Folder			= 0x00000100
	obj.Search			= 0x00000200
	obj.Calendar		= 0x00000400
	obj.Discussion		= 0x00000800
	obj.Tasks			= 0x00001000
	obj.Document		= 0x00002000
	obj.ManageRoot		= 0x00004000
	obj.Manage1			= 0x00008000	// displays in webpart and admin
	obj.Manage2			= 0x00010000	// displays only in admin
	obj.Tab				= 0x00020000
	obj.Item			= 0x00040000
	obj.Favorites		= 0x00080000
	obj.RecentWorkspaces = 0x00100000
	obj.WorkspaceSearch	= 0x00200000 
	obj.WorkArea		= 0x00400000
	obj.Shortcut		= 0x00800000

	obj.All				= 0x7FFFFFFF

	obj.WorkspaceContents	= obj.Workspace | obj.Tab | obj.Item | obj.Folder | obj.Document | 
								obj.Calendar | obj.Discussion | obj.Tasks | 
								obj.Shortcut | obj.Favorites | obj.Worklist | obj.CheckedOut | 
								obj.Search | obj.WorkspaceSearch | obj.Subscription

	obj.WorkspaceParents	= obj.WorkArea | obj.Explorer | obj.Database | obj.VF_Pages| obj.Workspace | obj.WorkspaceSearch | 
								obj.RecentWorkspaces | obj.Folder | obj.Shortcut | obj.Subscription | obj.Favorites
								
	obj.FolderParents		= obj.WorkspaceParents | obj.Workspace | obj.Tab | obj.Folder | obj.Search | obj.VF_Folders
	
	obj.DocumentParents		= obj.FolderParents | obj.Worklist | obj.CheckedOut | obj.Search | obj.Favorites

	obj.FolderLink			= obj.WorkArea | obj.Worklist | obj.CheckedOut | obj.Database | 
								obj.VF_Pages | obj.VF_Folders | obj.Folder | obj.Search | obj.Shortcut
								
	obj.FolderLinkParents	= obj.FolderLink | obj.FolderParents
								 
	
	return obj
}

var btnEnums = BrowseTreeNodeEnums();

function ruleEngineEnums () {
	var obj = new Object()
	obj.keyOwner = "%owner%"
	
	obj.formatText = 0
	obj.formatHtml = 1
	
	obj.eventAdd = 15
	obj.eventRemove = 16
	obj.eventVersion = 11
	
	return obj
}

var reEnums = ruleEngineEnums()

function ConnectorFeatures() {
	var obj = new Object()
	
	obj.InstanceOptions = 1
	obj.UserOptions = 2
	obj.GlobalOptions = 4
	obj.Processable = 8
	obj.AllOptions = obj.InstanceOptions | obj.UserOptions | obj.GlobalOptions
	
	return obj
}

function SelectionModeEnum()
{
	var obj = new Object();
	
	/* This will ensure that the display doesn't have any content selection setting. Use this value to
	ignore the user's multi-op settings. */
	obj.None = 0
	
	/* This will display multi-op content selection.  Use this value to override user multi-op settings. */
	obj.MultiSelect = 1

	/* This will display contents whereby a user can only select a single item. */
    obj.SingleSelect = 2
    
    /* This will display multi-op content selection based on user settings.  If a user has multi-op
	disabled, then this will set the content selection mode to None.  If a user has multi-op enabled,
	then this will set the content selection mode to MultiSelect. */
	obj.UserMultiOpSelect = 3

	return obj
}

var selectionModeEnum = new SelectionModeEnum();

var SuiteEnums =
{	
	None : 0,
	WorkDocs:1,
	Connector:2,
	Colaboration:4,
	EWork:8,		
	Sharepoint:16,		

	WorkSiteWeb: 1 | 2 | 4,
	WorkSiteWebSharepoint: 1 | 2 | 4 | 16,
	WorkDocsSharepoint: 1 | 16,
	All : 255
}

//var suiteEnums = new SuiteEnums();

function ActionMenuLocationEnum()
{
	var obj = new Object();
	
	obj.RightmostColumn = 0
	obj.AfterIcon = 1
	obj.None = 2
	
	return obj
}

var actionMenuLocationEnum = new ActionMenuLocationEnum();

//Replace the delimitor for multiple look up result.
function ReplaceDelimitor(val) {	
	return val.replace(new RegExp(IMAN_DATA_DELIMITOR,"ig"), ",");
}

var DocumentTarget = 
{
	SameWindow: 0,
	Frame: 1,
	NewWindow: 2
}

var TransferControl = 
{
	FileControl: 0,
	ActiveX: 1,
	Applet: 2
}

// Rights
var bitCanAuthor=4
var bitCanCreateSysPages=2
var bitCanSearch=1



// Page types
var kTempPageType = "temp"
var kAdminPageType = "admin"
var kStartPageType = "start"
var kWorkPageType = "work"
var kPrefsPageType = "preferences"
var kTemplatePageType = "template"
var kConnectorPageType = "connector"
var kBrowsePageType = "browse"
var kWebPartPageType = "webpart"

var ResourcesAlias = "_resource";
var MonikerCheckedOutList = "_checkedoutlist";
var MonikerWorkList = "_worklist";
var MonikerRecentWorkspaces = "_recentpages";
var MonikerSubscriptionFolder = "_subscriptionfolder";
var MonikerFavoritesFolder = "_favoritesfolder";
var MonikerSession = "_session";
var MonikerWorkArea = "_workarea";
var MonikerDocumentSearchFolder = "_documentsearchfolder";
var MonikerStartWorkspace = "_start";
var MonikerManage = "_manage";

var MonikerStart = "!";
var MonikerVirtualStart = "_";

var kMultiOpSeparator = "^"

var kBrowseWndHt = 400
var kBrowseWndWd = 440

var kBrowseExWndHt = 450
var kBrowseExWndWd = 600

function openTag(tag, content) { return '<' + tag + ' ' + content + ' >' }
function closeTag(tag) { return '</' + tag + '>' }
var ampersand = "&"


document.onkeydown = document_onkeydown
function document_onkeydown()
{
	if ( event.keyCode == 116 )
	{
		setCookie("keyCode", event.keyCode, 1)
	}
	else
	{
		setCookie("keyCode", '', -1)
	}
}

function skipToContent() {
	window.location.replace("#content-area")
}

if ( window.page && window.page.debug == '4' ) {
	var startTime = new Date()
	window.onloadAdvise("alert(new Date() - startTime)")
}


function jumpToExpandedItem() {
	var item = getCookie("expandedItem","item")
	if(item != "" ) {
		window.location.replace("#"+item+"_anchor")
	}
	setCookie("expandedItem","item=")
}

window.onloadAdvise(jumpToExpandedItem)

function WebTransferCtrl_ClearTempDirectory()
{	
	if (page.transferControl == TransferControl.ActiveX) 
	{
		var obj = self.document.getElementById("WebTransferCtrl")
		
		if (obj && (obj.getAttribute("classid") == "CLSID:4BECECDE-E494-4f69-A3DE-DA0B77726307"))
		{
			obj.ClearTempDirectory()
		}
	}
}

//Add code to delete temp files using by the ActiveX Control
window.disposeAdvise(WebTransferCtrl_ClearTempDirectory)

function _versionControlObj(ServerSetting, ClientSetting, IsLatest, CanCheckout, CanCheckin, CanLock, CanUnlock,CanReplace, CanNewVersion,CanNewDoc, CurrentUser,IsCheckedOut)
{
	this.ServerSetting = ServerSetting
	this.ClientSetting = ClientSetting
	this.IsLatest = IsLatest
	this.CanCheckout = CanCheckout
	this.CanCheckin = CanCheckin
	this.CanLock = CanLock
	this.CanUnlock = CanUnlock
	this.CanReplace = CanReplace
	this.CanNewVersion = CanNewVersion
	this.CanNewDocument = CanNewDoc
	this.CurrentUser = CurrentUser
	this.IsCheckedOut = IsCheckedOut ;
}

function _document(nrtid, database, name, size, description, defaultName, number, version, extension, path, isCompound, isCheckedOut, isLocked, vcObj,editDate)
{
	this.nrtid = nrtid
	this.database = database
	this.name = name
	this.size = size
	this.description = description	
	this.defaultName = defaultName
	this.number = number
	this.version = version	
	this.extension = extension
	this.path = path
	this.IsCompound = isCompound
	this.IsCheckedOut = isCheckedOut
	this.IsLocked = isLocked
	this.VCObject = vcObj
	this.editDate = editDate	
}

function setFocusOnFirstItem(form) {
	if (!form) return
	var firstObj = null 
	if (form) {
		var elements = form.elements
		for (var i=0; i< elements.length; i++) {
			var item =elements[i]
			var type = item.type
			var isRightType = (type == "text" || type == "textarea" || type=="file" || type=="password")
			var canGetFocus = ( (!g_browser.isNS4) ? (!item.disabled) : true)
			if (type != "hidden" && canGetFocus) {
				if (!firstObj) {
					firstObj = item
				}
			}
			if (isRightType && canGetFocus) {
				// Don't set focus if the first item is not visible : JHL
				if(isParentVisible(item)) {
					item.focus()
				}
				return
			}
		}
		/*if (firstObj) {	//Causes an error if the first item isn't a RightType
			firstObj.focus()
		}*/
	}
}

function isParentVisible(item) 
{
	if ( item && item.style ) 
	{
		if ( item.style.display == 'none'
		    || item.style.visibility == 'hidden' )
		{
		    return false;
		} 
		else 
		{
			return isParentVisible(item.parentElement);
		}
	} 
	else 
	{
		return true;
	}
}

///////////////////////////////////////////////////////////////////////////////////
// standard API for netscape
///////////////////////////////////////////////////////////////////////////////////



var kComplete = 'complete'
var kInComplete = 'incomplete'
var locationHRef = window.location.href

if ( g_browser.isNav ) {
	document.readyState = kInComplete
} 

function attachment(url, title, imgSrc) {
	this.url = url
	this.title = title
	this.imgSrc = imgSrc
	this.AttStr = '|' + this.url + ';' + this.title + ';' + this.imgSrc + '|'
}
				
function getStyleObject(obj){
	var theObj
	if ( typeof obj == "string" ){
		theObj = window.document.getElementById(obj).style
	} else {
		theObj = obj
	}
	return theObj
}

function getAppletById(id) {
	return document.getElementById(id)
}

function addOptionItem(selObj, val, text, select) 
{
	var options = selObj.options
	var valUpper = val.toUpperCase();
	for (var i = 0; i < options.length; i++) 
	{
		if ( options[i].value.toUpperCase() == valUpper) 
		{
			if ( select )
			{
				selObj.selectedIndex = i
			}
			return
		}
	}
	options[options.length] = new Option(text, val)
	if ( select )
	{
		selObj.selectedIndex = options.length - 1
	}
}

function clearSelectObjOpitons (selObj, nth) 
{
	if ( !nth ) 
	{
		nth = 0
	}
	while (selObj.options.length > nth) 
	{
		selObj.options[selObj.options.length -1] = null
	}
}

///////////////////////////////////////////////////////////////////////////////////
// standard API for netscape END
///////////////////////////////////////////////////////////////////////////////////

var undefined = 0

if ( ! window.XMLHttpRequest ) 
{
    window.XMLHttpRequest = function()
                            {
                                return new ActiveXObject("MSXML2.XMLHTTP");
                            }
}
 
function clientToAsp(id) 
{
	if ( id )
	{
		var domObj = document.getElementById(id)
		if ( domObj ) 
		{
			return domObj;
		}
		document.writeln("<div id='" + id + "'></div>")
		domObj = document.getElementById(id)
	}
	if ( ! domObj ) 
	{
		domObj = {};
	}
	
		
	//Note: We had added following variable to make sure every request is unique,because XMLHTTP caches similar requests : SJ
	domObj.globalIndex = (new Date()).valueOf()
	domObj.hasError = false;
	domObj.errorMessage = "";
	
	domObj.getData = clientToAsp_getData
	domObj.clearError = clientToAsp_clearError
	domObj.isAccessGranted = clientToAsp_isAccessGranted
	domObj.putData = clientToAsp_putData 
	domObj.checkResult = clientToAsp_checkResult	
	domObj.getDataByPost = clientToAsp_getDataByPost
	domObj.parseResult = clientToAsp_parseResult
	
	return domObj;
}
 function clientToAsp_getData(url, callback) 
 {
 	this.clearError();
 	
 	url = htmlDeString(url);
	url = setURLParam(url, "xmlFormat", "1")
	url = setURLParam(url, "globleindex", this.globalIndex++)

	var requestObj = new XMLHttpRequest();
	
	//if url is pointing to an xml directly, we may need create an ASP
	//file to handle it.

	if(url.length > k2K) 
	{
		this.hasError = true;
		this.errorMessage = getLocStrByLID(1155, "Please reduce the number of selected items");
		return
	}

	var async = false;
	if ( typeof(callback) == 'function' )
	{
		var it = this;
		requestObj.onreadystatechange = function() 
										{ 
											if ( requestObj.readyState == 4 /*COMPLETED*/ )
											{
												callback(it, it.parseResult(requestObj));
												requestObj = it = callback = url = null;
											}
										};
		async = true;
	}
	requestObj.open("GET", url, async);
	requestObj.send(null);

	return async ? null : this.parseResult(requestObj);
}

function clientToAsp_clearError() 
{ 
	this.hasError = false; 
	this.errorMessage = "";
}

function clientToAsp_isAccessGranted() 
{ 
	return true;
}
	
function clientToAsp_putData(url) 
{
 	this.clearError();
	url = setURLParam(url, "xmlFormat", "1")
	url = setURLParam(url, "globleindex", this.globalIndex++)

	var requestObj = new XMLHttpRequest();

	if(url.length > k2K) 
	{
		this.hasError = true;
		this.errorMessage = getLocStrByLID(1155, "Please reduce the number of selected items");
		return
	}

	requestObj.open("GET", url, true)
	requestObj.send(null)
}
	
function clientToAsp_checkResult(result) 
{
	if ( result )
	{
		var indexError = result.indexOf(IMAN_DATA_DELIMITOR)
		if (indexError > 0) 
		{
			this.hasError = result.substring(0,indexError).toUpperCase() == "ERROR:";
		}
		if (this.hasError) 
		{
			this.errorMessage = result.substring(indexError + IMAN_DATA_DELIMITOR.length);
		}
	}
}
	
function clientToAsp_getDataByPost(url, body, callback) 
{
 	this.clearError();
	body += (body ? "&" : '') + "xmlFormat=1"

	var requestObj = new XMLHttpRequest();

	if(url.length > k2K) 
	{
		this.hasError = true;
		this.errorMessage = getLocStrByLID(1155, "Please reduce the number of selected items");
		return
	}

	var async = false;
	if ( typeof(callback) == 'function' )
	{
		var it = this;
		requestObj.onreadystatechange = function() 
										{ 
											if ( requestObj.readyState == 4 /*COMPLETED*/ )
											{
												callback(it, it.parseResult(requestObj));
												requestObj = it = callback = url = body = null;
											}
										};
		async = true;
	}

	requestObj.open("POST", url, async)
	requestObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
	requestObj.send(body)

	return async ? null : this.parseResult(requestObj);
}

function clientToAsp_parseResult(requestObj)
{
	var result = '';
	if ( requestObj.responseXML && requestObj.responseXML.documentElement )
	{
		var rootNode = requestObj.responseXML.documentElement;
		if ( rootNode.nodeName == 'data' )
		{
			result = rootNode.text;
			this.checkResult(result);
		}
		else
		{
			result = rootNode.ownerDocument;
		}
	}
	else
	{
		result = requestObj.responseText;
		this.checkResult(result);
	}
	return result;
}

function writeClientToAsp() 
{
	id = 'clientToAspApplet';
	var applet = getAppletById(id);
	if ( !applet )
	{	
		applet = new clientToAsp(id);
	}
}

function fixImageUrl(url)
{
	var root = virtualPath();

	if ( url && url.charAt(0) != '\\' && url.charAt(0) != '/' ) 
	{
		url = root + '/images/' + url 
	}
	else if ( ! url )
	{
		url = root + '/images/blankicon.gif'
	}
	return url;
}

function fixActionUrl(url)
{
	if ( typeof(url) == 'string' )
	{
		if ( urlIsRelative(url) )
		{
			var root = virtualPath();
			url = root + '/scripts/' + url 
		}
	}
	return url;
}

function isMonikerEqualIgnoreServerName(id1,id2) {
	return getMonikerInfo(id1,"database") == getMonikerInfo(id2,"database") && getMonikerInfo(id1,"page") == getMonikerInfo(id2,"page")
}

function getMonikerInfo(id,name) {
	//return the moniker part without any session information.
	var result = ""
	if (id)	{
		var oid = id.toUpperCase()
		if (!name) {
			result = id
		}else {
			var oname= name.toUpperCase()
			var posStart = oid.indexOf("!" +oname + ":")
			if (posStart > -1) {
				var nid = oid.substr(posStart + oname.length + 2)
				var posEnd = nid.indexOf(":")
				if (posEnd > 0) {
					result = nid.substring(0,posEnd)
				}
			}			
		}
	}
	return result
}

function sortByTitle(a1, a2)
{
	return sortBy(a1, a2, 'title')
}

function sortBy(a1, a2, property1, property2)
{
	if ( a1[property1] < a2[property1] )
	{
		return -1;
	}
	else if ( a1[property1] > a2[property1] )
	{
		return 1;
	}
	else if ( property2 )
	{
		if ( a1[property2] < a2[property2] )
		{
			return -1;
		}
		else if ( a1[property2] > a2[property2] )
		{
			return 1;
		}
	}
	return 0;
}

function sortColumn(id, column, element, view, description, pageid) 
{
	/*
		Now that we no longer store cached pages, we must resubmit hidden forms after processing
		the sort.  Therefore, we are using clientToAsp to perform the sort, and then the form
		with hidden variables gets resubmitted so that the sort can re-execute.
	*/	
	if (!description) 
	{
		description = ""
	}
	setCookie(window.name + "Offset", document.body.scrollLeft + "," + document.body.scrollTop, 0)
	
	if ( ! pageid )
	{
		if (document.forms["fm"])
		{
			var parent = document.forms["fm"].elements["page"]
			if (parent)
			{
				//use the form variable if present
				pageid = parent.value 
			}
			else
			{
				pageid = ResourcesAlias
			}
			parent = null
		}
		else
		{
			pageid = page.id
		}
	}
	
	if ( ! view )
	{
		view = page.view;
	}
	
	var url = virtualPath() + "/scripts/Sort.aspx?page=" + escape(pageid) + "&id=" + escape(id) + "&column=" + escape(column) + "&element=" + escape(element) + "&view=" + escape(view) + "&description=" + escape(description); 

	var applet = getAppletById('clientToAspApplet')
	applet.putData(url);
	sortColumnResult(id, element);
}

function sortColumnResult(id, element)
{
	if (document.forms["fm"])
	{
		if ( element == "tasks" || element == "events" )
		{
			var cmd = document.getElementById ('command');
			if (cmd != null ) 
			{
				document.fm.command.hidden = false 
				document.fm.command.value = "save"
			
				var  viewElement = document.getElementById ('view')
				if ( viewElement != null )
				{
					if ( element == "tasks")
						viewElement.value = "tasksearch"
					if ( element == "events")
						viewElement.value = "eventsearch"
				} 
			}
		}
			
		document.forms["fm"].submit()
	}
	else
	{		
		var redirect = window.page.getRedirect()
		if ( getURLParam(window.location.href, "showpopup") )
		{
			redirect = setURLParam(redirect, "showpopup", "1");
			
		}
		window.location = redirect
	}
}

function browseLookUpCallBack(window, cmd, nrtid, id, target, title, img, href, context)
{
	var paramArray = context.split(",")
	var formName = paramArray[0]
	var fieldName = paramArray[1]
	var uniqueSuffix = paramArray[2] || '';
	var form = document.forms[formName]
	if (form) {
		var controlObj = document.forms[formName].elements["p-" + fieldName + uniqueSuffix]
		if(controlObj) {
			controlObj.value =  nrtid
			controlObj.focus()
		}
	}		
	window.close()
}

function doBrowseDlgLookup(attributeID, parentName, title, formName, fieldName, dependents, isSearch, callBackFn, uniqueSuffix) {
	uniqueSuffix = uniqueSuffix || '';
	callBackFn = callBackFn ? callBackFn: "browseLookUpCallBack"
	var btnEnums = BrowseTreeNodeEnums()
	var context = formName + "," + fieldName + "," + uniqueSuffix
	var select = btnEnums.Folder | btnEnums.Workspace | btnEnums.Tab
	var pageId = page.type != "temp" ?  page.id != "" ? page.id : (dialog ?  dialog.data["page"] : "") : ""
	var url = virtualPath() + '/scripts/BrowseDlg.aspx?title=' + escape(getLocStrByLID(617, 'Select Folder')) + '&resolve=1&callback='+ escape(callBackFn) +'&context=' + escape(context) + '&filter=' + btnEnums.FolderParents  + '&select=' + select + "&page=" + escape(pageId)
	var height = page.type != "temp" ? kBrowseWndHt + 50 : kBrowseWndHt
	//fix for 36367:  renamed window so that it doesn't conflict with the browseDlgEx window (NS, 8/22/05, 8.1.51)  
	var wnd = openWindow(url, 'browseWnd2', kBrowseWndWd, height, '')
}


function doLookup(attributeID, parentName, title, formName, fieldName, dependents, isSearch, callBackFn, uniqueSuffix) 
{	
	uniqueSuffix = uniqueSuffix || '';
	if(fieldName == "search-for") 
	{
		return
	}
	else if(fieldName == "container-id") 
	{
		doBrowseDlgLookup(attributeID, parentName, title, formName, fieldName, dependents, isSearch, callBackFn, uniqueSuffix)	
		return
	}
		
	var form = document.forms[formName]
	var parentValue = ""
	title = htmlDeString(parseAndLocalizeStr(title))
	
	
	if (form) {		    
		var parentValue = ""
		var parent = document.forms[formName].elements["p-" + parentName + uniqueSuffix]
		if (parent) 
		{			
			parentValue = parent.value
		}
		
		// Get database name, if any
		var databaseName  = getDatabaseValueforLookup(formName, uniqueSuffix)
		
		databaseName = databaseName.indexOf(",") >=0 ? "" : databaseName
		var params = formName + "," + fieldName + "," + dependents + "," + uniqueSuffix
		isSearch = isSearch ? isSearch : ""
		callBackFn = callBackFn ? callBackFn: "lookupCallback"

		title = title.replace(/%20/g," ")

		var domObject = document.getElementById("lookupApplet")
		var scriptName = domObject.getAttribute("scriptName");
		var url = virtualPath() + "/scripts/lookupDialog.aspx?"
		var querryString = "id=lookup_" + attributeID +
						"&title=" + escape(title) +
						"&scriptName=" + escape(scriptName) +
						"&type=" + escape(attributeID) +
						"&parentString=" + escape(String(parentValue)) +
						"&functionName=" + escape(callBackFn) +
						"&textFieldId=" + escape(params) +
						"&database=" + escape(databaseName) +
						"&isSearch=" + escape(isSearch)
		url += querryString
		var winObj= openWindow(url,"", 430, 300, "scrollbars=no")
	}
}

function doGroupRoleMgmtLookup(itemId, dbName, lookupType)
{
	title = escape(parseAndLocalizeStr("{511|Add User}"))

	title = title.replace(/%20/g," ")
	if (g_browser.isNS4) {
		var lookupApp =getAppletById("lookupApplet")		
		lookupApp.setLookupType(attributeID, this,callBackFn , String(parentValue), title, params, databaseName, isSearch)
	}else {
		var domObject = document.getElementById("lookupApplet")
		var scriptName = domObject.getAttribute("scriptName");
		var url = virtualPath() + "/scripts/lookupDialog.aspx?"
		var querryString = "id=lookup_group" +
						"&title=" + escape(title) +
						"&scriptName=" + scriptName + "?isGrpRoleMgmt=1" +
						"&type=" + escape(lookupType) +
						"&parentString=" +
						"&functionName=grpRoleMgmtCallback" +
						"&textFieldId=" + escape(itemId) + "," + escape(dbName) + "," + escape(lookupType) +
						"&database=" + escape(dbName) +
						"&isSearch=1"
		url +=querryString
		
		var winObj= openWindow(url,"", 430, 300, "scrollbars=no")
	}
}

function grpRoleMgmtCallback(id, name, itemId)
{
	var redirect = escape(page.getRedirect());
	window.location.href = virtualPath() + "/scripts/XManagement.aspx?command=add&userid=" + escape(id) + "&xid=" + escape(itemId.split(",")[0]) + "&database=" + escape(itemId.split(",")[1]) + "&container=" + escape(itemId.split(",")[2]) + "&redirect=" + redirect
}

function removeUserFromGrpRole(id, containerId, database, container, multiselectID)
{
	if (multiselectID)
	{
		id = new NRTItems(multiselectID).getItems()
	}
	var redirect = escape(page.getRedirect());
	window.location.href = virtualPath() + "/scripts/XManagement.aspx?command=remove&userid=" + escape(id) + "&xid=" + escape(containerId) + "&database=" + escape(database) + "&container=" + escape(container) + "&redirect=" + redirect
}

function writeLookupApplet(id, scriptName) 
{
	document.write('<div id="' + htmlString(id ? id : 'lookupApplet') + '" scriptName="' + htmlString(scriptName) + '"></div>');
}
		
function lookupCallback(alias, description, params) {	
	alias = ReplaceDelimitor(alias);
	description = ReplaceDelimitor(description)
	var paramArray = params.split(",")
	var formName = paramArray[0]
	var fieldName = paramArray[1]
	var dependents = paramArray[2]
	var uniqueSuffix = paramArray[3] || ''
	var form = document.forms[formName]
	if (form) {
		var controlObj = document.forms[formName].elements["p-" + fieldName + uniqueSuffix]
		var exitingValue = controlObj.value
		//TODO: to allow multiple selection for search, we may want to have a window scoped
		//variable indicate if the lookup is for a search criteria and append the alias to
		//any existing value
		//controlObj.value = (exitingValue ? (exitingValue + "," + alias) : alias)
		controlObj.value = alias
		controlObj.focus()
		//[#38349] Setting controlObj.value programmatically 
		//doesn't fire the onchange event for that item.  Therefore,
		//we need to fire the onchange event so that event handlers
		//can be invoked in the profile. (NS, 4/7/06, 8.2.1)
		controlObj.fireEvent("onchange")
		
		var span = document.getElementById("s-" + fieldName + uniqueSuffix)
		if (span) {
			span.innerText = description.length > kDescLookupLength ? description.substring(0, kDescLookupLength) + "..." : description
		}
		
		clearDependents(formName, dependents, uniqueSuffix)
		if ( window.location.href.toLowerCase().indexOf("docprofile.aspx") >= 0 && (fieldName == "class" || fieldName == "subclass")) {
			updateRequiredFields(formName, uniqueSuffix)
		}
	}
}  
 
function updateRequiredFields(formName, uniqueSuffix) 
{
	uniqueSuffix = uniqueSuffix || '';
	var form = document.forms[formName]
	if (form) {
		// we dont need to validates fields for folder profileing : SJ
		if(form.isFolderProfile && form.isFolderProfile.value=="1") {
			return
		}
		var className = form.elements["p-class" + uniqueSuffix] ? form.elements["p-class" + uniqueSuffix].value : ""
		var subclassName = form.elements["p-subclass" + uniqueSuffix] ? form.elements["p-subclass" + uniqueSuffix].value : ""
		var databaseName = form.elements["p-database" + uniqueSuffix] ? form.elements["p-database" + uniqueSuffix].value : ""
		var pDatabaseName = form.elements["pdatabase" + uniqueSuffix] ? form.elements["pdatabase" + uniqueSuffix].value : ""
		var url = virtualPath() + "/scripts/GetRequired.aspx?class=" + escape(className) + "&subclass=" + escape(subclassName) + "&database=" + escape(databaseName ? databaseName : pDatabaseName)
		var applet = getAppletById('clientToAspApplet')
		var data = applet.getData(url)
		data = data ? String(data) : ""
		if (applet.hasError) {
			locAlert(applet.errorMessage)
			return
		}
		for (ii=0; ii < form.elements.length; ii++) {
			var element = form.elements[ii]
			if ( element.worksiteid ) {
				name = element['item-name']
				var img = document.images[name + uniqueSuffix + "-img"]
				var pos = data.search("," + name + ",")
				if (pos >= 0) {
					if (img) {
						img.src = virtualPath() + "/images/RequiredInd.gif"
						img.title = img.alt = getLocStrByLID(81,"Required Field")
					}
					if ( element.setAttribute ) {
						element.setAttribute("required", "1")
					}
				} else {
					if (img) {
						img.src = virtualPath() + "/images/BlankIcon.gif"
						img.title = img.alt = ""
					}
					if ( element.setAttribute ) {
					
						element.setAttribute("required", "0")
					}
				}
			}
		}
	}
}

function getFieldValue(form, fieldName) {
	var value = ""
	var field = form.elements[fieldName]
	if (field) {
		if (field.type == "select-one") {
			if (field.selectedIndex >= 0) {
				value = field.options[field.selectedIndex].value
			}
		} else {
			value = field.value
		}
	}
	
	return value
}
			
function clearDependents(formName, dependents, uniqueSuffix) 
{
	uniqueSuffix = uniqueSuffix + '';
	var form = document.forms[formName]
	if (form && dependents) {
		var dependent = form.elements["p-" + dependents + uniqueSuffix]
		if (dependent) {
			if (dependent.type == "select-one") {
				dependent.options.length = 0
				dependent.setAttribute("populated", "0")
			} else {
				dependent.value = ""
			}
			span = document.getElementById("s-" + dependents + uniqueSuffix)
			if (span) {
				span.innerText = ""
			}
		}
	}
}

function installUpdateRequiredFields(formName, uniqueSuffix)
{
	uniqueSuffix = typeof(uniqueSuffix) == "undefined" ? '': uniqueSuffix + '';
	var iClass = document.forms[formName].elements['p-class' + uniqueSuffix]
	if ( iClass && iClass.type == 'text' ) 
	{
		iClass.onchange = joinFunctions(bindFunction(clearDependents, formName, 'subclass', uniqueSuffix), bindFunction(updateRequiredFields, formName, uniqueSuffix));
	}
	var iSubClass = document.forms[formName].elements['p-subclass' + uniqueSuffix]
	if ( iSubClass && iSubClass.type == 'text' ) 
	{
		iSubClass.onchange = bindFunction(updateRequiredFields, formName, uniqueSuffix);
	}
}



function validateProfileFields(formName) {
	var valid = true
	var form = document.forms[formName]
	if (form) {
		for (i=0; i < form.elements.length && valid; i++) {
			var element = form.elements[i]			
			if ( element.getAttribute && element.getAttribute("required") == "1" ) {
				var value = getFieldValue(form, element.name)
				if (value.length == 0) {
					locAlert(getLocalizedString("882|Values must be entered for all required profile fields."))
					//set focus on element so user has visual cue as to failed item
					element.focus()
					valid = false
				}
			}
		}
	}
	
	return valid
}


function openWindow(sURL, sName, nWidth, nHeight, sFeatures) {
// wraps around 'window.open' and centralizes the new window based on its opener window
// usage:  var wnd = openWindow("Page.htm", "page name", 400, 400, "resizable=1")
	if(sURL.length > k2K) {
		alert(parseAndLocalizeStr("{1155|Please reduce the number of selected items}"))
		return
	}
	sFeatures = getWindowCenterOptions(nWidth, nHeight)  + (sFeatures ? ("," + sFeatures) : "") 
	sFeatures += ",resizable=yes"
	if (g_browser.isNS6) {
		sFeatures = "modal" + (sFeatures ? ("," + sFeatures): "") 
	}
	
	if (g_browser.isIE) 
	{
		return window.open(sURL, sName, sFeatures)
	}
	else 
	{
		return window.open(sURL, sName, sFeatures)
	}
}

function getWindowCenterOptions(nWidth, nHeight)
 {
	var sFeatures
	var nLeft, nTop
	
	if ( g_browser.isNav ) {
		nLeft = centralize(screen.availWidth, window.screenX, window.outerWidth, nWidth  )
		nTop = centralize(screen.availHeight, window.screenY, window.outerHeight, nHeight)
		sFeatures = "screenY=" + nTop + ",screenX=" + nLeft + ",outerWidth=" + nWidth + ",outerHeight=" + nHeight
	} else { 
		nLeft = centralize(screen.availWidth, window.screenLeft, window.document.body.offsetWidth, nWidth + 10) // 10 is a magic number
		nTop = centralize(screen.availHeight, window.screenTop, window.document.body.offsetHeight, nHeight + 29)	// 29 is another magic number
		sFeatures = "top=" + nTop + ",left=" + nLeft + ",width=" + nWidth + ",height=" + nHeight
	}
	
	return sFeatures
}

function download(nrtids, id) 
{	
	var nrtidArr = nrtids.split(kMultiOpSeparator)
	if( page.transferControl == TransferControl.ActiveX )
	{
		for (var i = 0; i < nrtids.length; i++)
		{
			var nrtid = nrtidArr[i]
			if (!nrtid) continue			
			downloadExView(nrtid);
		}
	}
	else
	{
		clearFileItems("WebTransferCtrl")
		for (var i = 0; i < nrtids.length; i++)
		{
			var nrtid = nrtidArr[i]
			if (!nrtid) continue
			var url = "../scripts/ViewDoc.aspx?nrtid=" + escape(nrtid) + "&command=ok"
			document.WebTransferCtrl.addTransferItem('','',url)
		}		
		startView("WebTransferCtrl");
	}
}

function downloadEx(nrtid, documentOption, overrideDocumentTarget) 
{
	if(window.event)
	{
		window.event.cancelBubble = true
	}
	
	var clientToAsp = getAppletById("clientToAspApplet");
	
	if ( clientToAsp ) 
	{
		var response = clientToAsp.getData(virtualPath() + "/scripts/getDocProps.aspx?nrtid=" + escape(nrtid)) + "";
		if (clientToAsp.hasError)
		{
			locAlert(clientToAsp.errorMessage);
		}
		else if(!response)
		{
			locAlert(getLocStrByLID(37, "Your session has expired. You must log in again."))
		}
		else
		{					
			eval(response + ";");
			
			if ( docProps.archived )
			{
			    locAlert(getLocStrByLID(1520, "The document is archived."))
				return;
			}
			nrtid = docProps.nrtid; 
			switch ( documentOption ) 
			{				
				case "viewHTML":
					openAsHTML(nrtid)
					break;
				
				case "checkOut":	
					downloadExCheckOut(nrtid);
					break;
					
				case "profile":
					downloadExProfile(nrtid);		
					break;
				
				case "portable":
					downloadExPortable(nrtid);					
					break;
					
				case "view":
				default:
					if ( typeof(overrideDocumentTarget) == 'undefined' )
					{
						overrideDocumentTarget = docProps.documentTarget
					}
					switch ( overrideDocumentTarget )
					{
						case DocumentTarget.Frame:
							if ( docProps.url )
							{
								openPortalLink(virtualPath()+ "/scripts/redirector.aspx?url=" + escape(docProps.url));
							}
							else
							{
								openPortalLink(virtualPath()+ "/scripts/redirector.aspx?nrtid=" + escape(nrtid));
							}
							break;
							
						case DocumentTarget.NewWindow:
							if ( docProps.url )
							{
								window.open(docProps.url);
							}
							else
							{
								downloadExView(nrtid);
							}
							break;
					}
					break;
			}
		}
	}
}

function downloadExView(nrtid, script, action, path, open, duedate, comments, portable,editDate) 
{  
	
	if ( page.transferControl == TransferControl.ActiveX )	
	{
		url = virtualPath()+ "/scripts/ProgressBar.aspx";
		url = setURLParam(url, "nrtid", escape(nrtid))
		url = setURLParam(url, "duedate", escape(duedate ? duedate : ""))
		url = setURLParam(url, "comments", escape(comments ? comments : ""))		
		url = setURLParam(url, "script", escape(script ? script : "ViewDoc.aspx"))
		url = setURLParam(url, "action", action ? action : 3)
		url = setURLParam(url, "open", open ? open : 1)
		url = setURLParam(url, "path", escape(path ? path : ""))
		url = setURLParam(url, "portable", portable ? portable : "0")		
		if ( editDate != "")
		{
			url = setURLParam(url, "editDate", editDate)				
		}
		var wnd = openWindow(url, "", 400, 100, "")	
	}
	else if(page.transferControl == TransferControl.Applet)
	{ 
		viewFile("WebTransferCtrl", virtualPath()+ "/scripts/ViewDoc.aspx?nrtid=" + escape(nrtid) + "&command=ok")
	}
	else
	{		
		url = virtualPath()+ "/scripts/FileControlDownload.aspx";
		url = setURLParam(url, "nrtid", escape(nrtid))
		url = setURLParam(url, "duedate", escape(duedate))
		url = setURLParam(url, "comments", escape(comments))
		url = setURLParam(url, "checkOut", (script == "CheckOut.aspx") ? "true":"false")		
		//var wnd = openWindow(url, "", 100, 100, "");		
		var wnd = openWindow(url);				
		closeDialogWindow();				
	}
}
	
function downloadExCheckOut(nrtid) 
{  	
	var clientToAsp = getAppletById("ClientToAspApplet");
	var data = clientToAsp.getData(virtualPath()+ "/scripts/viewDoc.aspx?command=informationonly&nrtid=" + escape(nrtid)) + "";
	var docInfo;
	if (clientToAsp.hasError) {
		locAlert(clientToAsp.errorMessage)
	} else if ( data.length > 0 ) {
		docInfo = eval(data);
	}
	if ( ! docInfo )
	{
		return;
	}
	if (docInfo.VCObject.IsCheckedOut )
	{
		locAlert(getLocalizedString("1162|The file is already checked out."));
		return ;
	}
	if ( docInfo.VCObject.CanCheckout != 1 ) {
		locAlert(getLocalizedString("1374|Action Checkout cannot be performed. \nSelect View to open document"));
		return ;
	}
	openDialogWindow(virtualPath()+ "/scripts/Checkout.aspx?nrtid=" + escape(nrtid) + "&redirect=" + escape(page.getRedirect()))
}

function downloadExProfile(nrtid) 
{
  	openDialogWindow(virtualPath()+ "/scripts/getDoc.aspx?nrtid=" + escape(nrtid) + "&redirect=" + escape(page.getRedirect()))
}

function downloadExPortable(nrtid, duedate, comments) 
{  	
	var clientToAsp = getAppletById("ClientToAspApplet");
	var data = clientToAsp.getData(virtualPath()+ "/scripts/viewDoc.aspx?command=informationonly&nrtid=" + escape(nrtid)) + "";
	var docInfo;
	if ( data.length > 0 ) 
	{
		docInfo = eval(data);
	}
	if ( ! docInfo )
	{
		return;
	}
		
	if ( docInfo.VCObject.IsCheckedOut || docInfo.VCObject.CanCheckout != 1 )
	{		
		downloadEx(nrtid, "view");		
		return ;
	}
	
	//user has selected Integrated Chkout for default click option, but the admin is forcing the applet to 
	//be used instead
	if ( !(page.transferControl == TransferControl.ActiveX) )
	{
		//33392:  if admin has changed upld/downld to applet, display error msg to users
		locAlert(getLocStrByLID(1481, 'Integrated Checkout requires an ActiveX control, which your administrator has disabled.\nChoose a new Document Default Click Action in User Options.'))
		return;
	}
	
	//default click action may be integrated checkout, at which point we don't have a reference
	//to the activeX control yet.
	if ( typeof(transferCtrl) == 'undefined' )
	{
		var transferCtrl = getTransferCtrl();
	}
	
	var myPath = transferCtrl.GetPortableFilePath(docInfo.database, docInfo.VCObject.CurrentUser, docInfo.number, docInfo.version, docInfo.extension);
	//The original WebTransferCtrl does not provide the about GetPortableFilePath method and it
	//use the following properties to prepare the right paths for both the file itself and the PRF file.	
	//Since the PRF file path is still needed, so the following code is required. BX.
	transferCtrl.DocNum  = docInfo.number
	transferCtrl.Version  = docInfo.version
	transferCtrl.Database  = docInfo.database
	transferCtrl.UserID  = docInfo.VCObject.CurrentUser
	transferCtrl.Extension  = docInfo.extension
	transferCtrl.PortableCheckout = true		
	if (!transferCtrl.OpenByThirdParty(nrtid) )
	{
		//Note sure why this code is needed.Will revisit if something breaks. [HK 04.13.05]
		/*if (docInfo.IsCompound == "1") {
			url = virtualPath() + "/scripts/Checkout.aspx?nrtid=" + escape(nrtid)
			url = setURLParam(url, "redirect", escape(page.getRedirect()))
			url = setURLParam(url, "PortableCheckOut", "on")
			url = setURLParam(url,"open", "1")				
			window.location.href = url
		}else {*/
			duedate = duedate ? duedate : ""
			comments = comments ? comments : ""		
			var refreshParent = window.opener && page.popupDialog ? '' : '&refreshParent=1';
			var url = virtualPath() + "/scripts/ProgressBar.aspx?nrtid=" + escape(nrtid) + "&script=Checkout.aspx&action=0&open=1&path=" + escape(myPath) + "&portable=1" + refreshParent + "&duedate=" + escape(duedate) + "&comments=" + escape(comments)
			var wnd = openWindow(url, "Progressbar", 400, 100, "")
		//}
	}
}
					
function writeItemHeader(id, title, imgSrc, expand, menu,params, noTitle,adHocSearch, cssClass, form)
 {	
	imgSrc = imgSrc ? imgSrc : "pixel.gif"
	altImgStr = getAltImgText(imgSrc)
	var menuTitle = htmlString(title);
	
	title = page.zoomed == '0' ?  checkLength(title, kTitleDisplayLength) : title
		
	var themeRoot = getThemeRoot()
	var tableClass = noTitle ? "worksite-item-header-hidden" : (expand != "1" ? "worksite-item-header-collapsed" : "worksite-item-header")
	
	
	var expandClass = page.zoomed == "0" ? (expand != "1" ? "worksite-item-header-collapsed" : "worksite-item-header-expanded") : "worksite-item-header-zoomed"	
	var expandText = page.zoomed == "0" ? (expand != "1" ? "&#052;" : "&#054;") : ""
	var expandId = id.replace(/-/gi, "_")	
	var expandFunction = "javascript:toggleExpand(\'" + expandId + "\',\'" + escape(title) + "\')"
	var locString = (expand != "1" ? '{668|Expand section: }' : '{540|Collapse section:  }') 
	var zoomLink = page.zoomed == "0" ? '<a  href="' + setURLParam(page.getRedirect(), "id", id) + '">' : ''
	
	var closeLink = page.zoomed == "0" ? '</a>' : ''
	var adHocSearchHtml = '<center>' +
							'<a href = "javascript:toggleExpandAdhocSearch(\'' + expandId + '\',\'' + javaString(title) + '\',this)"	>' + htmlString(parseAndLocalizeStr("{1401|Click here to toggle search parameters screen}")) + '</a>' +							
						'</center>'
						
	var style = expand == "1" ? 'populated:1;originalid:' + id : 'display:none;populated:0;originalid:' + id 
	var imgSrc = imgSrc.substring(0,1) == "/" ? imgSrc  : virtualPath()+"/images/" + imgSrc	
	var html = 
		'<div class="worksite-portal-item ' + (cssClass ? cssClass : '') + '">' +	
			'<table id="header_table_'+ id +'" class="'+ tableClass + '">' +
				'<tr>' +
					'<td class="'+ expandClass +'" title="' + parseAndLocalizeStr(locString) + title + '">' +
						'<div class="' + expandClass + '">'+
							'<a class="'+ expandClass + '" href="'+ expandFunction +'"  id="grouping_' + expandId + '" title="' + parseAndLocalizeStr(locString) + htmlString(title) + '">' +
								(page.zoomed == "0" ? '&nbsp;' : '') +
								'<span id="span_'+ id +'" title="' + parseAndLocalizeStr(locString) + title + '" class="' + expandClass + ' worksite-item-header-expand-collapse-icon">' + 
									expandText +
								'</span>' +
							'</a>' +
						'</div>' +
					'</td>' +
					'<td class="worksite-item-header-icon" >' +
						'<div class="worksite-item-header-icon">' +
							'<img alt="' + altImgStr + '" align="absmiddle" src="'+ imgSrc + '" width=16 height=16 />' +
						'</div>' +
					'</td>' +
					'<td class="worksite-item-header-title" title="' + menuTitle + '">' + 
						zoomLink + 
						htmlString(title) + 
						closeLink +
					'</td>' +
					'<td class="worksite-item-header-menubar" >' + 
						( menu ? writeActionMenus("{523|Action}", true , menu ,true, params, menuTitle, imgSrc) : '&nbsp;') + 
					'</td>' +
					'<td class="worksite-item-header-right-corner">' +
						'&nbsp;' +
					'</td>' +
				'</tr>' + 
			'</table>' +
			(adHocSearch == true ? adHocSearchHtml : '') +
			'<div id="' + expandId + '" class="worksite-portal-item-content" style="' + style + '">' +
			(form ? ('<form name="fm-' + htmlString(id) + '" style="margin:0">') : '');
	
	if ( form)
	{
		window['close-form-' + id] = true;
	}	
	document.write(html)
}
		
function writeMultiActionMenus(menu,id,nrtid,hideChkBox) {
	var params
	var hRef=""
	var onClick =  menu ? htmlString('return showMenu(&quot;' + menu +'&quot;,&quot;'+ params+'&quot;)') : ""
	var root = virtualPath()
	var cls =  'action-button-big' 
	var str = '<table class="worksite-multi-form-header" cellpadding="1" cellspacing="0" width="100%" border="0" >'
		str+='<tr>'
		str += '<td width="1%" class="worksite-item-table-cell">'
		str +=' <input type="hidden" name="parent-' + htmlString(id) + '" value="' + htmlString(nrtid) + '" />'
		str += '<table width="100%" border="0" cellpadding="0" cellspacing="0" >'
		str+='<tr >'
	if (!hideChkBox) {
		str += '<td width="1%" id="multiOpChk">'+getMultiOpParentChkBox(id)+'</td>'
	}
		str+='<td align="right"> '+ eval(menu) +'</td>'
		str+='</tr></table>'
		str+='</td></tr></table>'
	document.write(str)
}

function getMultiOpParentChkBox(id) {
	var str = ""
	var title = getLocStrByLID(1148, "Select/Unselect All")
	str= '<input type="checkbox" name="group-sel-' + htmlString(id) + '" value="'+ htmlString(id) + '" onClick="selectAllItemCheckBox(this)" title="' + htmlString(title) + '">'
	return str
}

function doNothing() {
	//return false
}
function writeItemFooter(id) 
{
	document.write(
		(id && window['close-form-' + id] ? '</form>' : '') +
		'</div></div><br>'
	);
}

function getMenuButton(menuFn,params,title,img, headerID, alignment) {
	/*	Added headerID param on 5/28/02 (NS).  This is required
		for 508 compliance when spitting out data tables.  We
		must associate a headers attribute on each <td> with the
		id of the main <th>.
		
		Added alignment param on 9/5/02 (NS).  This is optional param
		that is needed to determine how to position button.  When the user
		has selected to display the menu button on the left, we should center-align.
		This is handled in iwpl.
	*/
	var html
	
	if (headerID) {
		headerID = "headers=\"" + headerID + "\""
	}
	
	if (!alignment) {
		alignment = "align=\"right\""
	} else {
		alignment = "align=\"" + alignment + "\""
	}
	
	if (headerID) {
		html = '<td class="worksite-icon" ' + alignment + ' width="1%" ' + htmlString(headerID) + '>' + writeActionMenus("{523|Action}", false, menuFn,false,params,title,img)  + '</td>'
	} else {
		html = '<td class="worksite-icon"' + alignment + ' width="1%">' + writeActionMenus("{523|Action}", false , menuFn,false,params,title,img)  + '</td>'
	}
	
	return html
}

function writeMenuButton(menuFn,params,title,img, headerID, alignment) {
	document.write(getMenuButton(menuFn,params,title,img, headerID, alignment))
}

function toggleExpand(id, title, dontUpdateServer) {
	setCookie("expandedItem","item=")
	var refresh = false
	var divStyle = getStyleObject(id)

	var populated = (divStyle.populated == '1')
	var originalID = divStyle.originalid
	
	var url = virtualPath() + "/scripts/" + "Expand.aspx?page=" + escape(page.id) + "&id=" + escape(originalID) + "&expand=" + (populated ? "0" : "1")
	var altString = ""	
	var className = ""
	if ( populated )
	{
		var span = document.getElementById("span_" + id);
		var headerTable = document.getElementById("header_table_" + id);
		if ( divStyle.display == "none" ) 
		{						
			divStyle.display = "block"
			altString="{540|Collapse section:  }"
			className = "worksite-item-header-expanded"
			if (span)
			{
				span.innerHTML = "&#054;"	
				span.title = parseAndLocalizeStr(altString) + title			
			}
			if(headerTable)		
			{			
				headerTable.className = "worksite-item-header";			
			}
		}
		else 
		{					
			divStyle.display = "none"
			altString="{668|Expand section:  }"
			className = "worksite-item-header-collapsed"	
			if (span)
			{				
				span.innerHTML = "&#052;"
				span.title = parseAndLocalizeStr(altString) + title		
			}	
			if(headerTable)		
			{
				headerTable.className = "worksite-item-header-collapsed";
			}
		}
	}
	else 
	{
		refresh = true
	}
		
	if ( refresh ) {
		setCookie("expandedItem","item="+id)
		var redirect = page.getRedirect()
		redirect = escape(redirect)
		window.location.href = setURLParam(url, "redirect", redirect)
		
	} else {
		// Notify the server
		var applet = getAppletById('clientToAspApplet')
		applet.putData(url)
				
		// change the image
		var expandItem = document.getElementById("grouping_" + id )
		if ( expandItem ) {
			expandItem.className = expandItem.parentElement.className =  expandItem.parentElement.parentElement.className = className 
			expandItem.title = parseAndLocalizeStr(altString) + title
		}
	}
}

function toggleExpandAdhocSearch(id,title){
	//var url = virtualPath()	

	var divStyle = getStyleObject(id)
	if ( divStyle.display == "none" ) {
		divStyle.display = "block"
		imgSrc = getThemeRoot()+ "/images/item-header-expanded.gif"
		//url = setURLParam(url, "expand", "1")
		altString="{540|Collapse section:  }"
	} else {
		divStyle.display = "none"
		imgSrc = getThemeRoot()+ "/images/item-header-collapsed.gif"
		//url = setURLParam(url, "expand", "0")
		altString="{668|Expand section:  }"
	}
	var groupingImg = document.images["grouping_" + id ]
	if ( groupingImg ) {
		groupingImg.src =  imgSrc
		groupingImg.alt=parseAndLocalizeStr(altString) + title
	}
}

function doOpen() {
	var options = document.fm.attachments.options
	var index = document.fm.attachments.selectedIndex
	if (index < 0) {
		locAlert(getLocalizedString("786|Please make a selection first"))
		return
	}
	var option = document.fm.attachments.options[index]
	var url
	var ar = option.value.split("|")
	url = ar[0]
	var	j = url.search("GetDoc.asp")
	if ( j >=0 ) {
		var nrtid = getURLParam(url, "nrtid")
		downloadExView(nrtid)
	} else {
		// url = "../scripts/" + url
		//Fix for 9120:  Open attachments in current window, not new window (NS, 1/27/02)
		var url = virtualPath() + "/scripts/" + url
		openWindow(url,"",600,600,"resizable=1");
	}
}

function toggleGroupExpand(itemID, groupBy, groupName, img, altImgText) {
	// This expand or collapses the specified group.  img should be the expand or collapse image.  id should be the container
	// that needs to have its display style changed.
	
	/*	NS, 6/6/02:  Had to add altImgText param for grouping by date-time.  groupName is formatted
		as YYYY-MM-DD"T"HH:MM.  If I display groupName on toggling, then this is not helpful for
		the user.  Therefore, have to format date in xsl and send to this function as a param.
		
		The alt text is required for 508 compliance.	
	*/
	if (!img) {
		return 
	}
	
	var expand
	var elem = document.getElementById(itemID + "-" + groupName)
	if (elem) {
		if (elem.style.display == 'none') {
			img.src = getThemeRoot()+ "/images/group-expand.gif"
			img.alt = parseAndLocalizeStr("{688|Collapse grouping: }") + htmlString(altImgText)
			elem.style.display = "inline"
			expand = "1"
		} else {
			img.src = getThemeRoot()+ "/images/group-collapse.gif"
			img.alt = parseAndLocalizeStr("{693|Expand grouping: }") + htmlString(altImgText)
			elem.style.display = "none"
			expand = "0"
		}
	}
}

function getNrtTypeName(nrtidString) 
{
	var NameDelimitor = '!';
	var ValueDelimitor = ':';

	if ( nrtidString ) 
	{
		if ( nrtidString.charAt(0) == MonikerStart )
		{
			var resultString = '';
			//Find start position of the last name value pair defined by the DMS moniker protocol. 
			var begin = nrtidString.lastIndexOf(NameDelimitor);

			//If there is a pair, get the corresponding value, else return an empty string.
			if (begin > -1) 
			{
				//Advance to the right of the name delimitor to exclude the name moniker.
				begin += 1;

				//Find the end position of the value delimited by the value delimitor.
				var end = nrtidString.indexOf(ValueDelimitor, begin);

				//Get the right value if it exists.
				if (begin < end) 
				{
					resultString = nrtidString.substring(begin, end).toLowerCase();
				}
			}
			return resultString;
		}
		else if ( nrtidString.charAt(0) == MonikerVirtualStart ) 
		{
			var idx = nrtidString.indexOf(NameDelimitor);
			if ( idx > 0 )
			{
				return nrtidString.substr(1, idx - 1).toLowerCase();
			}
			else
			{
				return nrtidString.substr(1).toLowerCase();
			}
		}
	}
	
	return '';
}

function getObjectTypeFromNrtid(nrtid, tmplt)
{
	switch ( getNrtTypeName(nrtid) )
	{
		case 'checkedoutlist':
			return 'imTypeDocuments';
		case 'connectorfolder':	
			return 'imTypeConnectorFolder';
		case 'contentshortcut':
			return 'imTypeContentShortcut';
		case 'contents':
			return 'imTypeContents';
		case 'database':
			switch ( tmplt )
			{
				case 'personal-folders':
				case 'public-folders':
					return 'imTypeDocumentFolders';
				case 'personal-pages':
				case 'public-pages':
					return 'imTypeWorkspaces';
				default:
					return 'imTypeDatabase';
			}
		case 'discussion':
			return 'imTypeMessage';
		case 'discussionfolder':
		case 'rootdiscussion': 
			return 'imTypeMessageFolder';
		case 'document':
			return 'imTypeDocument';
		case 'documentsearchfolder':
			return 'imTypeDocumentSearchFolder';
		case 'event':
			return 'imTypeEvent';
		case 'eventfolder':
			return 'imTypeEventFolder';
		case 'favoritesfolder':
		case 'rootfavoritesfolder':
			return 'imTypeFavoritesFolder';
		case 'folder':
			return 'imTypeDocumentFolder';
		case 'linklistfolder':
			return 'imTypeLinkListFolder';
		case 'notefolder':
			return 'imTypeNoteFolder';
		case 'page':
			return 'imTypeWorkspace';
		case 'pagesearchfolder':
			return 'imTypeWorkspaceSearchFolder';
		case 'recentpages':
		case 'workspaces':
			return 'imTypeWorkspaces';
		case 'session':
			return 'imTypeSession';
		case 'shortcutfolder':
			return 'imTypeFolderShortcut';
		case 'subscriptionfolder':
			return 'imTypeSubscriptionFolder';
		case 'task':
			return 'imTypeTask';
		case 'taskfolder':
			return 'imTypeTaskFolder';
		case 'worklist':
			return 'imTypeDocuments';
		case 'workarea':
			return 'imTypeWorkArea';

		default:
			return 'imTypeNone';
	}
}

function Page() {
	// this default values should be aprropriate for all temporary pages
	
	this.id			= ''
	this.access		= iEnums.nrReviewerAccess
	this._redirect	= virtualPath() + '/scripts/home.aspx'
	this.image		= virtualPath() + '/images/ipage.gif'
	this.type		= kTempPageType
	this.view		= ''
	this.debug		= ''
	this.zoomed		= '0'
	this.required	= '0'
	this.rights		= '0'
	this.title		= ''
	this.description = ''
	this.owner = ''
	this.database = ''
	this.enable508Menus = '0'
	this.theme = ''	// break if the theam is not set
	this.AdhocSearch = '' // quick-search / search
	this.helpFile = ''
	this.cssClass = ''
	this.showTitle = true
	this.showVerticalTabs = false
	this.popupDialog  = false
	
	this.load = Page_load
	this.isCurrentTabIsPage = Page_isCurrentTabIsPage
	this.getRedirect = Page_getRedirect
	this.getTabObj = Page_getTabObj	
}
function Page_getRedirect() 
{ 
	if ( this._redirect )
	{
		if ( this.getTabObj().getSelectedTab() )
		{
			return setURLParam(this._redirect, 'tabid', this.getTabObj().getSelection());
		}
		else
		{
			return this._redirect;
		}
	}
	else
	{
		return virtualPath() + "/scripts/home.aspx";
	}
}
function Page_getTabObj() 
{ 
	return window.innerTabsObj 
}
function Page_isCurrentTabIsPage()
{ 
	return this.getTabObj().getSelection() == this.id && this.id != ''; 
}
function Page_load(newPage)
{ 
	for(var i in newPage)
	{
		if ( typeof(newPage[i]) != 'function' )
		{
			this[i] = newPage[i];	
		}
	}
}

page = new Page()

window.g_menuid = 0

function showMenu(menu, params, srcName) 
{
	window.menuServerParams=htmlDeString(params)
	window.fw_menu = eval(menu)

	if (!window.fw_menu) return 
	
	var src = event.srcElement;
	while ( srcName && srcName != src.nodeName.toLowerCase() )
	{
		src = src.parentElement;
	}

	var left = posLib.getScreenLeft(src) + posLib.getWidth(src) - window.fw_menu.getPreferredWidth();
	var top = posLib.getScreenTop(src) + posLib.getHeight(src) - src.clientTop; 
	window.fw_menu.show(left,top); 
	return false
}

function redirectTo508Menu(url) {
	url = setURLParam(url,"tabid", page.getTabObj().getSelection())
	url = setURLParam(url,"redirect", escape(page.getRedirect()))
	window.location.href=(url)
	
}

function redirectTo508MenuEx(menu, menuParams, title, img) {

    var url = virtualPath()+ '/scripts/show508menu.aspx'
    url = setURLParam(url, "menu", htmlString(escape(menu)))
    url = setURLParam(url, "page", escape(page.id))
    url = setURLParam(url, "title", escape(title ? title : ""))
    url = setURLParam(url, "img", (img ? img : ""))
    url = setURLParam(url, "access", escape(page.access))
    url = setURLParam(url, "view", escape(page.view))
    url = setURLParam(url, "required", escape(page.required))
    url = setURLParam(url, "pageType", escape(page.type))
    url = setURLParam(url, "zoomed", escape(page.zoomed))
    url = setURLParam(url, "params", escape(menuParams ? menuParams : ""))   
	url = setURLParam(url, "tabID", escape(page.tabID))
	
	redirectTo508Menu(url)	
}

function writeActionMenus(buttonTxt, showCaption, menu,isItemHeader,params,title,img) {
	var hRef
	var onClick = ''
	
	title = title ? title : page.title
	var actionTitle = ''
	if (buttonTxt.indexOf("Action") > 0)
	{
		actionTitle = getLocalizedMessage(710, title) //Action menu for %1
	}
	else if (buttonTxt.indexOf("Add") > 0)
	{
		actionTitle = getLocalizedMessage(711, title) //Add menu for %1
	}
	
	if (page.enable508Menus == '1') 
	{
		//onClick = 'redirectTo508Menu(\''+ virtualPath()+ '/scripts/show508menu.aspx?menu='+htmlString(escape(menu))+'&page='+escape(page.id)+'&title='+escape(title)+'&img='+img+'&access='+escape(page.access)+'&view='+escape(page.view)+'&required='+escape(page.required)+'&pageType='+escape(page.type)+'&params='+escape(params ?params:"")+'\');return false'
		 onClick = 'redirectTo508MenuEx("' + menu + '", "' + (params ? params : "") + '", "' + title + '", "' + img + '");return false';
	}		
	else
	{
		onClick= menu ? 'showMenu("' + javaString(menu) + '", "' + javaString(params) + '"); return false' : ""
	}	
	
	if(isItemHeader)
	{

		return '<a class="worksite-item-header-menubar"  href="javascript:doNothing()" onclick="' + htmlString(onClick) + '" title="'+actionTitle+'"><span class="worksite-item-header-menubar">' + htmlString(parseAndLocalizeStr(buttonTxt)) +
				 '</span><span class="worksite-item-header-menubar-down-arrow">&#054;</span></a>'
	} 
	else
	{
		return	'<a class="worksite-small-action-menu" align="" href="javascript:doNothing()" onclick="' + htmlString(onClick) + '" title="' + htmlString(actionTitle) + '">' +  
					(showCaption ? ('<span class="worksite-action-title">' +  htmlString(parseAndLocalizeStr(buttonTxt)) + '</span>') : '') + 
					'<span class="worksite-down-arrow">&#054;</span>' + 
				'</a>'
	}				
}

function innerTabsAction(id)
 {
	
	if ( page.zoomed == '0' && page.populateAllTabs ) 
	{
		innerTabsObj.setSelection(id)
		var tabStyle
		var tab = innerTabsObj.getPrevSelectedTab()
		if ( tab ) 
		{
			tabStyle = getStyleObject(tab.getDomId())
			if ( tabStyle ) 
			{
				tabStyle.display = "none"
			}
		}
		tab = innerTabsObj.getSelectedTab()
		if ( tab ) 
		{
			tabStyle = getStyleObject(tab.getDomId())
			if ( tabStyle ) 
			{
				tabStyle.display = "block"
			}
		}
		var innerTabsDiv = window.document.getElementById("innerTabsDiv")
		if ( innerTabsDiv ) 
		{
			innerTabsDiv.innerHTML = innerTabsObj.render()
		}
	}
	else
	{
		window.location.href = virtualPath() + '/scripts/Home.aspx?page=' + escape(page.id) + '&tabid=' + escape(id);
	} 
}
	
function showAbout() {
	if (g_browser.isNS4) {
		openWindow(virtualPath() + "/scripts/About.aspx", "aboutWnd", 435, 300, "")
	}else {
		openWindow(virtualPath() + "/scripts/About.aspx", "aboutWnd", 510, 420, "")
	}	
}

function showHelp(topic) 
{
	topic = topic ? topic : page.helpFile;
	topic = topic ? topic : "Welcome.htm";
	
	var lcTopic = topic.toLowerCase();
	
	if ( !urlIsRelative(lcTopic) )
	{
		helpURL = topic;
	}
	else 
	{
		var langExt = window.lllist.abbreviation;

		if ( window.lllist.familyName == "en" )
		{
			if ( getCookie("enable508Menus") == "1" ) 
			{
				langExt = "en508";
			}
			else
			{
				langExt = "en";
			}
		}
		helpURL = virtualPath() + "/help/" + langExt + "/help/" + topic;
	}

	var helpWnd = window.open(helpURL, "help");
	if ( helpWnd )
	{
		helpWnd.focus();
	}
}

function getSectionHeader(caption)
{
	var str = '<table width="100%" border="0" cellspacing="0" cellpadding="0" align="center" >'
	if(caption) {
		str += '<tr><td class="worksite-section-header">'+htmlString(parseAndLocalizeStr(caption))+'</td></tr>'
	}
	str += '<tr><td  nowrap class="worksite-section-header-border"><img src="'+ virtualPath()+ '/images/pixel.gif" width="1" height="1" alt="" border="0"></td></tr>'
	str += '</table>'
	return str
}

function writeSectionHeader(caption) {
	document.write(getSectionHeader(caption))
}


function viewPreview(viewPreview) 
{
	var viewSelect = document.fm.elements[viewPreview]
	var viewID = viewSelect.options[viewSelect.selectedIndex].value
	if (viewID != 'sep' || viewID != 'custom') 
	{
		var url = virtualPath() + '/scripts/ViewPreview.aspx?view=' + escape(viewID)
		if ( g_browser.isNav ) 
		{
			var dialogWindow = window.open(url, 'dlg', 'height=400, width=480')
		} 
		else 
		{
			window.showModalDialog(url, '',  'dialogHeight: 400px; dialogWidth: 480px; center: yes; resizable: yes; help:no')		
		}
	}
}	

function writeFileXferApplet(transferControl, target, returnHTML) 
{	
	if(transferControl != TransferControl.FileControl)
	{
	    var transferCtrl = new WebTransferCtrl(transferControl);	    
	    
	    transferCtrl.AddParam(new WebTransferCtrlParam("FormName", "fm"))	    
	    if(transferControl == TransferControl.Applet)
        {           
           transferCtrl.AddParam(new WebTransferCtrlParam("cabbase", "iManage.cab"));
           transferCtrl.AddParam(new WebTransferCtrlParam("SendFormData", "yes"));
        }
        
    	switch(target)
    	{
    	    case 'hidden':
    	        transferCtrl.Style =  "position:absolute;top:1;left:1;height:1;width:1;float:right";
    	        transferCtrl.ViewAsText = true;
    	        if(transferControl == TransferControl.Applet)
	            {	            
		            transferCtrl.Mayscript = true;		              				        
		            transferCtrl.AddParam(new WebTransferCtrlParam("Action", "DownloadSelect"));		    
		            transferCtrl.AddParam(new WebTransferCtrlParam("FileCtrl", ""));		           
	            }
	            else 
	            {	                
		            transferCtrl.AddParam(new WebTransferCtrlParam("Action", "3"));		            
		            transferCtrl.AddParam(new WebTransferCtrlParam("_cx", "0"));
		            transferCtrl.AddParam(new WebTransferCtrlParam("_cy", "0"));
    	        }   
    	    break;
    	    case 'import':    	            	       
    	    case 'checkin':    	        
    	        if(transferControl == TransferControl.Applet)
	            {	         
		            transferCtrl.Style = "height:1;width:1;"
		            transferCtrl.AddParam(new WebTransferCtrlParam("Action", "UploadSelect"));		    
		            transferCtrl.AddParam(new WebTransferCtrlParam("FileCtrl", "File1"));
		            transferCtrl.AddParam(new WebTransferCtrlParam("Url", virtualPath() + "/scripts/checkin.aspx"));
		            transferCtrl.AddParam(new WebTransferCtrlParam("Debug", "true"));
	            }
	            else 
	            {	
		            if(target == 'import')
		            {
		                transferCtrl.Style = 'visibility:hidden;height:1;width:1;';
		            }
		            if ( target == 'checkin' && checkoutpath && checkoutpath.length > 0 )
		            {
			            transferCtrl.AddParam(new WebTransferCtrlParam("BrowsePath", checkoutpath));
		            }
		            transferCtrl.AddParam(new WebTransferCtrlParam("Action", "1"));
		            transferCtrl.AddParam(new WebTransferCtrlParam("DestinationURL", virtualPath() + "/scripts/Checkin.aspx"));	            
    	        }   
    	    break;
    	    case 'checkout':    	        
    	    case 'download':
    	        var destAspx = target == 'checkout' ? "CheckOut.aspx" : "Export.aspx";
    	        transferCtrl.ViewAsText = false;
    	        if(transferControl == TransferControl.Applet)
	            {
	                transferCtrl.Style = "height:1;width:1;"
	                transferCtrl.Mayscript = false;		        
	                transferCtrl.AddParam(new WebTransferCtrlParam("Action", "DownloadSelect"));		    		            
		            transferCtrl.AddParam(new WebTransferCtrlParam("Url", virtualPath() + "/scripts/" + destAspx));
	            }
	            else 
	            {
	                transferCtrl.Style = "width:100%";
		            transferCtrl.AddParam(new WebTransferCtrlParam("DefaultFilename", defaultName));	
		            transferCtrl.AddParam(new WebTransferCtrlParam("Action", "0"));			            		            
		            transferCtrl.AddParam(new WebTransferCtrlParam("DestinationURL", virtualPath() + "/scripts/" + destAspx));
    	        }   
    	    break;
    	}	    
    	
    	if(returnHTML)	
    	{
    	    return transferCtrl.GetHtml();    	    
    	}
    	else
    	{
	        transferCtrl.Write();    	    
	    }
	}
	window.onloadAdvise(validateTransferControl)	
}

//Trim description of any item to the supplied maximum number of characters.
function checkMaxChars(src, maxChars)
{							
	if ( src.value.length >= maxChars ) 
	{
		src.value = src.value.substr(0, maxChars )													
	}									
}

var is508User = getCookie("enable508Menus") == "1";

var keyCodes = 
{
	/*
		key maps:
		left arrow: 37;
		right arrow: 39;
		up arrow: 38;
		down arrow: 40
		shift key: 16;
		tab key: 9;
		space bar: 32;
		enter: 13;
		minus (dash):  189 --> replaced I since JAWS 5.0 now uses I for IE shortcut
		open bracket:  219 --> replaced J since JAWS 5.0 now uses J for IE shortcut
		close bracket:  221 --> replaced K since JAWS 5.0 now uses K for IE shortcut
		quotes:  222 --> replaced M since JAWS 5.0 now uses M for IE shortcut
		semicolon: 186;
		apostrophe: 222;
	*/
	ARROW_LEFT: this.is508User ? 219 : 37,
	ARROW_UP: this.is508User ? 189 : 38,
	ARROW_RIGHT: this.is508User ? 221 : 39,
	ARROW_DOWN: this.is508User ? 222 : 40,
	SHIFT: 16,
	TAB: 9,
	SPACE: this.is508User ? 186 : 32,
	ENTER: this.is508User ? 222 : 13
}

function dispatch(id, method, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) 
{
	var obj = document.getElementById(id);
	if ( ! obj && window.dispatchRegistry )
	{
		obj = window.dispatchRegistry[id];
	}
	return dispatchEx(obj, method, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10);
}

function dispatchEx(obj, method, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) 
{
	if ( obj && method && obj[method] && (typeof(obj[method]) == "function" || typeof(obj[method]) == "object") ) 
	{
		return obj[method](param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)
	}
}

function makeDispatch(id, method)
{
	return function(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) 
	{
		return dispatch(id, method, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10);
	}
}

/*
function makeDispatchEx(obj, method)
{
	return function(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) 
	{
		return dispatchEx(obj, method, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10);
	}
}
*/

function bindDispatch(id, method, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)
{
	return function() 
	{
		return dispatch(id, method, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10);
	}
}

function bindDispatchEx(obj, method, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)
{
	return function() 
	{
		return dispatchEx(obj, method, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10);
	}
}

function bindFunction(f, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)
{
	return function() 
	{
		return f(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10);
	}
}

function bindEx0(obj, method)
{
	return function(param1, param2, param3)
	{
		return obj[method](param1, param2, param3);
	}
}

function bindEx1(obj, method, param1)
{
	return function(param2, param3)
	{
		return obj[method](param1, param2, param3);
	}
}

function joinFunctions(f1, f2, f3)
{
	return function() 
	{
		if ( f1 && (typeof(f1) == 'function' || typeof(f1) == 'object') )
		{
			f1();
		}
		if ( f2 && (typeof(f2) == 'function' || typeof(f2) == 'object') )
		{
			f2();
		}
		if ( f3 && (typeof(f3) == 'function' || typeof(f3) == 'object') )
		{
			f3();
		}
	}
}
function dispatchRegister(id, obj) 
{
	if ( ! window.dispatchRegistry ) 
	{
		window.dispatchRegistry = new Object();
	} 
	window.dispatchRegistry[id] = obj;
}

function dispatchUnregister(id) 
{
	if ( id && window.dispatchRegistry ) 
	{
		window.dispatchRegistry[id] = null;
	} 
}

function getUniqueId()
{
	var unitIdPrefix = "unique-id-prefix"
	if ( ! window.lastUniqueId )
	{
		window.lastUniqueId = 1;
	}
	else
	{
		window.lastUniqueId++;
	}
	return unitIdPrefix + "-" + window.lastUniqueId;
}

function functionVoid() { }
function functionEmpty() { return ''; }
function functionFalse() { return false; }
function functionTrue() { return true; }
function functionCancelBubble() { if ( window.event ) window.event.cancelBubble = true; }

function parseXml(xml, returnError) {
	var doc = null;
	if ( g_browser.isIE ) 
	{
		if ( typeof(xml) == 'string' && xml )
		{
			doc = new ActiveXObject("MSXML2.DOMDocument")
			doc.resolveExternals = false
			doc.validateOnParse = false
			doc.async = false
			var success = doc.loadXML(xml)
			if ( ! success && doc.parseError ) 
			{
				if ( returnError )
				{
					return doc.parseError.reason + "\n" + trim(doc.parseError.srcText);
				}
				else
				{
					alert(doc.parseError.reason)
					return null
				}
			}
		}
		else if ( typeof(xml) == 'object' && xml.nodeName == '#document' )
		{
			doc = xml;
		}
	}
	return doc
}

function AlternativeImageText() {	
	
	var obj = new Object()
	obj["globaloptions"] = 614 //"Global Options
	obj.archived = 969 // "Archived
	obj.avi = 648 // "AVI file
	obj.addtab = 788 // "Add Tab
	obj.archived = 969 // "Archived	
	obj.bmp = 590 // "BMP file
	obj.browse = 246 // Browse
	obj.bullet = 541 // "Bullet
	obj.cal = 278 // "Calendar
	obj.caloptions = 348 // "Calendar Options
	obj["category-favorite"] = 139 //Category
	obj["category-matters"] = 139 //Category
	obj.checkedout = 164 // "Checked out
	obj.checkedoutdocs = 164 //Checked out
	obj.connectors = 547 // "Connectors
	obj.connector = 585 // "Connector
	obj["connector-new"] = 606 // "New
	obj.database = 150 // "Database
	obj["default"] = 481 // "Unknown file type
	obj.discussion = 316 // "Discussion
	obj.doc = 582 // "Word document
	obj.doclink = 90
	obj.dochdr = 343 // "Icon
	obj.editprofilebtn = 461 // "Edit Profile
	obj["event"] = 314 // "Event
	obj.eventcategory = 104 // "Event Categories
	obj["event-find"] = 324 // "Event Search
	obj["event-findsaved"] = 324 // "Event Search
	obj["event-folder"] = 278 // "Calendar
	obj.exclaim = 131 // "High
	obj.externaluser = 1388	// External User
	obj.favorites = 558 // "Favorites
	obj.favoritecategory = 139 // "Category
	obj.fax = 375 // "Fax
	obj.fdf = 496 // "Acrobat file
	obj.folder = 429 // "Folder
	obj.folderlink = 574 // "Folder Link
	obj.gif = 643 // "GIF file
	obj.generalsettings = 287 // "General
	obj.group = 355 // "Group
	obj["group_ex"] = 1389 // External Group
	obj.homepage = 253 // "Start Page
	obj["homepages"] = 544 //"Start Pages
	obj.htm = 274 // "HTML
	obj.html = 274
	obj.ipage = 279 // "Page
	obj.ipagelink = 279
	obj.ipages = 560 // "Pages
	obj.imanagepowered = 580	// "Goto:http://www.imanage.com"
	obj.importdoc = 366 // "Import Document
	obj.importurl = 367 // "Import URL
	obj.jpg = 638 // "JPEG file
	obj.layout = 519 // "Layout
	obj.lgbullet = 541 // "Bullet
	obj.link = 114 // "Link
	obj["link-list"] = 489 //Link List
	obj.locked = 970 // "Locked
	obj.manage = 584
	obj.matter = 1201 // Matter
	obj.matters = 1211 //Matters
	obj.minus = 543 // "Expanded
	obj.mmp = 529 // "Microsoft Project
	obj.mode = 45 // "Mode
	obj.morebtn = 945 // "More
	obj.msg = 323 // "Email message
	obj["navigation-menu"] = 1312 //Navigation menus
	obj.newsubfolderbtn = 368 // "Add subfolder
	obj.note = 581 // "Note
	obj.notification = 216 // "Notification
	obj["options"] = 345 //"User Options
	obj.pageprofile = 490 // "Profile
	obj.pagesearch = 577 // "Page Search
	obj["pagesearchform"] = 578 //"Page Search Form"
	obj["pagesearchprofile"] = 225 //"Page Search Profile"
	obj["pagesearchsaved"] = 577 // "Page Search
	obj.pagesearchopen = 578 // "Page Search Form
	obj.paperclip = 123 // "Attachments
	obj.pdf = 496 // "Acrobat file
	obj.plus = 561 // "Collapsed
	obj.privileges = 357 // "Privileges
	obj.profile = 490 // "Profile
	obj["profiles"] = 549 //"Document Profiles
	obj["properties"] = 115	//Properties
	obj.ppt = 499 // "PowerPoint file
	obj.psd = 532 // "Photoshop file
	obj.qpw = 530 // "QuattroPro file
	obj.recentpages = 1211 //Matters
	obj.related = 488 // "Related Documents
	obj.resources = 362 // "Resources
	obj.role = 364 // "Role
	obj.roles = 364 // "Role
	obj.rolemanagement = 397 // "Role Management
	obj.root = "WorkSite"
	obj.sbtab = 1141 // "Tab
	obj.search = 575 // "Document Search
	obj["searchcontainer"] = 247 //"Search
	obj["searchsaved"] = 575 // "Document Search
	obj.searchopen = 575 // "Document Search
	obj.searchfolder = 962 // "Search Folder
	obj.searchform = 576 // "Document Search Form
	obj.security = 214 // "Security
	obj.session = 528 // "Session
	obj.settings = 217 // "Settings
	obj.statushdr = 229 // "Status
	obj.tab = 1141 // "Tab
	obj.task = 275 // "Task
	obj.tasks = 321 // "Tasks
	obj.tasksearch = 280 // "Task Search
	obj["tasksearchsaved"] = 280 // "Task Search
	obj.tif = 646 // "TIFF image file
	obj.topic = 974 // "Topic
	obj["tree-minus"] = 543 // "Expanded
	obj["tree-minus-down"] = 543 // "Expanded
	obj["tree-minus-up"] = 543 // "Expanded
	obj["tree-minus-up-down"] = 543 // "Expanded
	obj["tree-plus"] = 561 // "Collapsed
	obj["tree-plus-down"] = 561 // "Collapsed
	obj["tree-plus-up"] = 561 // "Collapsed
	obj["tree-plus-up-down"] = 561 // "Collapsed
	obj.txt = 766 // "Plain text
	obj.user = 395 // "User
	obj.useroptions = 345 //User Options
	obj.url = 307 // "URL
	obj.view = 106 // "View
	obj["view-document"] = 550 //Document Views
	obj["view-workspace"] = 1323 //WorkSpace Views
	obj.versions = 487 // "Document Versions
	obj.vsd = 515 // "Visio file
	obj.wpd = 583 // "WordPerfect document
	obj.wri = 667 // "Windows Write document
	obj.wav = 650 // "WAV file
	obj.worklist = 555 //Documents
	obj["workspace-template"] = 196
	obj["workspace-templates"] = 546
	obj.xls = 520 // "Excel file
	obj.xml = 660 // "XML
	obj.zip = 524 // "Compressed file
	
	return obj
}

var alternativeImageText = new AlternativeImageText()

function getAltImgText(imgSrc) {
/*	This function returns text to be used for the alt attribute on an image
	NOTE:  not all images are supported.
*/
	var startPos
	var endPos
	var imgName = ""
	var altText = ""

	if ( ! imgSrc || imgSrc.indexOf("pixel.gif") >=0 ) {
		return imgName
	}
	
	startPos = imgSrc.lastIndexOf("/") + 1
	endPos = imgSrc.lastIndexOf(".")
	
	imgName = imgSrc.slice(startPos, endPos).toLowerCase()
	var altText = alternativeImageText[imgName]
	return altText ? getLocStrByLID(altText) : ""
}

function subscribeMatter(){
	var url = virtualPath() + "/scripts/MatterDialog.aspx?id=&functionName=matterSubscriptionCallback"
	var winObj= openWindow(url,"", 420 , 490, "scrollbars=no")
}

//id is not used here
function matterSubscriptionCallback(id, values)
{
	if (values) {
		var url = virtualPath() + "/scripts/MatterSubscribe.aspx?users=" + escape(values);
		var applet = getAppletById("clientToAspApplet");
		if (applet) {
			var result = applet.getData(url);
			if (applet.hasError) 
			{
				locAlert(applet.errorMessage)
			}
			else 
			{
				var href;
				if (getCookie("enable508Menus") == "1")
				{
					//need to redirect for 508 users back to original page
					href = window.location.href.toLowerCase().indexOf("/show508menu") > 0 ?
						page.getRedirect() : window.location.href;
				}
				else
				{
					href = window.location.href;
				}
				
				window.location.href = href;
			}
		}	
			
	}
}

function formatTimeSpan(seconds) {
	var hours = Math.floor(seconds / 3600)
	hours = hours < 10 ? "0" + hours .toString() : hours.toString()
	var minutes = Math.floor((seconds - hours * 3600) / 60)
	minutes = minutes < 10 ? "0" + minutes : minutes.toString() 
	seconds = seconds - hours * 3600 - minutes * 60
	seconds = seconds < 10 ? "0" + seconds.toString() : seconds.toString()
	document.write(hours + ":" + minutes + ":" + seconds)
}
	
function selectCheckBoxRow(obj) 
{
	checkParentCheckBoxStatus(obj);
	var trObj = obj.parentNode.parentNode
	if(trObj) 
	{
		if(obj.checked) 
		{
			trObj.setAttribute("old_color", trObj.style.backgroundColor);
			trObj.style.backgroundColor = "#eef0fb";
			obj.lastCheck = new Date();
		}
		else 
		{
			var bgColor = trObj.getAttribute("old_color");
			trObj.style.backgroundColor = bgColor ? bgColor : "#ffffff";
			obj.lastCheck = null;
		}	
	}
}	

function checkParentCheckBoxStatus(obj) 
{
	if ( ! obj.checked )
	{
		var id = obj.name.replace("nrt-chk-", "")
		var parentObj = document.getElementById("group-sel-" + id);
		if ( parentObj )
		{
			parentObj.checked = false
		}
	}
}

function changeCheckBoxRow(obj) 
{
	if (event.propertyName == 'checked' )
	{
		selectCheckBoxRow(obj);
	}
}

function clickCheckBoxRow(obj) 
{
	if ( obj.checked && obj.lastCheck && (new Date()) - obj.lastCheck > 50 )
	{
		obj.checked = false;
	}
}
function selectAllItemCheckBox(obj,value) 
{
	var id
	if((typeof obj) == "string") 
	{
		id = obj
	}
	else 
	{
		id = obj.value
		value = obj.checked		
	}
	
	var nrtItemsObj = new NRTItems(id)	//obj.value contain the ID
	// to check/uncheck all the checkboxes below this item
	if( ! nrtItemsObj.checkAll(value) ) 
	{
		obj.checked = !value
	}		
}

function beginGroup(id, groupBy, name, expand) {
	var title = name != "!" ? name : getLocStrByLID(1133, "No Category")
	var str = ""
	if (!g_browser.isNS4) {
	str+=	'<tr>' +
			'<td width="1%">' +
				'<a href="#" onclick="javascript:toggleGroupExpand(\'' + javaString(id) + '\', \'' + javaString(htmlString(groupBy)) + '\',\'' + javaString(htmlString(name)) + '\', this.firstChild, \'' + javaString(htmlString(title)) + '\');return false">' +
					( expand == '1'
						? '<img border="0" width="16" height="16" src="'+getThemeRoot()+'/images/group-expand.gif" alt="' + htmlString(parseAndLocalizeStr("{688|Collapse grouping: }") + title) + '"/>'
						: '<img border="0" width="16" height="16" src="'+getThemeRoot()+'/images/group-collapse.gif" alt="' + htmlString(parseAndLocalizeStr("{693|Expand grouping: }") + title) + '"/>'
					) +
				'</a>' +
			'</td>'
	} else {
	//Fix for 13554:  Do not give hyperlink on expanded image since we always have items expanded for NS4.x (NS, 10/8/02)
	str+=	'<tr>' +
			'<td width="1%">' +
				'<img border="0" width="16" height="16" src="'+getThemeRoot()+'/images/group-expand.gif" />' +
			'</td>'
	}
	str+='<td class="worksite-group-heading" colspan="5" width="99%">' +
				title +
			'</td>' +
		'</tr>' +
		'<tbody id="' + id + "-" + name + '" ' + ( expand != "1" && !g_browser.isNS4 ? 'style="display:none"' : '') + ' >'
	document.write(str)
}

function endGroup(msg, colspan) {
	document.write(			
			'<tr>' +
				'<td></td>' +
				'<td><img src="' + virtualPath() + '/images/blankIcon.gif"/></td>' +
				'<td class="worksite-message" colspan="' + (colspan ? colspan : 3) + '" align="center">' +
					'<em>' + (msg ? eval(msg) : '') + '</em>' +
				'</td>' +
			'</tr>' +
		'</tbody>'
		)
}


function openAsHTML(nrtid) {
	//We now support multiple docs being viewed as HTML; therefore, must open a separate window for each document
			
	if (nrtid.charAt(nrtid.length-1) == kMultiOpSeparator)
	{
		nrtid = nrtid.slice(0, nrtid.length-1)
	}
	var nrtAry = nrtid.split(kMultiOpSeparator)
	for (var j = 0; j<nrtAry.length; j++) {
		var url=virtualPath() + "/scripts/viewDoc.aspx?nrtid=" + escape(nrtAry[j]) + "&ishtml=1&command=ok&redirect=" + escape(page.getRedirect());
		var wnd=window.open(url, "viewDoc_" + j, "scrollbars=yes, resizable=yes, toolbar=yes, location=yes, menubar=yes")
	}

}

function getAccessEnum(access){
	switch(access){
		case "nrRightAll":
		case "3":
			return iEnums.nrRightAll;
		case "nrRightReadWrite":
		case "2":
			return iEnums.nrRightReadWrite;	
		case "nrRightRead":
		case "1":
			return iEnums.nrRightRead;
		case "nrRightNone":
		case "0":
			return iEnums.nrRightNone;
		
	}
}

function getDocumentOptionMessage(documentOption) {
	switch ( documentOption ) {
		case 'view':
			return 951
		case 'viewHTML':
			return 460
		case 'checkOut':
			return 960
		case 'portable':
			return 961
		case 'profile':
			return 964
		default:
			return 0
	}
}

function checkLength(str, size)
{
	if( str.length > size)	
	{
		return str.substring(0, size) + "...";
	}
	return str;
}

function getItemCountMsg(count,overflow, total, singleItemName, multiItemName) {
	document.write(eval(getItemCountMsgEx(count,overflow, total, singleItemName, multiItemName)))
}

function getItemCountMsgEx(count,overflow, total, singleItemName, multiItemName ) {
	if (!singleItemName) {
		singleItemName = "1054|Item"
	}
	
	if (!multiItemName) {
		multiItemName = "1055|Items"
	}
	if (count > 0) {
		if (total && total != "0") {
			return 'getMessage("1051", "' + count + '", "' + total + '", getLocalizedString("' + multiItemName + '"))'
		}

		if (!overflow || overflow == "0") {
			if (count == 1) {
				return '\'1 \' + getString("", "{' + singleItemName + '}", "")'
			} else {
				return '\'' + count + ' \' + getString("", "{' + multiItemName + '}", "")'
			}
		} else {
			overflow = Number(overflow)
			if(!isNaN(overflow))
			{
				if (overflow < 0) {
					return 'getMessage("1051", "' + count + '", "' + count + '", getLocalizedString("' + multiItemName + '"))'		
				} else {
					return 'getMessage("1051", "' + count + '", "' + (count + overflow) + '", getLocalizedString("' + multiItemName + '"))'
				}			
			}
			else
			{
				return 'getMessage("1051", "' + count + '", "' + count + '", getLocalizedString("' + multiItemName + '"))'					
			}
		}
	}
	else
	{	
			return 'parseAndLocalizeStr("{414|There are no items to display.}")'
	}
}

function openSelectedLink(xmlElement) 
{
	if ( xmlElement ) 
	{ 
		openSelectedLinkEx(xmlElement.getAttribute("href"), xmlElement.getAttribute("target"))
	}
}

function openSelectedLinkEx(href, target) 
{
	if ( href ) 
	{
		if ( target == 'ws_childframe' ) 
		{
			openPortalLink(virtualPath() + "/scripts/redirector.aspx?url=" + escape(href))
		} 
		else if ( href.indexOf("javascript:") == 0 ) 
		{
			eval(href.substr("javascript:".length))
		} 
		else if (!urlIsRelative(href))
		{
		    if ( target == '_self')
			{
				openPortalLink(href)
			}
			else if( target == "_blank")
			{
				window.open(href);
			}
		}
		else 
		{
			href = setURLParam(href, "redirect", escape(page.getRedirect()))
			if ( target == '_self' && isHomeLink(href) && !isDocumentLink(href))
			{
				openPortalLink(href)
			}
			else if( target == "_blank")
			{
				window.open(href);
			}
			else
			{
				openDialogWindow(href)
			}
		}
	}
}

function isHomeLink(href)
{
	href = href.toLowerCase()
	return href.indexOf('home.aspx') > -1 | href.indexOf('portal.aspx') > -1 | href.indexOf('admin.aspx') > -1 | href.indexOf('manage.aspx') > -1
}

function isDocumentLink(href)
{
	href = href.toLowerCase()
	return href.indexOf('getdoc.aspx') > -1 
}

function openPortalLink(href, replace)
{
	var frame = window.frames[kMainFrameName] ? window.frames[kMainFrameName] : window;
	if ( replace )
	{
		frame.location.replace(href);
	}
	else
	{
		frame.location = href;
	}
}

function synchronizePortal()
{
	if ( window.name == kMainFrameName && window.parent !== window )
	{
		var parent = window.parent
		parent.setCookie('url', escape(window.location.href));
		
		if ( parent.lllist.lcid != window.lllist.lcid 
			|| (parent.page.theme != window.page.theme && window.page.theme ) )
		{
			parent.location.reload()
		}
		else
		{
			parent.page.load(window.page);
			
			if ( parent.checkQuickSearchCurrentOption )
			{
				parent.checkQuickSearchCurrentOption()
			}
			if ( window.sidebar )
			{
				window.sidebar.refresh(parent);
			}
		}
	}
}

window.onloadAdvise(synchronizePortal)

function dueDateSelectArray()
{
	/*	Removed per Mohit's email on 9/22/03 ; 
		'last week' too confusing w/last 30 days, 
		and last 30 days is more explicit, etc. (NS, 9/23/03) 
	*/
	var dateFilterValues = new Array()
	dateFilterValues[dateFilterValues.length] = ",,0"	
	dateFilterValues[dateFilterValues.length] = "overdue," + getLocalizedString('767|Overdue') + ",0"															
	dateFilterValues[dateFilterValues.length] = "today," + getLocalizedString('173|Today') + ",0"															
	dateFilterValues[dateFilterValues.length] = "tomorrow," + getLocalizedString('753|Tomorrow') + ",0"															
	dateFilterValues[dateFilterValues.length] = "last 7 days," + getLocalizedString('754|Last 7 days') + ",0"															
	dateFilterValues[dateFilterValues.length] = "next 7 days," + getLocalizedString('755|Next 7 days') + ",0"															
	dateFilterValues[dateFilterValues.length] = "last 30 days," + getLocalizedString('149|Last 30 days') + ",0"															
	dateFilterValues[dateFilterValues.length] = "next 30 days," + getLocalizedString('112|Next 30 days') + ",0"															
	dateFilterValues[dateFilterValues.length] = "this month," + getLocalizedString('760|This month') + ",0"															
	dateFilterValues[dateFilterValues.length] = "on or before," + getLocalizedString('762|On or before') + ",1"															
	dateFilterValues[dateFilterValues.length] = "on or after," + getLocalizedString('763|On or after') + ",1"															
	dateFilterValues[dateFilterValues.length] = "on," + getLocalizedString('764|On') + ",1"															
	dateFilterValues[dateFilterValues.length] = "between," + getLocalizedString('765|Between') + ",2"																
	return dateFilterValues														
}

function startDateSelectArray()
{
	/*	Removed per Mohit's email on 9/22/03 ; 
		'last week' too confusing w/last 30 days, 
		and last 30 days is more explicit, etc. (NS, 9/23/03) 
	*/
	var dateFilterValues = new Array()
	dateFilterValues[dateFilterValues.length] = ",,0"	
	dateFilterValues[dateFilterValues.length] = "on or after today," + getLocalizedString('266|Active') + ",0"															
	dateFilterValues[dateFilterValues.length] = "yesterday," + getLocalizedString('752|Yesterday') + ",0"															
	dateFilterValues[dateFilterValues.length] = "today," + getLocalizedString('173|Today') + ",0"															
	dateFilterValues[dateFilterValues.length] = "tomorrow," + getLocalizedString('753|Tomorrow') + ",0"															
	dateFilterValues[dateFilterValues.length] = "last 7 days," + getLocalizedString('754|Last 7 days') + ",0"															
	dateFilterValues[dateFilterValues.length] = "next 7 days," + getLocalizedString('755|Next 7 days') + ",0"															
	dateFilterValues[dateFilterValues.length] = "last 30 days," + getLocalizedString('149|Last 30 days') + ",0"															
	dateFilterValues[dateFilterValues.length] = "next 30 days," + getLocalizedString('112|Next 30 days') + ",0"															
	dateFilterValues[dateFilterValues.length] = "this month," + getLocalizedString('760|This month') + ",0"															
	dateFilterValues[dateFilterValues.length] = "on or before," + getLocalizedString('762|On or before') + ",1"															
	dateFilterValues[dateFilterValues.length] = "on or after," + getLocalizedString('763|On or after') + ",1"															
	dateFilterValues[dateFilterValues.length] = "on," + getLocalizedString('764|On') + ",1"															
	dateFilterValues[dateFilterValues.length] = "between," + getLocalizedString('765|Between') + ",2"																
	return dateFilterValues														
}

function writeButtonHTML (caption,cmdHandler,title,className,accessKey,id,enable, display)
{
	document.write(getButtonHTML(caption,cmdHandler,title,className,accessKey,id,enable, display))
}
function getButtonHTML (caption,cmdHandler,title,className,accessKey,id,enable, display)
{
	var strTitle ;
	var straccessKey ;
	var strId ;
	var strCmd ;
	var strStyle ;
	var strDisplay;
	var enable508 = getCookie("enable508Menus")
	cmdHandler = cmdHandler + ";return false"
	
	if ( typeof(title) == "undefined" || title == null) 
	{
		strTitle = '' ;
	}
	else
	{
		strTitle = 'title="' + htmlString(title) +'"'  ;
	}
	
	if ( typeof(accessKey) == "undefined" || accessKey == null) 
	{
		straccessKey =''
	}
	else 
	{
		straccessKey='accesskey="' + accessKey +'"' ;
	}
		
	if ( typeof(id) == "undefined" || id == null) 
	{
		strId =""
	}
	else 
	{
		strId=' id="' + htmlString(id) + '"';
	}

	if ( (typeof(enable) != "undefined" &&  enable != null && !enable) || enable508 == '1')
	{
		strCmd = ' onclick=\"' +htmlString(cmdHandler)+'\"; onmousedown="doNothing();" onmouseup="doNothing();" onmouseout="doNothing();"'
	}
	else
	{
		strCmd = ' onclick=\"' +htmlString(cmdHandler)+'\" onmousedown="this.className=\'worksite-button-selected\'" onmouseup="this.className=\'worksite-button-selected\'" onmouseout="this.className=\'worksite-button\'"'
	}	
	
	if ( display )
	{
		strDisplay = 'display:' + display; + ';';
	}
	
	if(enable508 == '1')
	{		
		return ("<input class='worksite-dialog-button' align='left' style='display: inline; " + strDisplay + "' type='button' value='" + htmlString(caption) + "' " + strCmd + straccessKey + strTitle + strId +"/>")
	}
	else
	{
		return '<span class="worksite-button" style="' + strDisplay + '" ' +  strId + strCmd + '><a href="javascript:void(0)"' +  straccessKey +  strTitle + ' ><span>' + htmlString(caption) +  '</span></a></span>'
	}
	
}

function getSearchFor(id, defaultVal, style, readOnly)
{
	return "<select id='" + htmlString(id) + "' name='" + htmlString(id) + "'" + (style ? " style='" + htmlString(style) + "'"  : "") + (readOnly ? " disabled" : "") + ">" +
			"<option value='imSearchEmailOrDocuments' " + (! defaultVal || defaultVal == "imSearchEmailOrDocuments" ? "selected='selected'" : "") + ">" + htmlString(getLocStrByLID(625, "Documents/Emails")) + "</option>" +
			"<option value='imSearchEmailOnly' " + (defaultVal == "imSearchEmailOnly" ? "selected='selected'" : "") + ">" + htmlString(getLocStrByLID(626, "Emails")) + "</option>" +
			"<option value='imSearchDocumentsOnly' " + (defaultVal == "imSearchDocumentsOnly" ? "selected='selected'" : "") + ">" + htmlString(getLocStrByLID(555, "Documents")) + "</option>" +
		"</select>";
}

function removeRelation(parentId, childIds)
{
	var url = virtualPath() + "/scripts/DocRemoveRelation.aspx?"
	url = setURLParam(url, "parent", escape(parentId));
	url = setURLParam(url, "children", escape(childIds));
	url = setURLParam(url, "redirect", escape(page.getRedirect()));
	
	window.location.href = url;
}

function getSearchButton(formName, buttonOnBottom)
{
	return getButtonHTML(parseAndLocalizeStr("{247|Search}") ,"javascript:validateAdvancedSearch('" +javaString(formName) + "')",parseAndLocalizeStr("{1327|Begin search}"));
}

function writeSearchButton(formName, buttonOnBottom)
{
	document.write(getSearchButton(formName, buttonOnBottom));
}
 
 function doAdvancedSearchCancel()
 {
	var url
	if(document.fm){
		if(document.fm.redirect) {
			url  = document.fm.redirect.value
		}	
	}
	if(!url || url == "") {
		url = virtualPath() + "/scripts/home.aspx"
	 }
	window.location.href = url
 }
 
function worksiteMore(url, partID)
{
	window.location.reload(setURLParam(url || window.location.href, 'more', '1'));
}
 
 function makeZoomUrl(pageID, itemID, nrtid)
 {
	return virtualPath() + '/scripts/Home.aspx?page=' + escape(pageID) + '&id=' + escape(itemID) + '&nrtid=' + escape(nrtid);
 }
 
 function doMoreSearch(formName) {
	formName = formName ? formName : "fm"
	var fm = document.forms(formName);
	if(fm.tabid) {
		fm.tabid.value = page.getTabObj().getSelection() 
	}
	var  queryString = constructAdvancedSearyQuery(formName)
	//fix for 22084:  More button does not work on adhoc searches (NS, 3/15/04)
	queryString = setURLParam(queryString, 'more', '1')
	window.location.href = queryString
 }
 
 function constructAdvancedSearyQuery(formName) {
	formName = formName ? formName : "fm"
 	var fm = document.forms(formName)
 	if(fm.redirect)
 	{
		fm.redirect.value = escape(fm.redirect.value)
	}
	var queryString = virtualPath() + "/scripts/" + fm.action  + (fm.action.indexOf("?") !=-1 ? "" : "?")
	
	for(var i=0; i < fm.elements.length; i++){
		var element = fm.elements[i]
		element.value = trim(element.value)
		queryString = setURLParam(queryString, element.name, escape(element.value))
	}
	return queryString
 }

 function validateAdvancedSearch(formName) {
	formName = formName ? formName : "fm"
  	var fm = document.forms(formName);
  	var opNum = Number(fm.op.value) 
	fm.op.value = (opNum == searchesEnums.AdvancedSearch)  ?  searchesEnums.AdvancedSearchResult : ( (opNum == searchesEnums.SavedForm) ? searchesEnums.SavedFormResult : fm.op.value);
	fm.tabid.value = page.getTabObj().getSelection() 
	window.location.href = constructAdvancedSearyQuery(formName)
 }
 
 
 function SearchesEnums()
 {
 	var obj = new Object()
 	obj.None					= 0x00000000
 	obj.QuickSearch				= 0x00000001
	obj.AdvancedSearch			= 0x00000002
	obj.AdvancedSearchResult	= 0x00000004
	obj.QuickSearchResult		= 0x00000008
	obj.SavedForm				= 0x00000010
	obj.SavedFormResult			= 0x00000020
	obj.All						= 0x7FFFFFFF
	return obj
 }

 var searchesEnums = SearchesEnums() 
 
function getDatabaseValueforLookup(formName, uniqueSuffix)
{
	uniqueSuffix = uniqueSuffix || '';
	var databaseName = ""
	var fieldNamesArray = "p-database,pdatabase,database".split(",");
    var databaseField;

    for ( i=0; i < fieldNamesArray.length; i++ )
    {
        databaseField = document.forms[formName].elements[fieldNamesArray[i] + uniqueSuffix]
        if ( databaseField )
        {
            break;
        }
    }

	if (databaseField) 
	{
		var objType = databaseField.type
		if (objType == "select-one" || objType == "select-multiple" ) 
		{
			var selectedIndex = databaseField.selectedIndex
			if (selectedIndex > -1) 
			{
				databaseName = databaseField.options[selectedIndex].value
			}
		}
		else 
		{
			databaseName = databaseField.value
		}
	}	

	return databaseName
} 

function specialGroupPicker(formName, fieldID, pageContainment, pageID, uniqueSuffix)
{	
	uniqueSuffix = uniqueSuffix || '';
	var domObject = document.getElementById("lookupApplet")
	var scriptName = domObject.getAttribute("scriptName");
	scriptName = setURLParam(scriptName, "pagecontainment", pageContainment ? "1" : "0")
	if ( pageID )
	{
		scriptName = setURLParam(scriptName, "folderid", pageID)
	}
	var title = getLocalizedString('208|New Group')
	var aclType = 'G'
	
	var database = getDatabaseValueforLookup(formName, uniqueSuffix)
	window.specialPickerFormName = formName
	var url = virtualPath() + '/scripts/singlePickerDialog.aspx?title=' + escape(title) + '&aclType='+ escape(aclType) +'&scriptName='+ escape(scriptName) +'&database='+ escape(database) +'&minSecurityLevel=1&maxSecurityLevel=3&roleInfo=&showAccessInfo=&context=accessList&fieldID='+ escape(fieldID) +'&uniqueSuffix='+ escape(uniqueSuffix)
	var wnd = openWindow(url,'',400,300);
}

function doThemePreview()
{
	//this function assumes default form name to be fm
	var themeName = document.fm.theme.options[document.fm.theme.selectedIndex].value
	var url = virtualPath() + '/scripts/showTheme.aspx?name=' + escape(themeName) + '&redirect=' + escape(page._redirect)
	
	self.showModalDialog(url,'','dialogHeight:600px; dialogWidth:785px')
}					

function TrustedLoginStates()
{
	var obj = new Object();

	obj.None = 0;
	obj.Login = 1;
	obj.Auto = 2;
	obj.Logout = 4;

	return obj;
}

function TrustedLoginCookie()
{
	var obj = new Object();
	
	obj.cookieName = "trustedLogin";
	obj.getState = TrustedLoginCookie_getState;
	obj.setState = TrustedLoginCookie_setState;
	
	return obj;
}

function TrustedLoginCookie_getState()
{
	var state = Number(getCookie(this.cookieName));
	return state == Number.NaN ? 0 : state;
}

function TrustedLoginCookie_setState(newState)
{
	setCookie(this.cookieName, newState, 30);
}


function Stack() 
{
	this.stack = new Array();
	
	this.push = Stack_push;
	this.pop  = Stack_pop;
	this.peek =	Stack_peek;
	this.remove = Stack_remove;
	this.dispose = Stack_dispose;
}
function Stack_push(item) 
{
	this.stack.push(item);
}
function Stack_pop() 
{
	return this.stack.pop();
}
function Stack_peek() 
{
	if ( this.stack.length > 0 ) 
	{
		return this.stack[this.stack.length - 1];
	}
}
function Stack_remove(item)
{
	for(var i = 0; i < this.stack.length; ++i )
	{
		if (this.stack[i] === item)
		{
			this.stack.splice(i, 1);
		}
	}
}
function Stack_dispose()
{
	var item = null
	while ( item = this.pop() )
	{
		if ( item.dispose )
		{
			item.dispose();
		}
	}
}

function Queue() 
{
	this.id = getUniqueId()
	this.nextItem = this.id + '.nextItem'
	this.count = 0;
	this.firstItem = null;
	this.lastItem = null;
	
	this.enqueue = Queue_enqueue
	this.dequeue = Queue_dequeue
	this.dispose = Queue_dispose
}
function Queue_enqueue(item, inFront) 
{
	if ( this.firstItem == null || this.lastItem == null )
	{
		this.firstItem = this.lastItem = item;
	}
	else if ( inFront )
	{
		item[this.nextItem] = this.firstItem;
		this.firstItem = item;
	}
	else
	{
		this.lastItem[this.nextItem] = item;
		this.lastItem = item;
	}
	this.lastItem[this.nextItem] = null;
	this.count++
}
function Queue_dequeue() 
{
	var item;
	if ( this.firstItem != null )
	{
		item = this.firstItem;
		this.firstItem = this.firstItem[this.nextItem];
		item[this.nextItem] = null;
	}
	if ( item )
	{
		this.count--
	}
	else
	{
		this.firstItem = this.lastItem = null;
	}
	return item;
}
function Queue_dispose()
{
	var item = null
	while ( item = this.dequeue() )
	{
		if ( item.dispose )
		{
			item.dispose();
		}
	}
	
	this.firstItem = this.lastItem = null;
}


//================================================================
// start: functions for calendar view of calendar and task folders
//================================================================

// Parameters
// **********
// collabType: "task" or "event"
// divId: Id of the div element
// view: "day" or "week" or "month"
// date: "mm/dd/yyyy"
// rand: random number used for the div
// collabItemsXml: xml text corresponding to the tasks/events
// itemRootID:  the moniker for the folder --> used in the New Task link
function collabCalendarRefresh (collabType, itemRootID, divId, view, date, rand, collabItemsXml)
{
	var url = virtualPath() +  "/scripts/CalendarView.aspx";
	var obj = clientToAsp();
	var data = obj.getDataByPost(url,"xml=" + encodeURIComponent(collabItemsXml) + "&view=" + escape(view) + "&date=" + escape(date) + "&rand=" + escape(rand) + "&divId=" + escape(divId) + "&itemRootID=" + escape(itemRootID));
	var divTag = document.getElementById(divId);
	if (obj.hasError)
	{
		divTag.innerHTML = obj.errorMessage;
		return;
	}
	if (divTag)
	{
		divTag.innerHTML = data.xml;
		ccvResizeCalendar('collabCalTable'+rand);
	}
	else
	{
		alert ("Div not found");
	}
}

// shows popup calendar
// ccv = collab calendar view
function ccvShowCalendar(context,dtStr,rand)
{
	var	width =	230;
	var	height = 285;
	openWindow(virtualPath() + '/scripts/popupCalendar.aspx?callback=ccvCalendarCallback' + rand + '&amp;context=' + escape(context) + '&amp;today=' + escape(dtStr), 'Calendar'+rand, width, height, "");
}

// Resize calendar in case of month view
function ccvResizeCalendar(tableId)
{
	var tableElement = document.getElementById(tableId);
	if (tableElement == null)
	{
		// assuming table id is declared only in case of month view
		return;
	}
	var numRows = tableElement.rows.length - 1;
	var cellHeight = tableElement.rows(2).cells(0).clientWidth;
	for (i=1; i<=numRows; ++i)
	{
		for (j=0; j<tableElement.rows(i).cells.length; ++j)
		{
			document.getElementById(tableId).rows(i).cells(j).style.height = cellHeight;
		}
	}
}

//==============================================================
// end: functions for calendar view of calendar and task folders
//==============================================================

function writeCollabSearchPathAnchor(path)
{
	/*
	NOTE:  The values in path variable have already been encoded on the server side
	
	This function builds an anchor tag around the path value for tasks and events that originate in searches.
	The anchor will allow the user to go directly to the folder in which the collab item resides.
	
	path = workspace_name{}collab_folder_name{}moniker_for_folder
	
	aryPath[0] = Workspace name
	aryPath[1] = Collab folder name
	aryPath[2] = Moniker for folder
	*/
	
	if ( path.length > 0 )
	{
	    var aryPath = path.split(IMAN_DATA_DELIMITOR)
    	var anchorStr = "\\\\" + aryPath[0] + "\\" + aryPath[1]
    	var anchorHref = virtualPath() + "/scripts/home.aspx?nrtid=" + escape(aryPath[2])
    	writeAnchorStr('', anchorStr, anchorHref, '', '', '', '', '', '', 1398, aryPath[1] )
	}
	else
	{
	    //Sometimes you may not have access to the folder/workspace on which the collab item is located,
	    //so we cannot build a proper path on the server-side.  Therefore, we're just going to give a generic message. (NS, 7/19/06, 8.2.18)
	    document.write(getMessage(23));
	}
}

function openDialogWindow(url, newWindow)
{
	if (page.popupDialog || newWindow) 
	{
		openWindow(url, kWorkSiteDialog, 600, 500,'status=yes')
	}
	else
	{
		document.location.href = url;
	}
}

function performMiscDocOp(nrtid, op, closeWindow, prompt)
{
	//For unlock, we were making trip to server and redirecting back.  clientToAsp is sufficient for this command.
	//Since all we have to pass to MiscDocumentOps are the nrtid and the op, I also removed publishDoc() (in common.js) and moved the functionality here. (NS, 3/4/05)
	var applet = getAppletById("clientToAspApplet")
	var url;
	var doOp = true;	
	
	if(op == "freeze")
	{			 
		url = virtualPath() + "/scripts/GetDocInfo.aspx?nrtids=" + escape(nrtid) + "&onlyVersionInfo=true";
		if (applet)
		{
			var message = '\n';
			var response = applet.getData(url)		
			
			if(!applet.hasError && response != "")
			{
				eval(response +"")			
				if(documents.length > 0)						
				{
					for(var i = 0;i < documents.length;i++)
					{
						message += documents[i].number + "_" + documents[i].version	+ "\n"					
					}			
					//message = "You are about to declare the following document version(s) as record(s):"	+ message;
					//message = message + "This operation cannot be rolled back. Do you still want to proceed?";		
					
					message = getLocalizedMessage(1494, message)				
					if(!confirm(message)) return;
				}
				else
				{
					locAlert(parseAndLocalizeStr("{1495|Selected document(s) is already marked as a record.Please modify your selection.}"))					
					return;
				}
			}			
		}		
	}
	//#36270:  Prompt user for unlock operation just like DeskSite. (NS, 2/24/06, 8.1.77 (SP1))
	if ( op == "unlock" && prompt)
	{
	    doOp = confirm(getLocStrByLID(1519, "You will not be able to checkin the document after unlocking it.  Continue?"))
	}
	
	if ( doOp )
	{
	    url = virtualPath() + "/scripts/MiscDocumentOps.aspx?op=" + escape(op) + "&nrtid=" + escape(nrtid)
	    if ( applet )
	    {
		    var val = applet.getData(url)
		    if(!applet.hasError) 
		    {
			    if ( op == "freeze" )
			    {
				    locAlert(getLocStrByLID(1493, "Document(s) marked successfully."))
			    }			
		    }
		    else
		    {
			    return val;
		    }
		    if ( closeWindow == true )
		    {
			    closeDialogWindow()
		    }
	    }
    }
}

var contentTypeFromObjectType =
{
	imTypeDocument: btnEnums.Document,
	imTypeContent: btnEnums.Document,
	imTypeContents: btnEnums.Document,
	imTypeFavoritesFolder: btnEnums.Document,
	imTypeDocumentFolder: btnEnums.Document,
	imTypeDocuments: btnEnums.Document,
	imTypeDocumentSearchFolder: btnEnums.Document,
	imTypeWorkspaceSearchFolder: btnEnums.Workspace,
	imTypeWorkspaces: btnEnums.Workspace,
	imTypeMessageFolder: btnEnums.None,
	imTypeTaskFolder: btnEnums.None,
	imTypeEventFolder: btnEnums.None
}

function WorkSiteViewCache()
{
	var obj = new Object();
	
	obj.cache = new Object();
	obj.getView = WorkSiteViewCache_getView
	obj.getViewResult = WorkSiteViewCache_getViewResult
	obj.setView = WorkSiteViewCache_setView
	obj.hasView = WorkSiteViewCache_hasView
	
	return obj;
}

function WorkSiteViewCache_hasView(objectType)
{
	return typeof(contentTypeFromObjectType[objectType]) != 'undefined';
}

function WorkSiteViewCache_getView(id, objectType, viewName, callback)
{
	if ( this.hasView(objectType) )
	{
		var cacheID = viewName + '|' + contentTypeFromObjectType[objectType];
		
		if ( this.cache[cacheID] )
		{
			callback(this.cache[cacheID]);
		}
		else
		{
			var url = virtualPath() + '/scripts/PrefsViewOp.aspx?op=get-view&id=' + escape(id) + '&p-object-type=' + objectType + '&view-name=' + viewName + '&page=' + escape(page.id);
			
			var c2asp = getAppletById('clientToAspApplet');
			var it = this;
			c2asp.getData(url,	function(c2asp, response) 
								{ 
									it.getViewResult(c2asp, response, cacheID, callback); 
									c2asp = it = callback = null;
								} 
						);
		}
	}
	else // always call the callback
	{
		callback(null);
	}
}

function WorkSiteViewCache_getViewResult(c2asp, response, cacheID, callback)
{
	var viewData;
	if ( c2asp.hasError ) 
	{
		locAlert(c2asp.errorMessage);
	} 
	else if ( ! response ) 
	{
		locAlert(getLocStrByLID(37, 'Your session has expired. You must log in again.'));
	}
	else
	{
		eval(response);
		this.cache[cacheID] = viewData;
	}
	// always call the callback
	callback(viewData);
}

function WorkSiteViewCache_setView(id, objectType, viewName, viewHRef)
{
	if ( this.hasView(objectType) )
	{
		var cacheID = viewName + '|' + contentTypeFromObjectType[objectType];

		if ( this.cache[cacheID] )
		{
			this.cache[cacheID].selected = viewHRef;
		}

		var url = virtualPath() + '/scripts/PrefsViewOp.aspx?op=set-view&id=' + escape(id) + '&p-object-type=' + objectType + '&view-name=' + viewName + '&page=' + escape(page.id) + '&view-href=' + viewHRef;
		
		var c2asp = getAppletById('clientToAspApplet');
		c2asp.putData(url);
	}
}

// client-side returns positive value when behind UTC
// this must be glogal code ( SPS )
setCookie("clientTimeZone", -1 * new Date().getTimezoneOffset());

/////////////////////////////////////////
// following functions are for other portal intergration 
// one can implement these functions if they want to give mouse-over effect on description
function Description_OnMouseOver(srcName)
{	
}
function Description_OnMouseOut(srcName)
{	
}
function Description_OnMenu(objectType, nrtid, tmplt, parentNrtid, partID, srcName)
{
	return true;
}

function Description_OnAnchorClick(objectType, nrtid, id, partID, parentID)
{
	switch ( objectType )
	{
		case 'imTypeDocument':
			downloadEx(nrtid, page.documentOption, DocumentTarget.NewWindow);
			break;
			
		case 'imTypeFolder':
			openPortalLink(virtualPath() + '/scripts/Home.aspx?page=' + escape(page.id) + '&id=' + escape(id) + '&tabid=' + escape(page.getTabObj().getSelection()) + '&nrtid=' + escape(nrtid))
			break;
		
		case 'imTypeWorkspace':
			openPortalLink(virtualPath() + '/scripts/Home.aspx?page=' + escape(nrtid))
			break;
			
		case 'imTypeResource':
			if(window.event)
			{
				window.event.cancelBubble = true
			}

			switch ( parentID )
			{
				case "documents-views":
				case "pages-views":
					appendRedirectToURL("/scripts/View.aspx?id=" + escape(id) + "&redirect=");
					break;
			
				case "search-profiles":
				case "page-search-profiles":
				case "document-profiles":
				case "page-profiles":
					appendRedirectToURL("/scripts/FormEdit.aspx?updateResource=1&page="+escape(nrtid)+"&id="+escape(id)+"&redirect=");
					break;
			}
			break;
		case 'imTypeManage':
			if(window.event)
			{
				window.event.cancelBubble = true
			}
			appendRedirectToURL("/scripts/RoleEdit.aspx?op=edit&database=&xid="+escape(nrtid)+"&redirect=");
			break;
	}
	return false;	// this is very important
}

/////////////////////////////////////////////

//sets the minimum properties for ActiveX/applet --> will eventually be moved to common.js so CheckOut can use it too (NS, 3/1/05)
function setTransferCtrlUploadProps(transferCtrl)
{
	if (document.location.port)
	{
		transferCtrl.Port = parseInt(document.location.port)
	}	
	transferCtrl.SessionID      = document.cookie 
	transferCtrl.Server         = document.location.hostname 
	transferCtrl.Protocol       = document.location.protocol
}

function getTransferCtrl()
{
	return document.fm != null && document.fm.WebTransferCtrl != null ? document.fm.WebTransferCtrl : document.WebTransferCtrl;
}

function urlIsRelative(url)
{
	if ( url )
	{
		var tmpUrl = url.toLowerCase();
		return tmpUrl.indexOf('http://') != 0
			&& tmpUrl.indexOf('https://') != 0
			&& tmpUrl.indexOf('file://') != 0
			&& tmpUrl.indexOf('ftp://') != 0
			&& tmpUrl.charAt(0) != '/'
			&& tmpUrl.charAt(0) != '\\'
	}
}

// This function checks for a live session by making a call to an aspx page.
// We can make a call to any aspx page to check for live session but since
// login.aspx has minimal code , we chose this aspx page to check for live session.
function isSessionAlive()
{
    var applet = getAppletById("ClientToAspApplet");
	var response = applet.getData(virtualPath()+ "/scripts/login.aspx");
	
	if (applet.hasError) 
	{
		locAlert(applet.errorMessage)
		return false;
	}
	else if(!response)
	{
		alert(parseAndLocalizeStr("{37|Your session has expired.  You must log in again.}"))
		return false;
	}
	else
	{
	    return true;
	}
}

function checkIsPortablePath(path)
{
	var pathArr = path.split("\\")
	
	for(var j = 1 ;j < pathArr.length; j++)
	{												
		if(pathArr[j].toLowerCase() == "nrportbl")
		{
			return true								
		}
	}
	return false
}

//******************************************//
//*****Import/CheckIn Related Functions******
//******************************************//

function setCheckinMode(mode) 
{
	var controls = document.fm.mode
	if (controls.length > 1) 
	{
		for (var i=0; i<controls.length; i++) 
		{
			if (controls[i].value == mode) 
			{
				controls[i].checked = true
				return true;
			}
		}
	}
	else if (controls.value == mode)
	{
		controls.checked = true
		return true
	}
	return false
}

function GetCheckinMode() 
{
	var controls = document.fm.mode
	if (controls.length > 1) 
	{
		for (var i=0; i<controls.length; i++) 
		{
			if (controls[i].checked) 
			{
				return controls[i].value
			}
		}
	}
	else 
	{
		return controls.value;
	}
}

function ShowOleLinkingPanel(transferCtrl)
{	
	var checkForOleLinks = document.fm.checkForOleLinks && document.fm.checkForOleLinks.checked
	var selectedMode = GetCheckinMode();
	
	if (selectedMode != 'undo')
	{							
		if (oleLinks.isOleLinkPanel)
		{ 							
			oleLinks.addLinksFilesForUpload()								
			if(oleLinks.isCheckIn)
			{				
				//Delete all read only files that were downloaded
				//at the time of checkOut.This is only in case of OleLinking.																				
				oleLinks.deleteReadOnlyFiles()		
			}		
		}	
		else if(checkForOleLinks)
		{																			
			oleLinks.checkForNewORCheckedOutLinks()										
			if(oleLinks.hasNewLinks || oleLinks.hasCheckedOutLinks)
			{									
				if(!oleLinks.isCheckIn) oleLinks.isCheckIn = true;
				oleLinks.showOleLinkPanel()
				return true																		
			}			
		}			
		if(document.fm.multiop.value != 1 && !oleLinks.isCheckIn && !oleLinks.isOleLinkPanel)
		{
			//In case of multi import, files are added to the transfer control when we hit the "+" button.
			//So we donot have to add them here again.TT 36556 [H.K]\				
			transferCtrl.AddFile(validatePath(transferCtrl.BrowsePath))					
		}
	}
	
	return false
}

//If checkin path does not has the file name,
//this function appends the file name to it because activex
//always looks for the file name in the path.TT 39194 [H.K.]
function validatePath(path)
{    
    //if(path.indexOf(documents[0].defaultName) == -1 && !checkIsPortablePath(path))
    var fileExtensionLength = path.lastIndexOf(".") == -1 ? 0 : path.substring(path.lastIndexOf(".") + 1 ,path.length).length;
    
    if(fileExtensionLength < 2  && !checkIsPortablePath(path))    
	{        
	    return path + "\\" + documents[0].defaultName
	}
	return path;
}

