//////////////////////////////////////////////////////////////////////////////
//
// Common.js
//
// Copyright (c) 2000 by iManage, Inc.  All Rights Reserved
//
//////////////////////////////////////////////////////////////////////////////
//
// DESCRIPTION:
// 	Various client-side utility functions
//

function iManageEnums() {
	// Access rights
	this.nrRightNone = 0
	this.nrRightRead = 1
	this.nrRightReadWrite = 2
	this.nrRightAll = 3

	// Page Access rights	
	this.nrNoAccess = this.nrRightNone
	this.nrReviewerAccess = this.nrRightRead
	this.nrContributorAccess = this.nrRightReadWrite
	this.nrEditorAccess = this.nrRightAll
}

var iEnums = new iManageEnums()

// Suite options
var kSuiteDocFolder = 1
var kSuiteConnector = 2
var kSuiteColaboration = 4
var kSuiteEWork = 8 
var kSuiteAutonomy = 16

// Page types
var kSystemPageType = "system"
var kTempPageType = "temp"
var kAdminPageType = "admin"
var kStartPageType = "start"
var kWorkPageType = "work"
var kPrefsPageType = "preferences"
var kTemplatePageType = "template"
var kSidebarPageType = "sidebar"
var kConnectorPageType = "connector"

window.onloadAdvise = function(funcObj) {
	if ( window.onloadListeners ) {
		window.onloadListeners[window.onloadListeners.length] = funcObj
	} else {
		window.onloadListeners = new Array(funcObj)
	}
}

window.onload = function() {
	if ( window.onloadListeners ) {
		for(var i = 0; i < 	window.onloadListeners.length; ++i ) {
			var listener = window.onloadListeners[i]
			if ( typeof(listener) == "function" ) {
				listener()
			} else if ( typeof(listener) == "string" ) {
				eval(listener)
			}
		}
	}
}

/*
// performance testing code
var date1 = new Date()
function myfunction () {
	alert((new Date() - date1))
}
window.onloadAdvise("loadApplet()")
*/

	function loadApplet() {
		var applet = document.applets["shortcutsApplet"]
		if (applet) {
			applet.setOnclickHandler("onAppletSelectCallback", this)
		}	
	}
					
	function onAppletSelectCallback(a, b, c) {
		var applet = document.applets["shortcutsApplet"]
				
		if (applet) {
			var sel = applet.getSelection()
			var href = sel.getAttribute("href")+ ""
			if (href) {
				if (sel.getAttribute("istab") == "1") {
					var id = sel.getAttribute("id")
					if(document.readyState == "complete" && window.page.type != kTempPageType){
						document.renderTabs(id,true)
					} else {
						document.location = virtualRoot()+"/scripts/"+href
					}
				} else {
					var target = sel.getAttribute("target") + ""
					if (!target || target=="mainframe" || target=="_self") {
						document.location = virtualRoot()+"/scripts/"+href
					}else {
						window.open(href)
					}	
				}
			}	
		}
	}

window.onloadAdvise("loadApplet()")

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) {
				item.focus()
				return
			}
		}
		if (firstObj) {
			firstObj.focus()
		}
	}
}
///////////////////////////////////////////////////////////////////////////////////
// standard API for netscape
///////////////////////////////////////////////////////////////////////////////////

// BrowserInfo object
function Browser() {
/*
	Properties:
		isIE:		is Internet Explorer;
		isNS6:	is Netscape 6 and above;
		isNS4:  is Netscape 4.x;
		isNav:	is Netscape browser;
		isMac:	is Macintosh machine;
		isWin:  is Windows machine;
		isIE5:  is Internet Explorer 5.0*;
*/	
	 this.isIE	= (document.all)? true : false
	 this.isNS6 = (document.implementation && document.implementation.createDocument) ? true : false
	 this.isNS4 = (navigator.userAgent.toUpperCase().indexOf("MOZILLA/4.79") > -1)
	 this.isNav = this.isNS6 || this.isNS4
	 this.isMac = (navigator.userAgent.indexOf("Macintosh") > -1)
	 this.isWin = !this.isMac	 
	 this.isIE5 = (navigator.userAgent.indexOf("MSIE 5.0") > -1)
}

g_browser = new Browser()

var kComplete = 'complete'
var kInComplete = 'incomplete'
var locationHRef = window.location.href

if ( g_browser.isNav ) {
	document.readyState = kInComplete
} 

if ( g_browser.isNS4 ) {
	document.body = new Object()
	document.body.style = new Object()
	window.onResize = new Function("window.location.reload(false)")
}

function initDocument() {
	if ( g_browser.isNav ) {
		document.readyState = kComplete
	} 
}
window.onloadAdvise(initDocument)

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" ){
		if ( g_browser.isNS4 ) {
			theObj = window.document.ids[obj]
		} else {
			theObj = window.document.getElementById(obj).style
		}
	} else {
		theObj = obj
	}
	return theObj
}

function addOptionItem(selObj,val,text) {
	if (!val) val = ""
	if (!text) text = val
	selObj.options[selObj.options.length] = new Option(text,val)
	selObj.selectedIndex = selObj.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

function getCookie(name, item) {
	var arg = name.toUpperCase() + "="
	var alen = arg.length
	var clen = document.cookie.length
	var i = 0
	while (i < clen) {
		var j = i + alen
		if (document.cookie.substring(i, j).toUpperCase() == arg) {
			var cEnd = document.cookie.indexOf(";",j)
			if (cEnd == -1) {
				cEnd = document.cookie.length
			}
			var cookie = document.cookie.substring(j, cEnd)
			if (item != null) { // Find item
				arg = item.toUpperCase() + "="
				alen = arg.length
				clen = cookie.length
				i = 0
				while (i < clen) {
					j = i + alen
					if (cookie.substring(i, j).toUpperCase() == arg) {
						cEnd = cookie.indexOf("&",j)
						if (cEnd == -1) {
							cEnd = cookie.length
						}
						cookie = cookie.substring(j, cEnd)
						return unescape(cookie)
					} else {
						i = cookie.indexOf("&", i) + 1
						if (i == 0) return ""
					}
				}	
			}
			return unescape(cookie)
		} else {
			i = document.cookie.indexOf(" ", i) + 1
			if (i == 0) break;
		}
	}
	return ""
}

function setCookie(name, value, expireDays,path) {
	var pair = name + "=" + value
	if (expireDays) {
		var expires = new Date()
		var expTime = expires.getTime() + (expireDays * 86400000)
		expires.setTime(expTime)
		pair += "; expires=" + expires.toGMTString()
	}
	if (path) {
		pair += "; path=" + path
	} else {
		var docpath= document.location.pathname
		var position = docpath.indexOf("/",1)
		if (position >0) {
			docpath=docpath.substring(0,position)
			pair += "; path=" + docpath
		}	
	}
	document.cookie = pair
}
	
function getParam(name) {
	var query = window.location.search
	var arg = name + "="
	var alen = arg.length
	var qlen = query.length
	var i = query.indexOf("?") + 1
	while (i < qlen) {
		var j = i + alen
		if (query.substring(i, j) == arg) {
			var cEnd = query.indexOf("&",j)
			if (cEnd == -1) {
				cEnd = query.length
			}
			return unescape(query.substring(j, cEnd))
		} else {
			i = query.indexOf("&", i) + 1
			if (i == 0) break;
		}
	}
	return ""
}

function javaString(str) {
	// This add's backslashes to any single || double quotes

	if ( str ) {
		str = str.replace(/\\/g, "\\\\")
		str = str.replace(/\'/g, "\\\'")
		str = str.replace(/\"/g, "\\\"")
		return str
	} else {
		return ''
	}
}

function htmlString(str) {
	// This HTML escapes the string

	if ( str ) {
		str = str.replace(/\'/g, "&#39;")
		str = str.replace(/\"/g, "&quot;")
		str = str.replace(/</g, "&lt;")
		str = str.replace(/>/g, "&gt;")
		return str
	} else {
		return ''
	}
}

function htmlDeString(str) {
	// This HTML unescapes the string

	if ( str ) {
		str = str.replace(/&#39;/gi, "\'")
		str = str.replace(/&quot;/gi, "\"")
		str = str.replace(/&lt;/gi, "<")
		str = str.replace(/&gt;/gi, ">")
		str = str.replace(/&amp;/gi, "&")
		return str
	} else {
		return ''
	}
}

function rTrim(str) 
{ 
	return str.replace(/\s+$/, "")
} 

function lTrim(str) 
{
	return str.replace(/\s*/, "") 
} 

function trim(str) 
{
	return str.replace(/\s*(.*\S)\s*$/, "$1") 
} 

function getURLParam(url, param) {
	// This extracts a named param
	
	var value
	
	var index = url.indexOf(param + "=")
	if (index >= 0) {
		var start
		if (index == 0) {
			start = param.length + 1
		} else {
			var priorChar = url.charAt(index-1)
			if (priorChar == '&' || priorChar == '?') {
				start = index + param.length + 1
			}
		}
		
		if (start) {
			var end = url.indexOf("&", start)
			if (end < 0) {
				end = url.length
			}
			value = url.slice(start, end)
		}
	}
	
	return value
}

function setURLParam(url, param, value) {
	// This sets a named param
	
	var index = url.indexOf("?" + param + "=")
	if (index < 0) {
		index = url.indexOf("&" + param + "=")
			}

	if (index > 0) {
		var start = index + 1
			var end = url.indexOf("&", start)
			if (end < 0) {
				end = url.length
			}
			value = url.slice(0, start) + param + "=" + value + url.slice(end)
	} else {
		value = appendURLParam(url, param, value)
	}
	
	return value
}

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 appendURLParam(url, param, value) {
	if (url.indexOf("?") < 0) {
		url = url + "?"
		} else {
		url = url + "&"
	}
	url += param + "=" + value
	
	return url
}

function expandLinks(itemID, parent, id, action) {
	//alert('expandLinks("' + itemID + '", "' + parent + '", "' + id + '", "' + action + '")')
	
	var url
	var row = document.getElementById(id)
	if (row) {
		var display
		var btnSrc
		var expand
		if (row.style.display == "none") {
			// Expand
			expand = "1"
			display = "inline"
			btnSrc = "../images/Minus.gif"
		} else {
			// Collapse
			expand = "0"
			display = "none"
			btnSrc = "../images/Plus.gif"
		}
		var xoffset = document.body.scrollLeft // TODO: Use window.pageXOffset for Nav
		var yoffset = document.body.scrollTop

		if (!action || (action == "refresh")) {	
			var refresh = false
			if (action && (action == "refresh") && (expand == "1")) {
				var populated = row.getAttribute("populated")
				if (!populated) {
					// force a refresh to populate the expanded node
					setCookie(window.name + "Offset", xoffset + "," + yoffset, 0)
					refresh = true
				}
			}
			url = virtualRoot() + "/scripts/Expand.asp?page=" + page.id + "&id=" + itemID + "&parent=" + parent + "&node=" + id + "&expand=" + expand

			// Update display
			if (refresh) {
				url += "&redirect=" + escape(window.page.getRedirect())
				window.location = url
			} else {
				// Notify server
				var applet = document.applets['clientToAspApplet']
				applet.putData(url)
				row.style.display = display
				var btn = document.getElementById(id+"Btn")
				if (btn) {
					btn.src = btnSrc
				}
			}
		} else {
			setCookie(window.name + "Offset", xoffset + "," + yoffset, 0)
			url = action + "&page=" + page.id + "&id=" + itemID + "&node=" + id + "&expand=" + expand
			window.location = url
		}
	}
}

function sortColumn(id, column, element, view, description) {
	if (!description) {
		description = ""
	}
	setCookie(window.name + "Offset", document.body.scrollLeft + "," + document.body.scrollTop, 0)
	var redirect = escape(window.page.getRedirect())
	var url = "../scripts/Sort.asp?page=" + page.id + "&id=" + id + "&column=" + column + "&element=" + element + "&view=" + view + "&description=" + description + "&redirect=" + redirect
	window.location = url
}

function doLookup(attributeID, parentName, title, formName, fieldName, dependents, isSearch,callBackFn) {
		var form = document.forms[formName]
		var parentValue = ""
		title = escape(parseAndLocalizeStr(title))
		
		if (form) {		    
			var parentValue = ""
			var parent = document.forms[formName].elements["p-" + parentName]

			//var parent = document.getElementById("p-" + parentName)
			if (parent) {			
				if (parent.type == "select-one") {
					parentValue = parent.options[parent.selectedIndex].value
				} else {
					parentValue = parent.value
				}
				//+ Janice added on 11/09/01 to escape special characters
				parentValue = escape(parentValue)				
			}
			// Get database name, if any
			var databaseName = ""
			var databaseField = document.forms[formName].elements["p-databases"]			
			if(databaseField){			    
				var selected = ""
				//there is no good way to know if the selection is single or multiple, and hence I need to iterate thru the
				//options collections.
				var bMultiple = false
				for(var j=0; j<databaseField.length ;j++) {
						selected = databaseField.options[j].selected
						if (!bMultiple){
							if (selected){
								bMultiple = true
								databaseName = databaseField.options[j].value
								//alert(databaseName)
							}
						}else{
							if(selected){
								databaseName = ""
								break;
							}
						}
				}
			}else{
				
				//databaseField = document.getElementById("p-database")
			    databaseField = document.forms[formName].elements["p-database"]
			    if(!databaseField) {
					databaseField = document.forms[formName].elements["pdatabase"]							    
			    }			
				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 = ""
						}
					}else {
						databaseName = databaseField.value
					}
				}
			    //quick fix for passing databaseName to lookup for docprofile
			    // in case profile also has field called "p-database" :SJ
			    if(!databaseName) {
					databaseField = document.forms[formName].elements["pdatabase"]
					if (databaseField) {							    
						databaseName = databaseField.value
					}	
			    }			
				
			}
			
			databaseName = databaseName.indexOf(",") >=0 ? "" : databaseName
			var params = formName + "," + fieldName + "," + dependents
			isSearch = isSearch ? isSearch : ""
			callBackFn = callBackFn ? callBackFn: "lookupCallback"
			//var lookupApp = document.getElementById("lookupApplet")
			var lookupApp =document.applets["lookupApplet"]		
			title = title.replace(/%20/g," ")
			lookupApp.setLookupType(attributeID, this,callBackFn , String(parentValue), title, params, databaseName, isSearch)
		}
}
			
function lookupCallback(alias, description, params) {
	var paramArray = params.split(",")
	var formName = paramArray[0]
	var fieldName = paramArray[1]
	var dependents = paramArray[2]
	var form = document.forms[formName]
	if (form) {
	    document.forms[formName].elements["p-" + fieldName].value = alias	
	    
		//document.getElementById("p-" + fieldName).value = alias
		//var span = document.forms[formName].elements["s-" + fieldName]
		var span 
		if (g_browser.isIE) {
			 span = document.getElementById("s-" + fieldName)
			if (span) {
				span.innerText = description
			}
		}	
		var descField = document.forms[formName].elements[fieldName + "Desc"]
		if (descField) {
			descField.value = description
		}
		if (dependents) {
			// Clear dependents
			var dependent =document.forms[formName].elements["p-" + dependents]
			if (dependent) {
				if (dependent.type == "select-one") {
					dependent.options.length = 0
					dependent.setAttribute("populated", "0")
				} else {
					dependent.value = ""
				}
				if (g_browser.isIE) {
					span = document.getElementById("s-" + dependents)
					if (span) {
						span.innerText = ""
					}
				}	
			}
		}
		if ((form.action == "DocProfile.asp") && (fieldName == "class" || fieldName == "subclass")) {
			updateRequiredFields(formName)
		}
	}
}  
 
function onSelectChange(formName, name, dependents, updateRequired) {
	var form = document.forms(formName)
	if (form) {
		var select = document.getElementById("p-" + name)
		if (select) {
			var title
			var selectedIndex = select.selectedIndex
			if (selectedIndex >= 0) {
				var option = select.options[selectedIndex]
				var title = option.getAttribute("title")
			}
			if (!title) {
				title = ""
			}
			var span = document.getElementById("s-" + name)
			if (span) {
				span.innerText = title
			}
			if (dependents) {
				var dependent = document.getElementById("p-" + dependents)
				if (dependent) {
					if (dependent.type == "select-one") {
						dependent.options.length = 0
						dependent.setAttribute("populated", "0")
					} else {
						dependent.value = ""
					}
					span = document.getElementById("s-" + dependents)
					if (span) {
						span.innerText = ""
					}
				}
			}
			if (updateRequired && (name == "class" || name == "subclass")) {
				updateRequiredFields(formName)
			}
		}
	}
}

function updateRequiredFields(formName) {
	var form = document.forms[formName]
	if (form) {
		var className = form.elements["p-class"] ? form.elements["p-class"].value : ""
		var subclassName = form.elements["p-subclass"] ? form.elements["p-subclass"].value : ""
		var databaseName = form.elements["p-database"] ? form.elements["p-database"].value : ""
		var url = virtualRoot() + "/scripts/GetRequired.asp?class=" + escape(className) + "&subclass=" + escape(subclassName) + "&database=" + escape(databaseName)
		var applet = document.applets["clientToAspApplet"]
		var data = applet.getData(url)
		data = data ? String(data) : ""
		if (data.substring(0, 6) == "Error:") {
			locAlert(data)
			return
		}
		for (ii=0; ii < form.elements.length; ii++) {
			var element = form.elements[ii]
			var name = element.name
			if (name.substring(0, 2) == "p-") {
				name = name.slice(2)
				var img = document.images[name + "-img"]
				var pos = data.search("," + name + ",")
				if (pos >= 0) {
					if (img) {
						img.src = virtualRoot() + "/images/RequiredInd.gif"
						img.title = img.alt = getLocStrByLID(81,"Required Field")
					}
					if ( element.setAttribute ) {
						element.setAttribute("required", "1")
					}
				} else {
					if (img) {
						img.src = virtualRoot() + "/images/BlankIcon.gif"
						img.title = img.alt = ""
					}
					if ( element.setAttribute ) {
					
						element.setAttribute("required", "0")
					}
				}
			}
		}
	}
}

function validateProfileFields(formName) {
	var valid = true
	var form = document.forms[formName]
	if (form) {
		for (ii=0; ii < form.elements.length && valid; ii++) {
			var element = form.elements[ii]			
			if (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."))
					valid = false
				}
			}
		}
	}
	
	return valid
}

function validateSearchFields(formName) {
	var valid = true
	var form = document.forms[formName]
	if (form) {
		var commentQuery = getFieldValue(form, "p-comment")
		var fullTextQuery = getFieldValue(form, "p-full-text")
		if (commentQuery.length > 0 && fullTextQuery.length > 0) {
			locAlert(getLocalizedString("883|Searching on both the comments and full text cannot be done simultaneously."))
			valid = false
		}
	}
	
	return valid
}

function clearSearch(formName) {
	var form = document.forms(formName)
	if (form) {
		for (ii=0; ii < form.elements.length; ii++) {
			var element = form.elements[ii]
			if ((element.name.substring(0,2) == "p-") && !element.readOnly) {
				var fieldName = element.name.substring(2, element.name.length)
				if (element.tagName == "INPUT") {
					if (element.type == "text") {
						element.value = ""
					} else if (element.type == "hidden") {
						var dateSel = form.elements("sel-p-" + fieldName)
						if (dateSel) {
							dateSel.selectedIndex = 0
							dateSel.onchange()
						}
					}
				} else if (element.tagName == "SELECT") {
					element.selectedIndex = -1
				} else if (element.tagName == "TEXTAREA") {
					element.value == ""
				}
				var span = document.getElementById("s-" + fieldName)
				if (span) {
					span.innerText = ""
				}
				var descField = form.elements(fieldName + "Desc")
				if (descField) {
					descField.value = ""
				}
			}
		}
	}
}

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 onSelectFocus(formName, name, attributeID, parentName, isSearch) {
	// alert("onSelectFocus(name=" + name + ", attributeID=" + attributeID + ", parent=" + parent + ")")
	var form = document.forms(formName)
	if (form) {
		var select = form.elements("p-" + name)
		if (select) {
			var populated = select.getAttribute("populated")
			if (!populated || populated == "0") {
				var selectedValue
				var selectedIndex = select.selectedIndex
				if (selectedIndex >= 0) {
					selectedValue = select.options[selectedIndex].value
				}
				select.options.length = 0
				// Get options
				var parentValue = ""
				if (parentName) {
					var parent = form.elements("p-" + parentName)
					if (parent) {
						if (parent.type == "select-one") {
							parentValue = parent.options[parent.selectedIndex].value
						} else {
							parentValue = parent.value
						}
					}
				}
				// Get database name, if any
				var databaseName = ""
				var databaseField = form.elements("p-database")
				if (databaseField) {
					databaseName = databaseField.value
				}
				isSearch = isSearch ? isSearch : ""
				var applet = document.applets["clientToAspApplet"]
				var url = virtualRoot() + "/scripts/GetLookup.asp?lookupType=" + attributeID + "&searchString=&parentString=" + parentValue + "&database=" + databaseName + "&isSearch=" + isSearch
				var data = applet.getData(url)
				populateSelect(select, data, selectedValue)
			}
		}
	}
}
			
function populateSelect(select, data, selectedValue) {
	//alert("populateSelect")
	if (data.substring(0, 6) == "Error:") {
		locAlert(data)
		return
	}
	var dataArray = data.split("\n")
	dataArray.sort()
	select.options.length = 0
	var count = 0
	var option = new Option("", "")
	option.setAttribute("title", "")
	select.options[count++] = option
	for (var ii = 0; ii < dataArray.length; ii++) {
		var dataPair = dataArray[ii]
		var end = dataPair.indexOf(",")
		if (end > 0) {
			var alias = dataPair.substring(0, end)
			var description = dataPair.substring(end + 1, dataPair.length)
			// alert("alias = " + alias + ", description = " + description)
			option = new Option(alias, alias)
			option.setAttribute("title", description)
			select.options[count] = option
			if ((selectedValue != null) && (selectedValue == alias)) {
				select.options[count].selected = true
				selectedValue = null
			}
			count++
		}
	}
	select.setAttribute("populated", "1")
}

function onChangeValidated(name) {
	var span = document.getElementById("s-" + name)
	if (span) {
		span.innerText = ""
	}
}

var selectedNodeID
var selectedNRTID

function selectNode(id, nrtid) {
	alert("selectNode('" + id + "', '" + nrtid + "')")

	var span = document.getElementById(id + "Span")
	if (span) {
		if (selectedNodeID) {
			oldSpan = document.getElementById(selectedNodeID + "Span")
			if (oldSpan) {
				oldSpan.style.backgroundColor = "white"
				oldSpan.style.color = "black"
			}
		}
		span.style.backgroundColor = "navy"
		span.style.color = "white"
		selectedNodeID = id
		selectedNRTID = nrtid
	}
}

function centralize(Sr, Pl, Pw, Dw) {
	return Math.max(0, Math.min(Sr - Dw, (Math.max(0, Pl) + Math.min(Sr, Pl + Pw) - Dw) / 2))
}

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")

	sFeatures = getWindowCenterOptions(nWidth, nHeight) + (sFeatures ? "," : "") + sFeatures
	return window.open(sURL, sName, sFeatures)
}

function getWindowCenterOptions(nWidth, nHeight) {
	var sFeatures
	var nLeft, nTop
	
	if ( g_browser.isNS4 ) {
		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(nrtid) 
{	
  if( g_browser.isIE && document.WebTransferCtrl ){
	var destURL = document.location.pathname 
	var ctrl = document.WebTransferCtrl
	var temp = destURL.slice(0, destURL.lastIndexOf("/"))
	ctrl.DestinationURL = temp.slice(0, temp.lastIndexOf("/")+1) + "scripts/ViewDoc.asp"
	
	ctrl.SessionID =  document.cookie
	ctrl.NrtID = nrtid
	ctrl.Server = document.location.hostname 
	if (document.location.port) {
		ctrl.Port = parseInt(document.location.port)
	}
	ctrl.Protocol = document.location.protocol
	ctrl.Download() 
  }else		
	 startDownload("TransferClient","../scripts/ViewDoc.asp?nrtid=" + nrtid + "&command=ok", "", "View");      	 
 	
	} 

function downloadEx(nrtid, script, action, path, open, duedate, comments) 
{
  if( g_browser.isIE && document.WebTransferCtrl ){
		script = script ? script : "ViewDoc.asp"
		action = action ? action : 3
		open = open ? open : 1
		duedate = duedate ? duedate : ""
		comments = comments ? comments : ""
		path = path ? path : ""
		var url = "../scripts/ProgressBar.asp?nrtid=" + nrtid + "&script=" + script + "&action=" + action + "&open=" + open + "&duedate=" + duedate + "&comments=" + comments + "&path=" + path
		var wnd = openWindow(url, "Progressbar", 400, 100, "")
	}else		{
		startDownload("TransferClient","../scripts/ViewDoc.asp?nrtid=" + nrtid + "&command=ok", "", "view");      	 
	}
}

function writeItemHeader(id, title, imgSrc, expand, menu) {
	var expandLink, zoomLink, closeLink
	var style, btnImg,locString
	imgSrc = imgSrc ? imgSrc : "pixel.gif"
	title = checkLength(title, 40)
	
	if ( expand == "0" ) {
		style = (g_browser.isIE ? 'display:none;':'')+'populated:0;originalid:' + id 
		btnImg = 'titleCornerCollapsed.gif'
		locString = '{958|Collapse}'
	} else {
		style = (g_browser.isIE ? 'display:block;':'')+'populated:1;originalid:' + id 
		btnImg = 'titleCornerExpanded.gif'
		locString = '{956|Expand}'
	}
			
	var expandId = id.replace(/-/gi, "_")	// NS4 stuff
	if ( page.zoomed == "0" ) {
		expandLink = '<a  class="item-title-bar" href="javascript:toggleExpand(\'' + expandId + '\')" title="'+parseAndLocalizeStr(locString)+'">'
		zoomLink = '<a  class="item-title-bar" href="' + appendURLParam(page.getRedirect(), "id", id) + '">'
		closeLink = '</a>'
	} else { 
		expandLink = zoomLink = closeLink = ''
	}
	
	html = '\n' +
			'<table width="100%" border="0" cellspacing="0" cellpadding="0">\n' +
				'<tr> \n' +
					'<td class="item-title-bar" nowrap width="1%">' + expandLink +'<img name="grouping_' +  expandId + '" src="../images/'+btnImg+'" width="18" height="17"  border="0" alt="'+parseAndLocalizeStr(locString)+'">' + closeLink + '</td>\n' +
								'<td class="item-title-bar" width="1%"><img src="../images/' + imgSrc + '" width="16" height="16" alt="" border="0"></td>\n' +
								'<td class="item-title-bar" width="1%"><img src="../images/pixel.gif" width="2" height="1" alt="" border="0"></td>\n' +
								'<td class="item-title-bar" nowrap>'	 
									+ zoomLink 
										+ title
									+ closeLink + '\n' +
								'</td>\n' +
				'<td class="item-title-bar" nowrap align="right">\n' +
					 ( menu ? writeActionMenus("{523|Action}", "big", menu,true) : "&nbsp;") + '\n' +
					'</td>\n' +
				'</tr>\n' +
				'<tr>\n' +
					'<td class="item-title-line" colspan="5"><img src="../images/pixel.gif" width="1" height="1" alt="" border="0"></td>\n' +
				'</tr>\n' +
		'</table>\n\n' +
		'<div id="' + expandId + '" style="' + style + '">'
	document.write(html)
}
function writeTreeHeader(title, replyLink) {
	var	style = 'populated:1;originalid:'
	var swoop = ''
	var	btnImg = 'titleCornerExpanded.gif'
			title = parseAndLocalizeStr(title)
			title = checkLength(title,40)
	if (!replyLink) {
		 replyLink = ""
		 swoop = ""
	}else {
		 swoop = '<img src="../images/titleSwoop.gif" width="35" height="18" alt="" border="0">'
		 replyLink ='<img src="../images/pixel.gif" width="1" height="1" alt="" border="0">' + replyLink
	}
	html = '\n' +
		  '<table width="100%" border="0" cellspacing="0" cellpadding="0">\n' +
			'<tr> \n' +
				'<td class="item-title-bar" nowrap >\n' +
					'<table border="0" cellspacing="0" cellpadding="0">\n' +
						'<tr>\n' +
							'<td class="item-title-bar"><img src="../images/titleCornerExpanded.gif" alt="titleCornerExpanded.gif"></td>\n' +
							'<td class="item-title-bar">' + title + '</td>\n' +
						'</tr>\n' +
					'</table>\n' +
				'</td>\n' +
				'<td class="item-title-bar" nowrap align="right"> \n' +
				  '<table border="0" cellspacing="0" cellpadding="0">\n' +
				    '<tr> \n' +
				      '<td class="item-title-bar" nowrap>' + swoop + '</td>\n' +
				      '<td class="item-title-menu">' + replyLink +'</td>\n' +
				    '</tr>\n' +
				  '</table></td>\n' +
		    '</tr> \n' +
			'<tr> \n' +
				'<td class="item-title-menu" colspan="2"><img src="../images/pixel.gif" width="1" height="1" alt="" border="0"></td>\n' +
			'</tr>\n' +
		 '</table>'
	document.write(html)					
}

function writeItemFooter() {
	document.write('</div>\n<br>\n')
}

function writeMenuButton(xxx, menuFn) {
	document.write('<td align="right" width="1%">' + writeActionMenus("{523|Action}","small", menuFn)  + '</td>')
}

function toggleExpand(id) {
	var refresh = false
	var divStyle = getStyleObject(id)

	var populated = (divStyle.populated == '1')
	var originalID = divStyle.originalid
	var url = virtualRoot() + "/scripts/" + "Expand.asp?page=" + page.id + "&id=" + originalID + "&expand=" + (populated ? "0" : "1")
	var altString = ""	
	if ( g_browser.isNS4 ) {
		refresh = true
	} else {
		var imgSrc 
		if ( populated ) {
			if ( divStyle.display == "none" ) {
				divStyle.display = "block"
				imgSrc = "titleCornerExpanded.gif"
				url = setURLParam(url, "expand", "1")
				altString="{956|Expand}"
			} else {
				divStyle.display = "none"
				imgSrc = "titleCornerCollapsed.gif"
				url = setURLParam(url, "expand", "0")
				altString="{958|Collapse}"
			}
		} else {
			refresh = true
		}
	}
		
	if ( refresh ) {
		window.location.href = setURLParam(url, "redirect", escape(page.getRedirect()))
	} else {
		// Notify the server
		var applet = document.applets['clientToAspApplet']
		var data = applet.putData(url)
				
		// change the image
		var groupingImg = document.images["grouping_" + id ]
		if ( groupingImg ) {
			groupingImg.src = "../images/" + imgSrc
			groupingImg.alt=parseAndLocalizeStr(altString)
		}
	}
}

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")
		downloadEx(nrtid)
	} else {
		// url = "../scripts/" + url
		//Fix for 9120:  Open attachments in current window, not new window (NS, 1/27/02)
		location.href = virtualRoot() + "/scripts/" + url
	}
}

function selectThumbnail(callbackFnName) {
	// callback function must be of the form:
	//		function thumbNailCallback(wnd, cmd, title, nrtid)
	//			cmd		"ok" | "cancel"
	//			title	Image title
	//			nrtid	iManage moniker id for the thumbnail document

	var title = escape(getLocalizedString("1050|Select a page icon"))
	var url = "../scripts/PageIconDlg.asp?title="+title+"&callback=_thumbnailCallback&context=" + callbackFnName
	if (g_browser.isIE) {
	var wnd = openWindow(url, "thumbnailWnd", 500, 460, "")
	} else {
		var wnd = openWindow(url, "thumbnailWnd", 500, 510, "")
	}
}

function _thumbnailCallback(wnd, cmd, nrtid, id, title, imgSrc, url, context) {

	var callbackFn = eval("window." + context)
	if (!callbackFn) {
		locAlert(getLocalizedString("884|Callback function not found!"))
	}
	else {
		callbackFn(wnd, cmd, title, nrtid)
	}
}

function toggleGroupExpand(itemID, groupBy, groupName, img) {
	// 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.
	
	//alert('toggleGroupExpand(' + itemID + ', ' + groupBy + ', ' + groupName + ', ' + img.src + ')')
	
	if (!groupName) {
		groupName = "!"
	}
	
	var expand
	
	var elem = document.getElementById(itemID + "-" + groupName)
	if (elem) {
		if (elem.style.display == 'none') {
			img.src = "../images/Expanded.gif"
			img.alt=parseAndLocalizeStr("{956|Expand}")
			elem.style.display = "inline"
			expand = "1"
		} else {
			img.src = "../images/Collapsed.gif"
			img.alt=parseAndLocalizeStr("{958|Collapse}")
			elem.style.display = "none"
			expand = "0"
		}

		// Notify server
		var url = virtualRoot() + "/scripts/Expand.asp?page=" + page.id + "&id=" + itemID + "&group=" + groupName + "&expand=" + expand + "&groupBy=" + groupBy + "&view=" + page.view
		var applet = document.clientToAspApplet
		if (applet) {
			//alert('applet.putData("' + url + '")')
			var data = applet.putData(url)
		}
	}
}

function mailtoURL(nrtid, title, script) { 
	if ( ! g_browser.isIE || ! g_browser.isIE5 ) {
		var body = script + escape(nrtidEncode(nrtid)) + "&ext=1"
		var subject = title
		return "mailto:?body=" + escape(body) + "&subject=" + escape(subject)
	} else {
		var body = mailtoEncode(script) + nrtidEncode(nrtid) + "%2526ext=1"
		var subject = mailtoEncode(title)
		return "mailto:?body=" + body + "&subject=" + subject
	}
}

function nrtidEncode(nrtid) {
	return nrtid.replace(/\!/g, "$").replace(/\:/g, ";")
}

function mailtoEncode(input) {
	return escape(input).replace(/%/g,  "%25")
}

function virtualRoot() {
	var str = getCookie("rootURL")
	return prependIPSURL(str)
}

//This function is only useful for iPlanet gateway.
function prependIPSURL(str) {
	var add_ipsURL_to_iman = str;
	return add_ipsURL_to_iman;
}

//Check the length of "str" with "size".If greater, then trim "str" to "size".
function checkLength(str,size)
{
	if(str.length > size)	
		str = str.substring(0,size) + "..."	
	return str
}

function getNRTypeName(item) {
	// This gets the NRT type via the id.  It accepts either an object or an ID string.
	
	var typeName = ""
	var id
	
	if (typeof(item) == "object") {
		id = item.ID
	} else {
		id = item
	}
	
	var idStr
	var beginPos = id.lastIndexOf("!")
	
	if (beginPos >= 0) {
		beginPos++
		var endPos = id.indexOf(":", beginPos)
		idStr = id.slice(beginPos, endPos)
	
		switch (idStr) {
			case "folder":
				typeName = "NRTFolder"
				break
			case "database":
				typeName = "NRTDatabase"
				break
			case "session":
				typeName = "NRTSession"
				break
			case "nrtdms":
				typeName = "NRTDMS"
				break
			case "documents":
				typeName = "NRTDocuments"
				break;
			case "document":
				typeName = "NRTDocument"
				break;
			case "page":
				typeName = "NRTPage"
				break
			case "discussionfolder":
				typeName = "NRTDiscussionFolder"
				break
			case "rootdiscussion":
			case "discussion":
				typeName = "NRTDiscussionTopic"
				break
			case "eventfolder":
				typeName = "NRTEventFolder"
				break
			case "event":
				typeName = "NRTEvent"
				break
			case "taskfolder":
				typeName = "NRTTaskFolder"
				break
			case "task":
				typeName = "NRTTask"
				break
			case "rootfolder":
				typeName = "NRTRootFolder"
				break;
			default:
				typeName = "Unknown"
				break
		}
	}
	
	return typeName
}

function Page() {
	// this default values should be aprropriate for all temporary pages
	
	this.id			= 'temp-page'
	this.access		= iEnums.nrReviewerAccess
	this._redirect	= virtualRoot() + '/scripts/home.asp'
	this.image		= virtualRoot() + '/images/ipage.gif'
	this.type		= kTempPageType
	this.view		= ''
	this.debug		= ''
	this.zoomed		= '0'
	this.required	= '0'
	this.rights		= '0'
	this.title		= ''
	this.description = ''
	this.getRedirect = new Function("return setURLParam(this._redirect, 'tabid', this.getTabObj().getSelection())")
	this.getTabObj = new Function("return this.isStartPage() ? window.outerTabsObj : window.innerTabsObj")
	this.isStartPage = new Function("return isMonikerEqualIgnoreServerName(this.id.toUpperCase(),window.startPageID.toUpperCase())")
}

page = new Page()

window.g_menuid = 0

function writeActionMenus(buttonTxt, size, menu,isItemHeader) {
	var menuName = 'menu_' + (window.g_menuid++)
	var onClick = menu ? htmlString('window.fw_menu  = ' + menu + '; if (!fw_menu) return ; fw_menu.writeMenus(); FW_showMenu(fw_menu, -50, 15, null, \'' + menuName + '\');return false') : ""
	var root = virtualRoot()
	var cls = (size=='big' ? 'action-button-big' : 'action-button-small')

	var str = '\n' +
			'<table border="0" cellspacing="0" cellpadding="0" width="1"><tr>'
		 if (isItemHeader) {
			 str +='<td class="item-title-menu" nowrap><img src="../images/titleSwoop.gif" width="35" height="18" alt="" border="0"></td>'
	  		 str+='<td class="item-title-menu"  nowrap align="right"><a class="'+cls+'" href="#" onclick="' + onClick + '">' + parseAndLocalizeStr(buttonTxt) +
				  '<img name="' + menuName + '" border="0" src="../images/menuArrow.gif" width="9" height="9" align="absmiddle" /></a></td>'
		 }else {	
			str+='<td class="'+cls+'" nowrap align="right"><a class="'+cls+'" href="#" onclick="' + onClick + '">' + parseAndLocalizeStr(buttonTxt) +
				'<img name="' + menuName + '" border="0" src="../images/menuArrow.gif" width="9" height="9" align="absmiddle" /></a></td>'
		 }	
		str+='</tr></table>'
	return str		
}

function innerTabsAction(id) {

	innerTabsObj.setSelection(id)

	if ( page.zoomed == '1' || g_browser.isNS4 ) {
	
		// clear zoomed mode and refresh
		window.location.replace(setURLParam(page.getRedirect(), "id", ""))
	
	} else if ( page.zoomed == '0' && ! g_browser.isNS4 ) {
	
		var tabStyle
		var prevId = innerTabsObj.getPrevSelection()
		if ( prevId ) {
			tabStyle = getStyleObject(prevId)
			if ( tabStyle ) {
				tabStyle.display = "none"
			}
		}
		tabStyle = getStyleObject(innerTabsObj.getSelection())
		if ( tabStyle ) {
			tabStyle.display = "block"
		}
		var innerTabsDiv = window.document.getElementById("innerTabsDiv")
		if ( innerTabsDiv ) {
			innerTabsDiv.innerHTML = innerTabsObj.render()
		}
			
	}
}
	
function outerTabsAction(id) {
	outerTabsObj.setSelection(id)
	window.location.replace(virtualRoot() + "/scripts/" + "Home.asp?page=_start&tabid=" + escape(outerTabsObj.getSelection()))
}

function showAbout() {
	if (g_browser.isNS4) {
		openWindow(virtualRoot() + "/scripts/" + "About.asp", "aboutWnd", 435, 300, "")
	}else {
		openWindow(virtualRoot() + "/scripts/" + "About.asp", "aboutWnd", 400, 250, "")
	}	
	return false
}

function closeWindow() {
	var applet = document.applets["clientToAspApplet"]		
	var url = virtualRoot() + "/scripts/logout.asp?redirect=false"		
	var result = applet.getData(url)						
	top.close()
}

function showHelp(topic, isAdmin) {
	var helpForm = document.helpForm

	var helpURL
	if (topic) {
		helpURL = virtualRoot() + "/help/help/" + topic
	} else {
		if ( helpForm ) {
			helpURL = helpForm.action
		} else if ( dialog_Help ) {
			return dialog_Help()
		} else {
			helpURL = virtualRoot() + "/help/help/WebHelp.htm"
		}
	}	 

	//Support localized help	
	var langExt = window.lllist.abbreviation
	
	//Slice US / GB ... from the langExt for English help.
		var language = langExt.substr(0,2)
		langExt = (language == "en")?language:langExt
	
	var pos = helpURL.indexOf("help")
	var endPos = pos
	if ( pos > -1 ) {
		endPos = pos + 5
		helpURL = helpURL.substring(0, endPos) + langExt + "/" + helpURL.substring(endPos, helpURL.length)
	} else {
		helpURL = langExt + "/" + helpURL					
	}	
	var helpWnd = window.open(helpURL, "help")
	helpWnd.focus()
	return false
}

function writeSectionHeader(caption) {
	document.write('<table width="100%" border="0" cellspacing="0" cellpadding="0" align="center" >')
	document.write('<tr><td class="section-header">'+parseAndLocalizeStr(caption)+'</td></tr>')
	document.write('<tr><td  nowrap class="section-header-border"><img src="../images/pixel.gif" width="1" height="1" alt="" border="0"></td></tr>')
	document.write('</table>')
}

function appendRedirectToURL(url) {
	//This function will append the redirect from the page object (complete with tabid).
	window.location.href = virtualRoot() + setURLParam(url, "redirect", escape(window.page.getRedirect()))
}

function writePageTitle() {
	if (page.zoomed=='0') {
		document.write(page.title)
	}	
}

function writePageDescription() {
	if (page.zoomed=='0') {
		document.write('<p class="page-description">'+checkLength(page.description,90)+'</p>')
	}	
}


function writeFileXferApplet(useActiveX) {

	var appletInfo
	if (g_browser.isNav) {
		appletInfo =	'<applet name="TransferClient" codebase="../bin" code="com.imanage.workteam.filetransfer.TransferClient.class" height="0" width="1"  mayscript="true" archive="iManage.jar" VIEWASTEXT="1" id="TransferClient">'
		appletInfo +=	'	<param name="cabbase" value="iManage.cab"/>'
		appletInfo +=	'	<param name="Action" value="DownloadSelect"/>'
		appletInfo +=	'	<param name="FormName" value="fm"/>'
		appletInfo +=	'	<param name="FileCtrl" value=""/>'
		appletInfo +=	'	<param name="SendFormData" value="yes"/>'
		appletInfo +=	'</applet>'
	} else {
		if (useActiveX == '1') {
			appletInfo =	'<object ID="WebTransferCtrl" style="display:none;" width="1" height="1" codebase="../bin/iManFile.cab#version=7,0,42,0" classid="CLSID:9F51E426-6EED-11D3-80B8-00C04F610DBB" viewastext="1">'
			appletInfo +=	'	<param name="Action" value="3"/>'
			appletInfo +=	'	<param name="_cx" value="0"/>'
			appletInfo +=	'	<param name="_cy" value="0"/>'
			appletInfo +=	'</object>'
		} else {
			appletInfo =	'<applet name="TransferClient" codebase="../bin" code="com.imanage.workteam.filetransfer.TransferClient.class" height="0" width="1"  mayscript="true" archive="iManage.jar" VIEWASTEXT="1" id="TransferClient">'
			appletInfo +=	'	<param name="cabbase" value="iManage.cab"/>'
			appletInfo +=	'	<param name="Action" value="DownloadSelect"/>'
			appletInfo +=	'	<param name="FormName" value="fm"/>'
			appletInfo +=	'	<param name="FileCtrl" value=""/>'
			appletInfo +=	'	<param name="SendFormData" value="yes"/>'
			appletInfo +=	'</applet>'
		}
	}
		
	document.write(appletInfo)
}

function addToFavorites(pageID, image, title, href) {
	/*
	Instantiates clientToAspApplet to add an item to the favorites in the user's prefs page.
	PARAMETERS:
		pageID:	Moniker of dms page
		image:	Image associated w/item being added
		title:	Title of item being added
		href:	Used for adding documents; all other items go through home.asp, whereas
				documents are retrieved through getdoc.asp.
	*/
	
	var applet
	var url
	
	applet = document.applets["clientToAspApplet"]
	url = virtualRoot() + "/scripts/updateFavorites.asp?page=" + pageID + "&img=" + image + "&title=" + escape(title)
	if (href) {
		url = url + "&href=" + href
	}
	
	if (applet) {
		applet.getData(url)
		locAlert(getLocalizedMessage("134", unescape(title)))
	}
	
}