﻿// entree.js CopyRight 2003 Future Solutions Lab Ltd.
// Using this file is restricted

var istrace = false;			//Set this value true or false to enable or disable code tracing
//var istrace = true;
// By all means, try to use the following function to set or get the field value
//	getValue( key ) - return the value of the field with key
//	setValue( key, value) - set the field with key with value
//	getParentValue( key ) - return the value of the field with key in parent document
//  setParentValue( key, value) - set the field with key with value in parent document
//	getID( key ) - return the the field object with key
//  getParentID( key ) - return the the field object with key in parent document

if( istrace ) {
	var pt = openTrace()
	pt.document.write("<hr>")
}
var fdCond = new Array(0);

function nullfunc() {
	trace("nullfunct()")
}

function isNull(value) {
	return value == null | value == ''
}

function bcolor(s) {
	return "<font color=blue>" + s + "</font>"
}
function rcolor(s) {
	return "<font color=red>" + s + "</font>"
}
function ftrace(s) {
	trace("<strong>" + s + "()</strong>" );
}
function showtime () {
	var now = new Date();
	var hours = now.getHours();
	var minutes = now.getMinutes();
	var seconds = now.getSeconds()
	var timeValue = "" + ((hours >12) ? hours -12 :hours)
	if (timeValue == "0") timeValue = 12;
	timeValue += ((minutes < 10) ? ":0" : ":") + minutes
	timeValue += ((seconds < 10) ? ":0" : ":") + seconds
	timeValue += (hours >= 12) ? "p " : "a "
	return timeValue;
}

function openTrace() {
	return window.open("", "TRACE", "toolbar=0,location=0, directories=0, status=1, menubar=0, fullscreen=no, scrollbars=2, resizable=0,copyhistory=0,width=450,height=600");
}

function trace(s) {
	if( istrace ) {
		if( pt.closed )
			pt = openTrace()
		pt.document.write( '<div style="font-size:8pt"><font color=darkgray>' + showtime() + '</font>' + s + '</div>' );
	}
}

function eqVal(key) {
	return key + " = " + bcolor(getValue(key))
}

function getID(s) {
	return document.getElementById(s);
}

function getParentID(s) {
	return window.opener.document.getElementById(s);
}

function getValue(s) {
	var val = "";
	if( document.ContentForm.elements[s] != null )
		val = document.ContentForm.elements[s].value;
	//trace("get " + s + " = " + val)
	return val
}

function setClass( name, value)
{
	var obj = getID(name)
	if( obj != null )
	{
		obj.className = value
		trace("set class " + name + " = " + obj.className)
	}
}

function getParentValue(s) {
	var p = window.opener.ContentForm
	var val = "";
	if( p.elements[s] != null )
		val = p.elements[s].value;
	trace("getParent " + s  + " = " + val)
	return val;

}

function setValue( key, value ) {
	if( value == null ) return;
	var p = document.ContentForm;
	if( p.elements[key] == null ) {
		if( value == "" )
			return;
		var k = getID("dynamicfield");
		if( k != null )
			k.innerHTML += "<input Type=HIDDEN name=" + key  + " id=" + key + " />";
	}
	p.elements[key].value = value;
	trace("set " + eqVal(key));
}

function setParentValue( key, value ) {
	var o = window.opener.document
	var p = o.ContentForm;
	if( p.elements[key] == null )
		o.getElementById("dynamicfield").innerHTML = "<input Type=HIDDEN name=" + key  + " id=" + key + " />";
	p.elements[key].value = value;
	trace("setParent " + key + " = " + bcolor(getParentValue(key)) );
}
function setDisplay(key, isVisible ) {
	var p = getID(key);
	if( p != null ) {
		p.style.display = isVisible ? "block" : "none";
		trace( "set " + key + " = " + p.style.display );
	}
}

function getDisplay(key) {
	var p = getID(key);
	if( p != null ) {
		if( p.style.display == "block" )
			return true;
	} else
		trace( key + " not found" );
	return false;
}

function checkBoxAll(viewID, nrow) {
	ftrace("checkBoxAll")
	var i, currentrow, cvalue = getID(viewID + "_checkAll").checked;
	var p = document.ContentForm;
	for (var i=0; i < p.elements.length; i++){
		currentrow = p.elements[i];
		if (currentrow.name.indexOf(viewID + "_DEL_") == 0)
			currentrow.checked = cvalue;
	}
}

function selectRow(view, row) {
	setValue( view + "row" + getValue("_enid"), row );
}

function resetElement(sname) {
	var p = document.ContentForm;
	trace( "resetElement(" + sname + ")" );
	for (var i=0; i < p.elements.length; i++){
		if ( p.elements[i].name.indexOf(sname) >= 0 ) {
			p.elements[i].value = "";
			trace( rcolor(p.elements[i].name) );
		}
	}
}

function resetView() {
	var p = document.ContentForm;
	trace( "resetView()" );
	for (var i=0; i < p.elements.length; i++) 
	{
		var sname = p.elements[i].name;
		if( "Filter".indexOf(sname) >= 0 || "ColumnSort".indexOf(sname) >= 0 || "Order".indexOf(sname) >= 0 || "_sch_".indexOf(sname) >= 0 )
		{
			p.elements[i].value = "";
			trace( rcolor(p.elements[i].name) );
		}
	}
}

function viewReset(vname) {
	ftrace( "viewReset" )
	resetElement("_KEY.");
	setValue( vname + "Filter", "" );
	setValue( vname + "ColumnSort", "" );
	setValue( vname + "Order", "");
	resetElement(vname+"_sch_");
	formSubmit('_OPEN|CACHE');
}

function actionReset(vname) {
	ftrace( "actionReset" )
	setValue( vname + "Filter", "" );
	setValue( vname + "ColumnSort", "" );
	setValue( vname + "Order", "");
	resetElement( vname + "_sch_");
	formSubmit('');
}

function viewSubmit(svalue, colid, cache) {
	ftrace( "viewSubmit");
	setValue(svalue, colid);
	if( cache == "true" )
		setValue("_Action", getValue("_Action") + "|CACHE");
	document.ContentForm.submit();
}

function viewPageSubmit(cache) {
	ftrace( "viewPageSubmit");
	if( cache == "true" )
		setValue("_Action", getValue("_Action") + "|CACHE");
	document.ContentForm.submit();
}

function disableButton() {
	var pform = document.ContentForm
	for (var i=0;i<pform.elements.length;i++){
		if( pform.elements[i].type )
		{
			if ( pform.elements[i].type.toLowerCase() == "button" ||
				pform.elements[i].type.toLowerCase() == "submit" ){
				pform.elements[i].disabled  = true;
			} else if (istrace && pform.elements[i].name.indexOf("_KEY.") >= 0 )
				trace( "verify " + eqVal( pform.elements[i].name ) );
		}
	}
	/*
	alert(document.anchor.length)
	for(var i=0; i < document.anchor.length; i++ ) {
		trace(document.anchor[i].href)
		document.anchor[i].href = ""
	}
	*/
}

function changeUrlToRelative(sRef, sUrl)
{
	var	s;
	var	iMax;
	var	k;
	var	p;

	s = sUrl;
	/* try to match sUrl with sRef to change into relative path as much as we can */
	iMax = sRef.length;
	if (iMax > sUrl.length)
		iMax = sUrl.length;
	k = 0;
	while (k < iMax && sRef.charAt(k) == sUrl.charAt(k))
		k++;
	if (k < iMax)
	{ /* partial match try to change into ../ relative path */
		while (k > 0 && sRef.charAt(k) != "/")
			k--;	/* backtrack to the nearest / */
		if (k > 0)
		{ /* we have some relative paths */
			/* count the number of remaining / up to the end or ? */
			s = "";
			p = k+1;
			while (p < sRef.length && sRef.charAt(p) != "?")
			{
				if (sRef.charAt(p) == "/")
					s = s + "../";
				p++;
			}
			s = s + sUrl.substring(k+1, sUrl.length);		
		}	
	}
	return(s);			
}

function removeServerNameInTag(sLoc, sPrefix, doc, sTag, sAttrib)
{
	var 	myRegExp;
	var	cl;
	var	k;
	var	atb;
	var	s;
	var	sRef;

	cl = doc.getElementsByTagName(sTag);
	if (!!cl)
	{
		myRegExp = new RegExp("^" + sPrefix, "i");
		sRef = sLoc.replace(myRegExp, "/");	/* reference absolute URL path */
		for (k = 0; k < cl.length; k++)
		{
			atb = cl[k].getAttributeNode(sAttrib);
			if (!!atb)
			{
				s = atb.value.replace(myRegExp, "/");	/* change host part to / */
				s = changeUrlToRelative(sRef, s);
				atb.value = s;
			}
		}
	}
}

function removeServerNameInInnerHTML(doc)
{
	var	myRegExp;
	var	sPrefix;
	var	sLoc;
	
	myRegExp = new RegExp("^HTTP://[^/]*/", "i");	
	sLoc = window.location.toString();
	sPrefix = sLoc.match(myRegExp);	/* find host part up to / */
	if (!!sPrefix)
	{
		/* server name part located */
		removeServerNameInTag(sLoc, sPrefix, doc, "A", "HREF");
		removeServerNameInTag(sLoc, sPrefix, doc, "IMG", "SRC");
	}
//	alert(doc.body.innerHTML);
}

function formSubmit(action, url, statement) {
	ftrace( "formSubmit" );
	if (action.toUpperCase() == "_SAVE" && !areFieldsValid()) return;
	//to disable all buttons
	var pform = document.ContentForm;
	var fm;
	trace( "verify " + eqVal( "_enid" ) )
	disableButton()
	if( url == null ) {url = "";}
	for(var i=0; i < window.frames.length; i++ ){
		if( (fm = pform.elements[window.frames[i].name.substring(1) ]) != null ) {
			removeServerNameInInnerHTML(window.frames[i].document);
			fm.value = window.frames[i].document.body.innerHTML;
			}
	}
	setValue( "_statement", statement);
	setValue( "_URL", url);
	if( action != "" & action != null )
		setValue( "_Action", action);
	pform.submit();
	trace( rcolor("Submitted") )
}

function refreshForm(alias, target, id, value, reset) {
	ftrace("refreshForm");
	saveDefault();
	setValue("_REFRESH", target);
	setValue("REFRESHRESET", reset);
	setValue("REFRESHACTION", "true");
	resetKey(reset)
	if( alias != "" && alias != null ) {
		var key = "_KEY." + alias;
		var p = pform.elements[key];
		if( p == null ) {
			setValue( key,  id + "='" +  value + "'");
		} else {
			setValue( key, getValue(key) + " and " + id + "='" +  value + "'");
		}
	}
	formSubmit('');
}

function refreshParentForm(target, keys, reset) {
	ftrace("refreshParentForm");
	setParentValue("_REFRESH", "");
	if (reset) {
		setParentValue("REFRESHRESET", reset);
	} else {
		setParentValue("REFRESHRESET", "false");
	}
	setParentValue("REFRESHACTION", "true");
	if( keys !=  "" )
	{
		var a = keys.split(",");
		for( var i = 0; i < a.length; i++)
			setParentValue("_KEY." +  a[i], "");
	}
	var pnt =  window.opener.document.ContentForm;
	pnt.target = "_self";  
	pnt.submit();
}

function cancelConfirm() {
	ftrace("cancelConfirm");
	setValue("_wkaction", "");
	setDisplay("wkflow_Action",true);
	setDisplay("wkflow_Comment", false);
}
function workflowSubmit(id) {
	ftrace("workflowSubmit");
	setValue("_wkaction", id);
	setDisplay("wkflow_Action", false);
	setDisplay("wkflow_Comment", true);
}

function portalSubmit(gid) {
	ftrace("portalSubmit");
	setValue("_GID", gid);
	setValue("_AppID", "");
	setValue("_DocID", "");
	setValue("_enid", "");
	resetElement("_KEY.");
	formSubmit('_OPEN', '');
}

function appSubmit(appID, action, url) {
	ftrace("appSubmit");
	setValue("_enid", "");
	resetElement("_KEY.");
	setValue("_GID", "" );
	setValue("_DocID", "" );
	setValue("_menuItem", "" );
	setValue("_AppID",appID );
	formSubmit(action+'|CACHE', url);
}

function resetKey(keys) {
	if( keys != "" )
	{
		var a = keys.split(",")
		for( var i = 0; i < a.length; i++ )
			setValue("_KEY." + a[i], "");
	}
}

function actionSubmitReset(pageID, action, url, statement, sreset) {
	ftrace( "actionSubmitReset" );
	resetKey(sreset);
	actionSubmit(pageID, action, url, statement);
}

function actionSubmitKeep(pageID, action, url, statement, sreset) {
	ftrace("actionSubmitKeep");
	if( sreset != "" ) 	{
		var a = sreset.split(",");
		var p, pform = document.ContentForm;
		var sname, keep;
		for (var i=0; i<pform.elements.length; i++){
			sname = pform.elements[i].name;
			if( sname.indexOf("_KEY.") >= 0 ) {
				keep = false;
				for( var j = 0; j < a.length && !keep; j++ ) {
					if( sname == ("_KEY." + a[j]) ) {
						trace("keep " + sname );
						keep = true;
						}
				}
				if( !keep ) {
					trace( "reset " + pform.elements[i].name );
					pform.elements[i].value = "";
					}
			}
		}
	}
	actionSubmit(pageID, action, url, statement);
}

function actionSubmit(pageID, action, url, statement) {
	ftrace("actionSubmit")
	saveDefault();
	setValue("_enid", pageID);
	formSubmit(action, url, statement);
}

function pageSubmit(pageID, action, url, statement) {
	ftrace("pageSubmit");
	saveDefault();
	resetElement("_KEY.");
	setValue("_enid", pageID);
	formSubmit(action, url, statement);
}

function viewResetAll() {
	ftrace("viewResetAll")
	var pform = document.ContentForm;
	var p;
	for (var i=0; i< pform.elements.length; i++){
		p = pform.elements[i];
		if ( p.name.indexOf("Filter") >= 0 ||
			 p.name.indexOf("ColumnSort") >= 0 ||
			 p.name.indexOf("Order") >= 0 ||
			 p.name.indexOf("_sch_") >= 0 ) {
			p.value = "";
		}
	}
}

var pnt;
function parentSubmit(enid, action, p_enid, p_action, url, statement) {
	ftrace("parentSubmit");
	pnt = window.opener.document.ContentForm;
	var c = document.ContentForm;
	if( getParentValue("_enid") != p_enid ) {
		alert( "The parent window has been changed\n" +
			   "Press OK to close the window");
		window.close();
		return;
	}
	if( statement != "" && statement != null )setValue("_statement", statement);
	if( enid != "" && enid != null )setValue("_enid", enid);
	if( action != "" && action != null ) setValue("_Action", action);
	c.submit();
	trace(rcolor("Child - Submitted" ) )
	if( url == null ) {url = "";}
	setParentValue("_URL", url);
	setParentValue("_Action", p_action);
	pnt.target = "_self";
	pnt.submit();
	trace(rcolor("Parent - Submitted" ) )
	//setTimeout('pnt.elements["_URL"].value = url; alert("0"); pnt.elements["_Action"].value = p_action; alert(pnt); pnt.target = "_self"; pnt.submit(); alert("hello2");',0);
}

function menuSubmit(pageID, action, menuID) {
	ftrace("menuSubmit");
	var p = document.ContentForm;
	saveDefault();
	resetElement("_KEY.");
	viewResetAll();
	setValue("_menuItem", menuID);
	setValue("_enid", pageID);
	formSubmit(action, "");
}

function saveDefaultValue(s)
{
	setValue("_default" + s, getValue(s) );
}
function saveDefault()
{
	saveDefaultValue("_window");
	saveDefaultValue("_enid");
	saveDefaultValue("_URL");
	saveDefaultValue("_Action");
}

function docOpen( defappid, enid, alias, docID, action, url, appid) 
{
	ftrace("docOpen" );
	var p = document.ContentForm;
	var curr_appID = getValue("_AppID");
	if (p.app_classids | defappid != curr_appID ) {
		var appID = p.app_classids ?  getAppID(enid, getValue("app_classids")) : defappid
		if (appID.length > 0 && appID != curr_appID) {
			resetElement("_KEY.");
			setValue("_GID", "");
			setValue("_DocID", "");
			setValue("_menuItem", "");
			setValue("_AppID",appID);
		}
	}
	saveDefault();
	if( !isNull(appid) )
		setValue("_AppID", "%" + appid + "|" + alias);
	setValue("_enid", enid);
	setValue("_KEY." + alias, docID);
	formSubmit(action, url);
}

function docSubmit(enid, alias, docID, action, url, appid) {
	ftrace("docSumit" );
	var p = document.ContentForm;
	if (p.app_classids) {
		var curr_appID = getValue("_AppID");
		var sappID = getAppID(enid, getValue("app_classids"));
		if (sappID.length > 0 ) {
			resetElement("_KEY.");
			setValue("_GID", "");
			setValue("_DocID", "");
			setValue("_menuItem", "");
			setValue("_AppID",sappID);
		}
	}

	if( url.indexOf("popup") >= 0 )
	{
		ftrace("popupForm");
//		var w = window.open("", "Info_01", url);
		var w = window.open("", "Info_01", 'toolbar=0,location=0, directories=0, status=0, menubar=0, scrollbars=1, resizable=1,copyhistory=0,width=900,height=600');
		var id, exclude="_window_enid_Action_PopUP_PopUPcpField_PopUPidField";
 		w.document.write("<html><body><form method='POST' NAME='cForm' ID='cForm' enctype='multipart/form-data' >")
 		for(var i=0; i < p.elements.length; i++ )
 		{
 			id = p.elements[i].id
 			if( id != "" && id != null && exclude.indexOf(id) < 0 )
 				writeValue(w, id, p.elements[i].value)
 		}
 		writeValue(w, "_window", "Info_01");
 		writeValue(w, "_enid", enid);
 		writeValue(w, "_Action", action);
 		writeValue(w, "_PopUP", "1");
 		writeValue(w, "_KEY." + alias, docID);
		writeValue(w, "_URL", url.replace("popup","") );
		w.document.write("</form></body></html>")
		trace(w.document.body.outerHTML);
		w.document.cForm.submit();
	}
	else
	{
		if( !isNull(appid) )
			setValue("_AppID", "%" + appid + "|" + alias);
		saveDefault();
		setValue("_enid", enid);
		setValue("_KEY." + alias, docID);
		formSubmit(action, url);
	}
}

var apps_grp = new Array("gs", "oe", "mc", "ex", "cv", "lo", "mv", "at", "pb", "st", "up", "sp", "MMCcvfSR01", "pa");
var menu_grp = new Array("mnMCGS", "mnOEAR", "mnMC", "mnMCEXH", "mnMCCV", "mnMCLO", "mnMCMV", "mnMCAT", "mnMCPB", "mnMCST", "mnMCUP", "mnMCSA", "mnServReq", "mnMCPA", "mnProject");

function getAppID(enid, app_classids) {
	var appID = "";
	var p_enid = "";
	var idx = -1
	var app_classid = app_classids.split(",");

	if (enid.indexOf("MMCcvfSR01") > -1)
		p_enid = enid;
	else
		p_enid = enid.substring(3,5);
	for (var i=0; i<apps_grp.length; i++) {
		if (apps_grp[i].toString().indexOf(p_enid) > -1) {
			idx = i;
			i = apps_grp.length;
		}
	}
	if (idx > -1) {
		for (var j=0; j<app_classid.length; j++) {
			var tmp_appid = app_classid[j];
			if (tmp_appid.indexOf(menu_grp[idx] + "|") > -1) {
				var a_appid = tmp_appid.split("|");
				appID = a_appid[1];
			}
		}
	}
	return appID;
}

function workflowOpen(logid, enid, key, keyvalue, action, url) {
	var oldKey, oldApp, newApp;
	ftrace("workflowOpen");
	newApp = getValue("_AppID");
	var p = document.ContentForm;
	if (p.app_classids) {
		var curr_appID = getValue("_AppID");
		var appID = getAppID(enid, getValue("app_classids"));
		if (appID.length > 0 && appID != curr_appID) {
			resetElement("_KEY.");
			setValue("_GID", "");
			setValue("_DocID", "");
			setValue("_menuItem", "");
			setValue("_AppID",appID);
			newApp = appID;
		}
	}
	else
	{
		//use regular expression to find the appid embedded in keyvalue (if any), we must match for non "." since multi-key returns very long match key
		var myRegExp = /\.appid *\= *\\?\'([^\.]*)\\?\'/i;
		var ag = keyvalue.match(myRegExp);
		if (!!ag && ag.length >= 2)
			newApp = ag[1];
	}
	saveDefault();
	setValue("_wklogID", logid);
	//setValue("_enid", enid);
	oldKey = getValue(key);
	oldApp = getValue("_AppID");
	setValue(key, keyvalue);
	setValue("_AppID", newApp);
	popupForm( enid, action, 'WFIndexCard', 'toolbar=0,location=0, directories=0, status=0, menubar=0, scrollbars=1, resizable=1,copyhistory=0,width=600,height=600' , "", "");
	setValue(key, oldKey);
	setValue("_AppID", oldApp);
}

function workflowConfirm()
{
	disableButton()
	if( getValue("_PopUP") == "1" )
	{
		parentSubmit('', '', getParentValue('_enid'), getParentValue('_Action'), '', '')
		window.close();
	}
	else
	document.ContentForm.submit();
}

function writeValue(w, id, value)
{
	w.document.write("<input type='hidden' name='" + id + "' id='" + id + "' />" )
	w.document.getElementById(id).value = value;
	trace(id + " = " + value)
}

function popupForm(pageID, action, windowname, url, cpField, idField) {

	ftrace("popupForm");
	var p = document.ContentForm;
/*
	window.open("", windowname, url);
	p.target = windowname;
	setValue("_PopUP", "1");
	if( cpField != null ) setValue("_PopUPcpField", cpField);
	if( idField != null )  setValue("_PopUPidField", idField);
	var _window = getValue("_window");	setValue("_window", windowname);
    var _enid = getValue("_enid");				setValue("_enid", pageID);
    var _URL = getValue("_URL");				setValue("_URL", "");
    var _Action = getValue("_Action");		setValue("_Action", action);
	p.submit();
	trace(rcolor("Popup submitted"));
	setTimeout(	'document.ContentForm.target= "_self";' +
						'setValue("_window","' + _window + '");' +
						'setValue("_PopUP","");' +
						'setValue("_enid","' + _enid + '");' +
						'setValue("_URL","' + _URL + '");' +
						'setValue("_Action","' + _Action + '"); trace("value reset")'
						, 0);
*/
	var w = window.open("", windowname, url);
	var id, exclude="_window_enid_Action_PopUP_PopUPcpField_PopUPidField";
 	w.document.write("<html><body><form method='POST' NAME='cForm' ID='cForm' enctype='multipart/form-data' >")
 	for(var i=0; i < p.elements.length; i++ )
 	{
 		id = p.elements[i].id
 		if( id != "" && id != null && exclude.indexOf(id) < 0 )
 			writeValue(w, id, p.elements[i].value)
 	}
 	writeValue(w, "_window", windowname);
 	writeValue(w, "_enid", pageID);
 	writeValue(w, "_Action", action);
 	writeValue(w, "_PopUP", "1");
	if( cpField != null ) writeValue(w, "_PopUPcpField", cpField);
	if( idField != null )  writeValue(w, "_PopUPidField", idField);
	w.document.write("</form></body></html>");
	trace(w.document.body.outerHTML);
	w.document.cForm.submit();
}

function popupReturn(cpValue, idValue) {
	ftrace("popupReturn");
	setParentValue( getValue("_PopUPcpField"), cpValue);
	setParentValue( getValue("_PopUPidField"), idValue);
    window.close();
}

function viewColumnSort(vname, colid, sasc, sdesc ) {
	ftrace("viewColumnSort");
	var pColSort = vname + "ColumnSort";
	var pSortext = vname + "ColumnSortext";
	var pOrder = vname + "Order";

	if( getValue(pColSort) == colid) {
		if( getValue(pOrder) == "asc" ) {
			setValue(pOrder, "desc");
			setValue(pSortext, sdesc);
		//} else if( getValue(pOrder) == "desc" ) {
		//	setValue(pOrder, "");
		//	setValue(pSortext, "");
		} else
			{
			setValue(pOrder, "asc");
			setValue(pSortext, sasc);
		}
	} else {
		setValue(pColSort,colid);
		setValue(pOrder, "asc");
		setValue(pSortext, sasc);
	}
	formSubmit('_OPEN','');
}

function gotoPage(vname, direction) {
	ftrace("gotoPage")
	setValue(vname + "NextPage", direction);
	formSubmit('_OPEN','');
}

function validateTextArea(textArea, maxChar,sFieldName)
{
    var s = textArea.value;
    if 	(s.length>maxChar){
        textArea.value = s.slice(0, maxChar);
    }
}

function attachment(id)
{
	var s = getValue(id);
	popupForm( '_en_attachment' , '_EDIT' , 'TAtth', 'toolbar=0,location=0, directories=0, status=0, menubar=0, scrollbars=0, resizable=0,copyhistory=0,width=500,height=350' ,id, s);

}

function extractViewKey( T ) {
	var p = document.ContentForm;
	var viewkeys = "";
	for(var i = 1; p.elements[T + "_DEL_" + i] != null; i++ ) {
		if( p.elements[T + "_DEL_" + i].checked ) {
			var docID = p.elements[T + "_DEL_" + i].value;
			viewkeys += "," + docID.substring(1,docID.length - 2);
		}
	}
	return viewkeys == "" ? "" : viewkeys.substring(1);
  }

//-------------------------------------------------------
// Belows are not yet checked
//-------------------------------------------------------

function checkBoxSingle() {
	alert('Check only one checked');
}

function fsllCheckM() {
	return true;
	}

//////////////////////////////////////////////////
// NEW BY BRIAN
//////////////////////////////////////////////////

// functions for validation of Text Fields

// check a field is empty or contains a number of the correct type
// now localised!

//function CheckIsNum(field,len,dp,bSigned,fieldName)
function CheckIsNum(field,len,dp,bSigned,fieldName,curLang)
{

    // in case hidden
    if (!field)
        return true;

    // if disabled don't check
    if (field.disabled)
        return true;

    // check field is not empty
    if (field.value == '') {
		field.value = "0";
        return true;
	}

	// bulid the expected format
	var exptFormat = "";
	for (var i=0; i<len-dp; i++)
		exptFormat = exptFormat + "9";
	if (dp > 0) {
		exptFormat = exptFormat + ".";
		for (var j=0; j<dp; j++)
			exptFormat = exptFormat + "9";
	}

    if (!CheckIsNumAux(field,len,dp,bSigned))
    {
		if (!curLang)
					showError(field,fieldName,' is not in expected format, ' + exptFormat);
				else
					showErrorL(fieldName,curLang,2);
        return false;
    }

	var text = field.value;
	var plen = text.indexOf(".");
	if (plen > -1)
	{
		var aText = text.split(".");
		if (aText[0].length > len) {
			return false;
		}
		if (aText[1].length > dp) {
			return false;
		}
	}

    return true;
}

// check if is a number in the correct format

function CheckIsNumAux(field,len,dp,bSigned)
{
    var text = field.value;
    var res = '';
    var sPat ='';
    var lLen = len - dp;

    // build up a pattern matching string
    if (bSigned)
        sPat = '^-?';
    else
        sPat = '^';
    sPat = sPat + '\\d{1,' + lLen + '}';
    if (dp>0)
    {
        sPat = sPat + '\\.\\d{1,' + dp + '}|' + sPat;
    }
    // build regular expressionn
    var pat = new RegExp(sPat,'i');
    res = text.match(pat);
    if (!res)
    {
        return false;
    }
    else
    {
        if (res!=text)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

// check a field is empty or contains a formated value
// localised

//function CheckIsFormat(field,format,fieldName)
function CheckIsFormat(field,format,fieldName,curLang,formatDesc)
{
    // in case hidden
    if (!field)
        return true;

    // if disabled don't check
    if (field.disabled)
        return true;

    // check field is not empty
    if (field.value == '')
        return true;
    if (!CheckIsFormatAux(field,format))
    {
		var msg = " is not in expected format";
		if (formatDesc) msg = msg + " " + formatDesc;
        if (!curLang)
					showError(field,fieldName,msg)
				else
					showErrorL(fieldName,curLang,3,format);
        return false;
    }
    return true;
}

// check if is a field in the correct format

function CheckIsFormatAux(field,format)
{
    var text = field.value;
    var res = '';

    // build regular expressionn
    var pat = new RegExp(format,'g');
    // search for match
    return pat.test(text);
}

// check a field is empty or contains a formated Date
// localised

//function CheckIsDate(field,format,fieldName)
function CheckIsDate(field,format,fieldName,curLang)
{
    // in case hidden
    if (!field)
        return true;
    // if disabled don't check
    if (field.disabled)
        return true;

    // check field is not empty
    if (field.value == '')
        return true;

    // in case date format is not in XML yet
    if (format == "")
        format = "DD/MM/YYYY"

	if (!fieldName && fieldName == "")
		fieldName = "\"" + getInnerText(getID(field.id + "_cp")) + "\"";

    if (!CheckIsDateAux(field,format))
    {
        //showError(field,fieldName,' is not in expected format (' + format + ')')
        if (!curLang)
					showError(field, fieldName ,', ' + field.value + ', is invalid!')
				else
					showErrorL(fieldName,curLang,3,format);
        return false;
    }
    return true;
}

// check if is a field in the correct Date format

function CheckIsDateAux(field,format)
{
    var text = field.value;
    var res = '';

	var i_day = "";
	var i_month = "";
	var i_year = "";

	/*
    if (format == 'DD/MM/YYYY')
        pat = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/i
    else if (format == 'MM/DD/YYYY')
        pat = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/i
    else if (format == 'YYYY-MM-DD')
        pat = /[0-9]{4}-[0-9]{2}-[0-9]{2}$/i
    else
    {
        alert('Unknown Date Format:'+format);
        return false;
    }

    res = text.match(pat);
    if (!res)
        return false;
	*/
	if (format == "DD/MM/YYYY") {
		var sArray1 = text.split("/");
		i_day = sArray1[0];
		i_month = sArray1[1];
		i_year = sArray1[2];
	} else if (format == "MM/DD/YYYY") {
		var sArray2 = text.split("/");
		i_month = sArray2[0];
		i_day = sArray2[1];
		i_year = sArray2[2];
	} else if (format == "YYYY-MM-DD") {
		var sArray3 = text.split("-");
		i_year = sArray3[0];
		i_month = sArray3[1];
		i_day = sArray3[2];
	}
    // watch out for month
    i_month = i_month -1;
    d = new Date(i_year,i_month,i_day);
    var d_year = d.getYear();
    if (d_year < 2000)
        d_year = 1900 + d_year;

    if (i_day != d.getDate())
        return false;
    if (i_month != d.getMonth())
        return false;
    if (i_year != d_year)
        return false;
    return true;
}

// Single error message function

function showError(field,fieldName,msgText)
{
    if (!fieldName)
        alert(field.name + ":\'" + field.value + "\'" + msgText);
    else
        alert("\"" + fieldName + "\"" + msgText);
}
//////////////////////////////////////////////////
// NEW BY BRIAN
//////////////////////////////////////////////////


function submitFolderLink(folderID)
{
	var href = InsertQSValue("_FOLDER", folderID);

	window.location = href;

	return ;
}

//Update By ChenRu(2001-09-29)
function popUpFolderPicker(loc)
{
//add by ChenRu(2001-09-29)
var stmp;
var re;
re="&amp;";
stmp=loc.replace(re,"&");
window.open(stmp, "FolderPickerWin", "width=400, height=400, resizable=yes, scrollbars=yes, screenX=200, screenY=200");
}

function InsertQSValue(name, val)
{
	var href = new String(window.location);
	var index_start = href.indexOf(name + "=")
	var index_end, strTemp = '';


	if (index_start != -1)
	{
	 	 index_end = href.indexOf("&", index_start);
		 if (index_end != -1)
		 	  strTemp = href.slice(index_end, href.length)

		 if (val != '')
		 	  href = href.slice(0, index_start+name.length + 1) + val + strTemp;
		else
			  href = href.slice(0, index_start-1) + strTemp;

	}
	else if (val != '')
	{
	 		index_start = href.indexOf("?");

			if (index_start != -1)
			   href += "&" + name + "=" + val;
			else
			   href += "?" + name + "=" + val;
	}

	return (href);
}

/* Added by Christine Wong 11/12/2001*/
function popupReviewerPicker()
{
      window.open("reviewer.asp", "ReviewerPicker","width=420,height=250");
}

//x25
function portal_change()
{
	var id="";
	if (document.ContentForm.portal != null) {
		id=document.ContentForm.portal.value;
	}
	else if(document.ContentForm.allstru != null) {
		id=document.ContentForm.allstru.value;
	}
	//alert (id);

	for (var i=0;i<document.ContentForm.allstru.options.length;i++)
	{
	if (id==document.ContentForm.allstru.options[i].value)
	{
//alert (document.ContentForm.allstru.options[i].text);
	document.ContentForm.portalstructure.value="";
	document.ContentForm.portalstructure.value=document.ContentForm.allstru.options[i].text;
	}
	}

	for (var j=0;j<document.ContentForm.alltree.options.length;j++)
	{
	if (id==document.ContentForm.alltree.options[j].value)
	{
	var s= document.ContentForm.alltree.options[j].text;
	s = s.replace(/\s+/g,"\n");
	document.ContentForm.portaltree.value="";
        document.ContentForm.portaltree.value=s;
	document.ContentForm.alltree.options[j].selected=true;
	}
	}
}
//2002-02-11
// added by Brian
// check a textarea is not too big
function checkTextArea(textArea, maxChar)
{
    var s = textArea.value;
    if 	(s.length>maxChar)
			return false;
    else
			return true;
}

function checkEmpty(field){
    var returnValue = true;
    if (field[0] && field[0].type == 'checkbox') {
		var isEmpty = true
		for (var i=0; i<field.length; i++) {
			if (field[i].checked) {
				isEmpty = false;
				i = field.length;
			}
		}
		if (isEmpty) {
			returnValue = false;
			alert("\"" + getInnerText(getID(field[0].name + '_cp')) + "\" is mandatory. Please tick at least one checkbox.");
		}
    } else {
		if (field.value == '') {
			returnValue = false;
			if (field.type == 'file')
				alert('Please use the Browse... button to select a file');
			else if (field.type == 'select-one')
				alert("\"" + getInnerText(getID(field.id + "_cp")) + "\" is mandatory. Please pick a choice.");
			else
				alert("\"" + getInnerText(getID(field.id + "_cp")) + "\" is mandatory. Please fill in the mandatory field.");
		}
    }
    return(returnValue);
}

//2002-03-12
// added by Brian
//Check that a select item has not got the first option selected
// check if this mutli value field has at least one option selected
// radio or checkbox
// 2002-05-08  (BRIAN) Check for special mandatory value "-----------------"

function fnCheckSelect(field)
{
    // in case hidden
    if (!field)
        return true;
    // if disabled don't check
    if (field.disabled)
        return true;
    // check if only one value
    if (!field.length)
    {
        if (field.selected)
            return true;
        else
            return false;
    }
    else
    {
        // check the array of items
        var arr = field;
        if (arr[0].selected)
        {
            if (arr[0].value == "-----------------")
                return false;
            else
                return true;
        }
        else
            return true;
    }
}
function CheckBlackBoxValidate(sName)
{
/*
	try
	{
		var ret = eval(sName);
		return ret;
	}
	catch(e)
	{
		// if missing function then return true - assume BlackBox item is hidden by Section
		if (e.number = -2146823279)
			return true
	}
	*/
}

// Check form fields.
// fdCond values:
// {"extp","field name"}
// {"format","money|date|datelong|datetime|time|regular expression","field name","min","max"}      (min & max are optional - may be blank)
function areFieldsValid() {
    var field;
    var form = document.ContentForm;
    for (var i = 0; i < fdCond.length; i++) {
        var fdCondArray = fdCond[i];
        if (fdCondArray[0] == "extp") {
            field = form.elements[fdCondArray[1]];
            if (isVisible(fdCondArray[1]) && !checkEmpty(field)) {
                //field.focus();
                if (field.type)
	                en_setFocus(fdCondArray[1]);
                return false;
            }
        } else if (fdCondArray[0] == "format") {
            field = form.elements[fdCondArray[2]];
            if (isVisible(fdCondArray[2])) {
                var formatType = fdCondArray[1];
                if (formatType == "money") {
                    // Pending.
                } else if (formatType == "date") {
						if (!CheckIsDate(field,getValue('_Dtfmt_date').toUpperCase(),getInnerText(getID(field.id + "_cp")),"")) {
							en_setFocus(fdCondArray[2]);
							return false;
                    }
                } else if (formatType == "datelong") {
                    // Pending.
                } else if (formatType == "datetime") {
                    var DATETIME_FORMAT = "^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}$";
                    if (!CheckIsFormat(field,DATETIME_FORMAT,"Input time")) {
                        //field.focus();
		                en_setFocus(fdCondArray[2]);
                        return false;
                    }
                } else if (formatType == "time") {
                    var TIME_FORMAT = "^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}$";
                    if (!CheckIsFormat(field,TIME_FORMAT,"Input time")) {
                        //field.focus();
		                en_setFocus(fdCondArray[2]);
                        return false;
                    }
                } else if (formatType.indexOf("number") == 0) {
					var sFormat = formatType.replace(" ", "");
					var nArray1 = sFormat.split("(");
					var nArray2 = nArray1[1].split(")");
					var nArray = nArray2[0].split(",");

					var len = nArray[0];
					var dp = nArray[1];
					var bSigned = false;

					if (!CheckIsNum(field,len,dp,bSigned,getInnerText(getID(field.id + "_cp")),false)) {
						en_setFocus(fdCondArray[2]);
						return false;
					}
				} else {
					// Generic regular expression.
					if (!CheckIsFormat(field,formatType,"Input")) {
						//field.focus();
						en_setFocus(fdCondArray[2]);
						return false;
					}
					// Check min.
					var formatMin = fdCondArray[3];
					if (!field.value.match(/^\s*$/) && formatMin != "" && eval(field.value + "<" + formatMin)) {
						alert("Must not be smaller than " + formatMin);
						//field.focus();
						en_setFocus(fdCondArray[2]);
						return false;
					}
					// Check max.
					var formatMax = fdCondArray[4];
					if (!field.value.match(/^\s*$/) && formatMax != "" && eval(field.value + ">" + formatMax)) {
						alert("Must not be larger than " + formatMax);
						//field.focus();
						en_setFocus(fdCondArray[2]);
						return false;
					}
               }
           }
        }
    }
    return true;
}

// Check visibility of given style id.  Checks parents.
function isVisible(id) {
    var element;

    element = document.getElementById(id);
    while (element != null) {
		if ( element.className ) {
           if( element.className == "visible" )
				return true;
		}
        if (element.style.display == "none") {
           return false;
        }
        if (element.style.display == "block")
            return true;
        element = element.parentElement;
    }
    return true;
}

// Check visibility of given style id.  Checks parents.
function isVisible2(id) {
    var element;

    element = document.getElementById(id);
    while (element != null) {
		if ( element.className ) {
           if( element.className == "visible" )
				return true;
		}
        if (element.style.display == "none") {
           return false;
        }
        if (element.style.display == "block")
            return false;
        element = element.parentElement;
    }
    return false;
}

function en_setFocus(id)
{
    var form = document.ContentForm;
	var field;

	if (!isVisible2(id)) {
		field = form.elements[id];
		field.focus();
	}
}

function fsFormatMoney(sValue)
{
	return sValue;
}

function checkImageType (filename)
{
	var filelen = filename.length;
	var extType = ".JPG";
	var extIdx = filename.toUpperCase().indexOf(extType);
	if (extIdx == -1) {
		extType = ".JPEG";
		extIdx = filename.toUpperCase().indexOf(extType);
	}
	if (extIdx == -1 && filelen > extIdx + extType.length) {
		alert("Invalid image type! Only JPEG image can be uploaded.");
		return false;
	}
	return true;
}

function copyright(toHTML) {
	var now = new Date();
	var year = now.getYear();
	var copyrightSign =""
	if (toHTML)
		copyrightSign = "&copy;";
	else
		copyrightSign = "(c)";
	return "Copyright " + copyrightSign + " " + year + " Hong Kong Museum of History. All right reserved.";
}

function showCopyRight()
{
	if (navigator.appName == "Netscape" && btnClick.which == 3) // check for netscape and right click
	{
		alert(copyright(false));
		return false;
	}
	else if (navigator.appName =="Microsoft Internet Explorer" && event.button == 2) // for IE and Right Click
	{
		alert(copyright(false));
		return false;
	}
}

function writeIMG(path, id, popupDetails)
{
	if (path=="" || id=="")
		document.write("No image!");
	else {
		var thumbnail = path + 'THN_' + id;
		var largeImg = path + id;
		document.write('<IMG SRC="' + thumbnail + '" ALT="Click this thumbnail to see the big images." OnMouseDown="showCopyRight()" ');
		document.write('onClick="popupIMG(\'' + largeImg + '\'');
		if (popupDetails)
			document.write(',\'' + popupDetails + '\'');
		document.write(')" />');
	}
}

function popupIMG(img, details)
{
	ftrace("popupImg");

	if (img!="") {
		var now = new Date();
		var popupName = now.getHours() + now.getMinutes() + now.getSeconds();
		var w = window.open("", popupName, "left=40, top=30, width=720, height=570, location=no, menubar=no, status=no, toolbar=no, scrollbars=yes,resizeable=yes");
 		w.document.writeln('<html>');
 		w.document.writeln('<title>HKMH Image viewer</title>');
		w.document.writeln('<META http-equiv="Content-Type" content="text/html; charset=utf-8">');
		w.document.writeln('<LINK REL="stylesheet" TYPE="text/css" HREF="../include/_en_standard.css" TITLE="style">');
 		w.document.writeln('<body>');
		w.document.writeln('<script language="JavaScript" src="../include/entree.js"></script>');
//		w.document.writeln('<script language="JavaScript" src="../include/_en_layout.js"></script>');

		w.document.writeln('<table width="660" align="left" border="0" cellspacing="1" cellpadding="0">');
		w.document.writeln('<tr>');
		w.document.writeln('<td class="normal">');
//		w.document.writeln('<td>');
		if (details)
		{
			w.document.writeln('<span class="formReadOnly">' + details + '</span>');
//			w.document.writeln('<span><font face="Verdana" size="2">' + details + '</font></span>');
//			w.document.writeln('<span>' + details + '</span>');
		}
		w.document.writeln('</td>');
		w.document.writeln('<td align="right">');
//		w.document.writeln('<input type="Button" class="formButton" value="Close" onmouseover="hightlight(this,\'formButton_o\')" onmouseout="hightlight(this,\'formButton\')" onclick="javascript:window.close()">');
		w.document.writeln('<input type="Button" class="formButton" value="Close" onclick="javascript:window.close()">');
//		w.document.writeln('<font face="Verdana" size="2">');
//		w.document.writeln('<input type="Button" value="Close" onclick="javascript:window.close()">');
//		w.document.writeln('</font>');
		w.document.writeln('</td>');
		w.document.writeln('</tr>');
		w.document.writeln('<tr><td colspan="2">');
		w.document.writeln('<img src="' + img + '" ALT="' + copyright(true) + '" OnMouseDown="showCopyRight()"/>');
		w.document.writeln('</td></tr>');
		w.document.writeln('<tr><td colspan="2" align="center">');
		w.document.writeln('<hr>');
		w.document.writeln('<span class="normal">' + copyright(true) + '</span>');
		w.document.writeln('</td></tr>');
		w.document.writeln('</table>');
		w.document.writeln("</body></html>");
	}
}

function logout()
{
	var	s;
	var	k;

	document.write("");
	s = window.location.pathname;
	k = s.length - 1;
	while (k > 0 && (s.charAt(k) != "." && s.charAt(k) != "/"))
		k--;
	if (s.charAt(k) == ".")
		window.location.href = "logout.aspx";	/* assume aspx backend */
	else
		window.location.href = "logout";		/* assume servlet backend */
}

function ToUCase(s, toAll) {
	if( document.ContentForm.elements[s] != null ) {
		var sVal = "";
		var sValue = getValue(s);
		//var sValue = document.ContentForm.elements[s].value;
		if (toAll != null) {
			sVal = sValue.toUpperCase();
		} else {
			var aValue = sValue.split(".");
			if (aValue.length <= 1) {
				sVal = sValue.toUpperCase();
			} else {
				sVal = aValue[0].toUpperCase();
				for( var i = 1; i < aValue.length; i++) {
					sVal = sVal + '.' + aValue[i].toLowerCase();
				}
			}
		}
		setValue(s, sVal);
		//document.ContentForm.elements[s].value = document.ContentForm.elements[s].value.substring(0,1).toUpperCase() + document.ContentForm.elements[s].value.substring(1,document.ContentForm.elements[s].value.length).toLowerCase();
	}
	return true;
}

function openWindow(url, name, features) 
{
		var now = new Date();
		var popupName = now.getHours() + now.getMinutes() + now.getSeconds();
		if (!name || name=='') {
			name = popupName;
		}
		if (!features || features=='') {
			features = '';
		}
		//var w = window.open("http://www.lcsd.gov.hk", popupName, "location=yes, menubar=yes, status=yes, toolbar=yes, scrollbars=yes, resizeable=yes");
		//var w = window.open(url, popupName, "");
		var w = window.open(url, name, features);
}
//temporary for BU JS (otherwise, InfoSpace cannot call this function)
function buSubmit(enid, alias, docID, action, url, appid) {
		var GID = "";
		var APPID = "";
		var FORMID = "";
		var ACTN = "";
		var a = enid.split("|");

		if (enid!='') {
			GID = a[0];
			APPID = a[1];
			FORMID = a[2];
			ACTN = a[3];
			if (GID!='') {
				portalSubmit(GID);
			}
			if (APPID!='') {
				appSubmit(APPID,ACTN);
			}

			var aDocID = docID.split("|");
			if (aDocID.length > 1) {			
				for( var i = 1; i < aDocID.length; i++) {
					var bDocID = aDocID[i].split(".");
					setValue("_KEY." + bDocID[0], aDocID[i]);
				}
			}
			docSubmit(FORMID, alias, aDocID[0], ACTN, url, appid);
		}
}

//temporary for BU JS (otherwise, InfoSpace cannot call this function)
function caseSubmit(enid, alias, docID, action, url, appid) {
		var GID = getValue("v.GID");
		var APPID = getValue("v.AppID");

		if (GID!='') {
			portalSubmit(GID);
		}
		if (APPID!='') {
			appSubmit(APPID,action);
		}

		docSubmit(enid, alias, docID, action, url, appid);
}



function trimQuot() {
	var p = document.ContentForm;
	var i, currentrow;
	for (i=1; i<p.elements.length; i++) {
		currentrow = p.elements[i];
		var id = "_DEL_";
		if (currentrow.name.indexOf(id) >= 0) {
			var docID = p.elements[i].value;
			docID = docID.replace("'", "");
			docID = docID.replace("'", "");
			p.elements[i].value = docID ;
		}
	}
}

function getInnerText(element) {
	//return element.innerText;	// not Netscape compatible
	return element.childNodes[0].nodeValue;
}

var pButtonColor = null;
function highlightButton(p, val)
{
	if( val == 'normal' && pButtonColor != null)
		p.style.color = pButtonColor
	else if( val == 'over' )
	{
		pButtonColor = p.style.color
		p.style.color = 'red'
	}
}
/*
function sel_add(sel) {
	var n = getID(sel + '_parent').firstChild;
	var rm = ""
	while( n != null )
	{
	
	for(var i=0; i < selem.length; i++ )
	{
		if( selem[i].selected )
		{
			var n = getID(sel)
			n.add(selem[i].cloneNode())
			var c = n.options.lastChild
			c.text = selem[i].text
			c.selected = '1'
			getID(sel + '_parent').removeChild(selem[i])
			rm += ',' + i;
		}
	}
}
*/

function sel_cache(sel)
{
	getID(sel + "_selected").value = getID(sel).innerHTML
}

function sel_add(sel) {
	var nd = getID(sel + '_parent').firstChild, nn;
	while( nd != null )
	{
		nn = nd.nextSibling
		if( nd.selected )
		{
			var n = getID(sel)
			n.add(nd.cloneNode())
			var c = n.options.lastChild
			c.text = nd.text
			c.selected = '1'
			getID(sel + '_parent').removeChild(nd)
		}
		nd = nn
	}
	sel_cache(sel)
}

function sel_remove(sel) {
	var nd = getID(sel).firstChild, nn;
	while( nd != null )
	{
		nn = nd.nextSibling
		if( nd.selected )
		{
			var n = getID(sel + '_parent')
			n.add(nd.cloneNode())
			var c = n.options.lastChild
			c.text = nd.text
			getID(sel).removeChild(nd)
		}
		nd = nn
	}
	sel_cache(sel)
}

function sel_all(sel)
{
	var selem = getID(sel).options;
	for(var i=0; i < selem.length; i++ )
		if( !selem[i].selected )
			selem[i].selected = '1'
}

function openPage(pageID) {
	ftrace("openPage")
	setValue("pageid", pageID);
	formSubmit('_OPEN','');
}

// JScript source code



function ConfirmDelete() {
	var slang;
	var msg;

	msg = "Are you sure to delete selected record?";
	slang = getValue('_language');

	if (slang == 'tradChinese')
		msg = '是否真的刪除已選取紀錄?';
	if (slang == 'SimpChinese')
		msg = '是否真的删除已选取纪录?';
	if (confirm(msg))
		return(true);

	return(false);
}

function actionSubmitConfirm(pageID, action, url, statement) {
	var slang;
	var msg;

	msg = "Are you sure?";
	slang = getValue('_language');
	if (slang == 'translateTradChinese')
		msg = '是否真的继续?';
	if (slang == 'translateSimpChinese')
		msg = '是否真的继续?';
	if (confirm(msg))
		actionSubmit(pageID, action, url, statement);
	return(false);
}

function actionSubmitConfirmBossOnly(pageID, action, url, statement) {
	var k;
	var msg;

	k = 3;
	while (k > 0 && getValue('df.signmgr'+k) == '')
		k--;
	if (k > 0 && getValue('df.signdir1') != '')
	{
		msg = '你已选择了部门及公司领导会签。文件会在部门会签後送回给你，才由你递交给公司领导。';
		if (confirm(msg))
			actionSubmit(pageID, action, url, statement);
		return(false);
	}
	else
	{
		return(actionSubmitConfirm(pageID, action, url, statement));
	}
}

function parentOpenForm(enid, action, p_enid, p_action, url, statement){
	ftrace("parentOpenForm");
	var c = document.ContentForm;
	setValue("_statement", statement);
	setValue("_enid", enid);
	if( action != "" & action != null ) setValue("_Action", action);	
	c.submit();
	trace(rcolor("Child - Submitted") )
	openParentForm("", "", "false");
	setTimeout(300, "window.close()");
}

function openParentForm(target, keys, reset) {
	ftrace("openParentForm");
	var pnt =  window.opener.document.ContentForm;
	pnt.target = "_self";  
	pnt.submit();
}

/*
function saveMeAndRefreshParent() {
	if (areFieldsValid())
	{
		setValue( "_URL", '|Action=_OPEN');
		//setParentValue('_AppID', getParentValue('_AppID'))
		parentSubmit('', '_SAVE', getParentValue('_enid'), getParentValue('_Action'), '', '')
		//formSubmit('_SAVE', '|Action=_CLOSE');
		//alert('h')
		//refreshParentForm('', '', false);
//		window.close();
		//setTimeout('window.close();', 200);
	}
}
*/
function saveMeAndRefreshParent() {
	if (areFieldsValid())
	{
		formSubmit('_SAVE', getValue('_enid')+'|Action=_OPEN');
		setTimeout("refreshParentForm('', '', false);", 200);
//		setTimeout('window.close();', 200);
	}
}

// JScript source code
// Add respond document to parent document
// assumption
// v.id - - current doc id 
// tc.msid - master id, normally appid
// tc.pid - parent doc id, null for root
// tc.lv - current doc level
function infoPopup(enid, alias, docID, action, url, appid) { 
// show the information form info space 
	ftrace("infoPopup"); 
	var myKey = "_KEY." + alias ; 
	var p = document.ContentForm
	var w = window.open("", "INFO", "toolbar=0,location=0, directories=0, status=1, menubar=0, scrollbars=1,resizable=1,copyhistory=0,width=640,height=500");
	var id, exclude="_window_enid_Action_PopUP_PopUPcpField_PopUPidField_KEY." + alias;
 	w.document.write("<html><body><form method='POST' NAME='cForm' ID='cForm' enctype='multipart/form-data' >")
 	if( !isNull(appid) ) 	 
 		exclude = exclude + "_AppID" ; 
 	for(var i=0; i < p.elements.length; i++ )
 	{
 		id = p.elements[i].id 
 		if( id != "" && id != null && exclude.indexOf(id) < 0   ) 
			writeValue(w, id, p.elements[i].value) ;
 	}
 	writeValue(w, "_window", "INFO");
 	writeValue(w, "_enid", enid);
 	writeValue(w, "_Action", action);
 	writeValue(w, "_PopUP", "1");
 	writeValue(w, "_KEY." + alias, docID);	
 	if( !isNull(appid) ) 	 
 		writeValue(w, "_AppID", "%" + appid + "|" + alias); 
	w.document.write("</ form></ body></html>")
	trace(w.document.body.outerHTML);
	w.cForm.submit()
}

function response(btn) {
	ftrace("response")
	var id = getValue("v.id");
	setValue( "tc.pid" , id);
	setValue( "v.id" , "");
	if( getValue("tc.msid") == "" ) 
		setValue( "tc.msid" , id);
	setValue('_KEY.tc', '');
	setValue( "tc.heading", "[new sub topic]");
	setValue( "$PRE.tc.heading", "");
	setValue( "tc.createby", "");
	setValue( 'tc.createdate', "");
	setValue('tc.lv', add('tc.lv'));	
	btn.disabled  = true;
}

function response2(btn, alias) {
	ftrace("response2")
	var id = getValue("v.id");
	setValue( alias + ".pid" , id);
	setValue( "v.id" , "");
	if( getValue(alias + ".msid") == "" ) 
		setValue( alias + ".msid" , id);
	setValue('_KEY.tc', '');
	setValue( alias + ".heading", "[new sub topic]");
	setValue( alias + ".createby", "");
	setValue( alias + ".createdate", "");
	setValue(alias + '.lv', add(alias + '.lv'));	
	btn.disabled  = true;
}

function reply(btn) {
	var id = getValue("v.id");
	setValue( "tc.pid" , id);
	setValue( "v.id" , "");
	if( getValue("tc.msid") == "" ) 
		setValue( "tc.msid" , id);
	setValue('_KEY.tc', '');
	setValue("tc.heading", "Re:" + getValue("tc.heading") );
	setValue( "tc.createby", "");
	setValue( 'tc.createdate', "");
	var s = getValue("tc.lv");
	var i = s - 0;
	setValue('tc.lv', (++i < 10 ? "0" : "") + i );	
	btn.disabled  = true;
}

// JScript source code
function dmslistSubmit(path,folder)
{
	setValue("_dms_path",path);
	setValue("_dms_folder",folder);
	refreshForm('','','','','');
}

function aclApply(classid, lv)
{
	ftrace("aclApply");
	setValue("_KEY.v", "v.classid='" + classid +"'" );
	setValue("_KEY.k", "k.lv='" + lv + "'" );
	popupForm('_en_acl_apply','_EDIT','P', 'toolbar=0,location=0, directories=0, status=1, menubar=0, scrollbars=1,resizable=0,copyhistory=0,width=400,height=600' ,'')
}

// Call by new edit form, Portal profile

function previewStyle(type, field) {
	ftrace("previewStyle");
	setValue("_KEY.i", "i.tp='" + type +  "' and i.id='" + getValue(field) + "'" );
	popupForm( '_sf_stylepicker' , '_EDIT' , 'P', 'width=400,height=300, toolbar=0, location=0, directories=0, status=1, menubar=0, scrollbars=1, resizable=0', '' )
}

// Call by InfoSpace Setup
function addLevel(btn, tp) 
{
	setValue('df.tp', tp);
	getID("v.tp").innerHTML = tp;
	setValue("df.pid", getValue("v.id"));
	setValue("v.id", "" );
	setValue('$PRE.df.sort', '');
	setValue('_KEY.df', '');
	var i = getValue("df.lv") - 0;
	setValue('df.lv', (++i < 10 ? "0" : "") + i );	
	btn.disabled  = true;
	formSubmit( '_SAVE');
}
					
function infoSetupDetail() {
	ftrace("infoSetupDetail")
	if( getValue("df.subtp") != "" ) {
		formSubmit('_Save','') 
		displayForm(getValue("df.subtp"))
	}
}

function displayForm(id, subtp) 
{
	setValue("_KEY.df","df.id='" + id + "'")
	popupForm( '_sf_info_' + subtp, '_EDIT' , 'ST', 'toolbar=0,location=0, directories=0, status=1, menubar=0, scrollbars=1, resizable=0,copyhistory=0,width=550,height=500' , '' )
}

function infoSetup()
{
	setValue( "_KEY.df", "df.id = \'" + getValue("_AppID") + "\'" );
	actionSubmit('_sf_infoSetup', '_OPEN' );
}

function resetAction()
{
	setValue("_Action", "" );
}

function saveInfoSummary()
{
	formSubmit('_SAVEXML', '');
	setTimeout("saveInfoSummary2();");
}

function saveInfoSummary2()	//wait certain time to let first submit complete
{
	window.opener.document.ContentForm.submit();
	window.close();
}

function extractFiles(T) 
{
	var table = document.getElementById( T );
	var rows = table.getElementsByTagName("tr")
	var viewkeys = "";
	for(var i = 1;  i < rows.length;  i++ ) {
		var cols = rows[i].getElementsByTagName("td");
		viewkeys += '<td>' + cols[1].innerHTML + '</td>'
		if( i % 5  == 0 )
			viewkeys += '</tr><tr>'
	}
	return viewkeys
}

function putValue() 
{
	var p = window.opener.document.ContentForm
	var s = getValue("_PopUPcpField")
	var val = getValue("v.id")
	var id = p.elements[s]
	if( id.value ==  '' ) 
		id.value = val
	val = extractFiles('Tfile')
	window.opener.document.getElementById("F_" + s).innerHTML = '<table border="0">	<tr>' + val + '</tr></table>';
}

function addAttach(s) 
{
	var k = getValue("v.file") 
	if( k != '' )
		pageSubmit( s , '_SAVE' , '', '' ) 
}

function setupInfo(type, id ) {
	ftrace("setupInfo")
	resetElement("_KEY.");
	setValue( "_KEY.i" ,"i.tp=\\\'" + type + "\\\' and i.id =\\\'" + getValue(id)  + "\\\'");	
	actionSubmit( '_sf_infoSetup','_OPEN', '')
}

function attachment(id) 
{
	var s = getValue(id);
	popupForm( '_en_attachment' , '_EDIT' , 'TAtth', 'toolbar=0,location=0, directories=0, status=0, menubar=0, scrollbars=0, resizable=0,copyhistory=0,width=350,height=350' ,id, s);
}

function trimFileName(val)
{
	var i = val.lastIndexOf('\\');
	if( i > 0 )
		return val.substring(i + 1,val.length);
	else
		return val;
}

function imageRef(id) 
{
	var s = getValue(id);
	popupForm( '_en_image' , '_EDIT' , 'TAtth', 'toolbar=0,location=0, directories=0, status=0, menubar=0, scrollbars=1, resizable=0,copyhistory=0,width=350,height=650' ,id, s);
}

function add(id)
{
	var s = getValue(id);
	var i = s - 0;
	return (++i < 10 ? "0" : "") + i; 
}

function submitWithValue(pageid, action, key1, val1)
{
	setValue(key1, val1)
	pageSubmit(pageid, action)
}

//Personal Info
function portalDefault(type)
{
	setValue("_dragdefault", type)
	pageSubmit('_sf_perInfo','_OPEN')
}

function extractKey(s,key)
{
	var i = s.indexOf(key)
	if(i >= 0 )
	{
		var j = s.indexOf("='", key.length + i)
		if( j > 0 )
		{
			j += 2
			i = s.indexOf("'", j)
			if( i > 0 )
			{
				return s.substring(j, i)
			}
		}
	}
	return ""
}

//DMS
function newIndexCard2(d1, d2, key, d3, d4, d5)
{
	var id, oid;
	id = extractKey(key,"dm.appid");
	oid = getValue("_AppID");
	setValue("_AppID", id);	//this is used to trick following popup, otherwise do not work properly from InfoSpace
	newIndexCard(extractKey(key,"dm.indexcard"), id);
	setValue("_AppID", oid);
}

function newIndexCard(indexcard, appid)
{
	setValue("_DMS_AppID", appid)
	popupForm(indexcard,'_NEW','IDX','toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=0,copyhistory=0,width=600,height=500','','')
}



function indexCard(enid,alias,key,action,d1,d2)
{
	var id, oid;

	setValue("_KEY." + alias, key);
	id = extractKey(key, alias+".appid");
	oid = getValue("_AppID");
	setValue("_AppID", id);	//this is used to trick following popup, otherwise do not work properly from InfoSpace
	popupForm(enid,action,'IDX', 'toolbar=0,location=0, directories=0, status=1, menubar=0, scrollbars=1,resizable=0,copyhistory=0,width=600,height=500' ,'');
	setValue("_AppID", oid);
}

var weekend = [0];
var weekendColor = "#FFEEEE";
var fontface = "Arial";
var fontsize = 2;

var gNow = new Date();
var ggWinCal;
isNav = (navigator.appName.indexOf("Netscape") != -1) ? true : false;
isIE = (navigator.appName.indexOf("Microsoft") != -1) ? true : false;

Calendar.Months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

// Non-Leap year Month days..
Calendar.DOMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Leap year Month days..
Calendar.lDOMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

function Calendar(p_item, p_WinCal, p_month, p_year, p_format, p_day) {
	if ((p_month == null) && (p_year == null))	return;

	if (p_WinCal == null)
		this.gWinCal = ggWinCal;
	else
		this.gWinCal = p_WinCal;
	
	if (p_month == null) {
		this.gMonthName = null;
		this.gMonth = null;
		this.gYearly = true;
	} else {
		this.gMonthName = Calendar.get_month(p_month);
		this.gMonth = new Number(p_month);
		this.gYearly = false;
	}

	this.gYear = p_year;
	this.gFormat = p_format;
	this.gBGColor = "white";
	this.gFGColor = "black";
	this.gTextColor = "black";
	this.gHeaderColor = "black";
	this.gReturnItem = p_item;
	
	var re = new RegExp ("'", "gi");
	this.gReturnItem2 = p_item.replace(re, "\\\'");
	
	// FSLL
	this.gDay = p_day;
}

Calendar.get_month = Calendar_get_month;
Calendar.get_daysofmonth = Calendar_get_daysofmonth;
Calendar.calc_month_year = Calendar_calc_month_year;
Calendar.print = Calendar_print;

function Calendar_get_month(monthNo) {
	return Calendar.Months[monthNo];
}

function Calendar_get_daysofmonth(monthNo, p_year) {
	/* 
	Check for leap year ..
	1.Years evenly divisible by four are normally leap years, except for... 
	2.Years also evenly divisible by 100 are not leap years, except for... 
	3.Years also evenly divisible by 400 are leap years. 
	*/
	if ((p_year % 4) == 0) {
		if ((p_year % 100) == 0 && (p_year % 400) != 0)
			return Calendar.DOMonth[monthNo];
	
		return Calendar.lDOMonth[monthNo];
	} else
		return Calendar.DOMonth[monthNo];
}

function Calendar_calc_month_year(p_Month, p_Year, incr) {
	/* 
	Will return an 1-D array with 1st element being the calculated month 
	and second being the calculated year 
	after applying the month increment/decrement as specified by 'incr' parameter.
	'incr' will normally have 1/-1 to navigate thru the months.
	*/
	var ret_arr = new Array();
	
	if (incr == -1) {
		// B A C K W A R D
		if (p_Month == 0) {
			ret_arr[0] = 11;
			ret_arr[1] = parseInt(p_Year) - 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) - 1;
			ret_arr[1] = parseInt(p_Year);
		}
	} else if (incr == 1) {
		// F O R W A R D
		if (p_Month == 11) {
			ret_arr[0] = 0;
			ret_arr[1] = parseInt(p_Year) + 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) + 1;
			ret_arr[1] = parseInt(p_Year);
		}
	}
	
	return ret_arr;
}

function Calendar_print() {
	ggWinCal.print();
}

function Calendar_calc_month_year(p_Month, p_Year, incr) {
	/* 
	Will return an 1-D array with 1st element being the calculated month 
	and second being the calculated year 
	after applying the month increment/decrement as specified by 'incr' parameter.
	'incr' will normally have 1/-1 to navigate thru the months.
	*/
	var ret_arr = new Array();
	
	if (incr == -1) {
		// B A C K W A R D
		if (p_Month == 0) {
			ret_arr[0] = 11;
			ret_arr[1] = parseInt(p_Year) - 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) - 1;
			ret_arr[1] = parseInt(p_Year);
		}
	} else if (incr == 1) {
		// F O R W A R D
		if (p_Month == 11) {
			ret_arr[0] = 0;
			ret_arr[1] = parseInt(p_Year) + 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) + 1;
			ret_arr[1] = parseInt(p_Year);
		}
	}
	
	return ret_arr;
}

// This is for compatibility with Navigator 3, we have to create and discard one object before the prototype object exists.
new Calendar();

Calendar.prototype.getMonthlyCalendarCode = function() {
	var vCode = "";
	var vHeader_Code = "";
	var vData_Code = "";
	
	// Begin Table Drawing code here..
	vCode = vCode + "<TABLE border=0 BGCOLOR=\"" + this.gBGColor + "\">";
	
	vHeader_Code = this.cal_header();
	vData_Code = this.cal_data();
	vCode = vCode + vHeader_Code + vData_Code;
	
	vCode = vCode + "</TABLE>";
	
	return vCode;
}

Calendar.prototype.show = function() {
	var vCode = "";
	
	this.gWinCal.document.open();

	// Setup the page...
	this.wwrite("<html>");
	this.wwrite("<head><title>Calendar</title>");
	this.wwrite("</head>");
	

	this.wwrite("<body leftmargin=0 onBlur=self.focus() topmargin=0 marginwidth=0 marginheight=0" + 
		"link=\"" + this.gLinkColor + "\" " + 
		"vlink=\"" + this.gLinkColor + "\" " +
		"alink=\"" + this.gLinkColor + "\" " +
		"text=\"" + this.gTextColor + "\">");
	// Show navigation buttons
	var prevMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, -1);
	var prevMM = prevMMYYYY[0];
	var prevYYYY = prevMMYYYY[1];

	var nextMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, 1);
	var nextMM = nextMMYYYY[0];
	var nextYYYY = nextMMYYYY[1];
	
	this.wwrite("<TABLE WIDTH='100%' border=0 CELLSPACING=0 CELLPADDING=0 bgcolor=#336699><TR><TD ALIGN=center>");
	this.wwrite("<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem2 + "', '" + this.gMonth + "', '" + (parseInt(this.gYear)-1) + "', '" + this.gFormat + "'" +
		");" +
		"\"><img src=../images/first.gif border=0 alt=previous_year><\/A></TD><TD ALIGN=center>");
	this.wwrite("<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem2 + "', '" + prevMM + "', '" + prevYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\"><img src=../images/previous.gif border=0 alt=previous_month><\/A></TD>");
	this.wwrite("<TD ALIGN=center>");


	this.wwriteA("<FONT FACE='" + fontface + "' SIZE=2 color=#EEEEEE><B>");
	this.wwriteA(this.gMonthName + " " + this.gYear);
	this.wwriteA("</B></td><td Align=center>");

	this.wwrite("<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem2 + "', '" + nextMM + "', '" + nextYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\"><img src=../images/next.gif border=0 alt=next_month><\/A></TD><TD ALIGN=center>");
	this.wwrite("<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem2 + "', '" + this.gMonth + "', '" + (parseInt(this.gYear)+1) + "', '" + this.gFormat + "'" +
		");" +
		"\"><img src=../images/last.gif border=0 alt=next_year><\/A></TD></TR></TABLE>");
	
	// Get the complete calendar code for the month..
	vCode = this.getMonthlyCalendarCode();
	this.wwrite(vCode);
	this.wwrite("<img src=../images/line.gif width=100% height=1>");
/*
	this.wwrite("<TABLE WIDTH='100%' border=0 CELLSPACING=0 CELLPADDING=0 bgcolor=#EEEEEE><TR><TD ALIGN=center>");
	this.wwrite("<A HREF='#' " + 
				"onClick=\"self.opener.document." + this.gReturnItem + ".value='" + 
				 (new Date().getMonth()+1) + "/" +new Date().getDate() + "/" + new Date().getFullYear() +
				"';window.close();\">" );
	this.wwrite("<font face=arial size=2>Today is: ");
	this.wwrite(new Date().getMonth() + 1);
	this.wwrite("/");
	this.wwrite(new Date().getDate());
	this.wwrite("/");
	this.wwrite(new Date().getFullYear());
	this.wwrite("</font></a></td></tr></table>");
*/
	this.writeToday();
	this.wwrite("</font></body></html>");

	this.gWinCal.document.close();
}

Calendar.prototype.writeToday = function()
{
	i = gNow.getDate();
	s_day = new String(i.toString());	
	if (i < 10) 
		s_day0 = "0" + i;	
	else
		s_day0 = s_day;
	i = gNow.getMonth() + 1;
	s_month = new String(i.toString());	
	if (i < 10) 
		s_month0 = "0" + i;	
	else
		s_month0 = s_month;
	s_year = new String(gNow.getFullYear().toString());

	if (this.gFormat == "MM/DD/YYYY")
	{
		s_date = s_month + "/" + s_day + "/" + s_year;		
		s_date0 = s_month0 + "/" + s_day0 + "/" + s_year;		
	}
	if (this.gFormat == "DD/MM/YYYY")
	{
		s_date = s_day + "/" + s_month + "/" + s_year;		
		s_date0 = s_day0 + "/" + s_month0 + "/" + s_year;		
	}
	if (this.gFormat == "YYYY-MM-DD")
	{
		s_date = s_year + "-" + s_month0 + "-" + s_day;		
		s_date0 = s_year + "-" + s_month0 + "-" + s_day0;		
	}

	this.wwrite("<TABLE WIDTH='100%' border=0 CELLSPACING=0 CELLPADDING=0 bgcolor=#EEEEEE><TR><TD ALIGN=center>");
	this.wwrite("<A HREF='#' " + 
				"onClick=\"self.opener.document." + this.gReturnItem + ".value='" + s_date0 +
				"';window.close();\">" );
	this.wwrite("<font face=arial size=2>Today is: ");
	this.wwrite(s_date);
	this.wwrite("</font></a></td></tr></table>");



}

Calendar.prototype.showY = function() {
	var vCode = "";
	var i;
	var vr, vc, vx, vy;		// Row, Column, X-coord, Y-coord
	var vxf = 285;			// X-Factor
	var vyf = 200;			// Y-Factor
	var vxm = 10;			// X-margin
	var vym;				// Y-margin
	if (isIE)	vym = 75;
	else if (isNav)	vym = 25;
	
	this.gWinCal.document.open();

	this.wwrite("<html>");
	this.wwrite("<head><title>Calendar</title>");
	this.wwrite("<style type='text/css'>\n<!--");
	for (i=0; i<12; i++) {
		vc = i % 3;
		if (i>=0 && i<= 2)	vr = 0;
		if (i>=3 && i<= 5)	vr = 1;
		if (i>=6 && i<= 8)	vr = 2;
		if (i>=9 && i<= 11)	vr = 3;
		
		vx = parseInt(vxf * vc) + vxm;
		vy = parseInt(vyf * vr) + vym;

		this.wwrite(".lclass" + i + " {position:absolute;top:" + vy + ";left:" + vx + ";}");
	}
	this.wwrite("-->\n</style>");
	this.wwrite("</head>");

	this.wwrite("<body " + 
		"link=\"" + this.gLinkColor + "\" " + 
		"vlink=\"" + this.gLinkColor + "\" " +
		"alink=\"" + this.gLinkColor + "\" " +
		"text=\"" + this.gTextColor + "\">");
	this.wwrite("<FONT FACE='" + fontface + "' SIZE=2><B>");
	this.wwrite("Year : " + this.gYear);
	this.wwrite("</B><BR>");

	// Show navigation buttons
	var prevYYYY = parseInt(this.gYear) - 1;
	var nextYYYY = parseInt(this.gYear) + 1;
	
	this.wwrite("<TABLE WIDTH='100%' border=0 CELLSPACING=0 CELLPADDING=0 BGCOLOR='#e0e0e0'><TR><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem2 + "', null, '" + prevYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\" alt='Prev Year'><<<\/A>]</TD><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"javascript:window.print();\">Print</A>]</TD><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem2 + "', null, '" + nextYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\">>><\/A>]</TD></TR></TABLE><BR>");

	// Get the complete calendar code for each month..
	var j;
	for (i=11; i>=0; i--) {
		if (isIE)
			this.wwrite("<DIV ID=\"layer" + i + "\" CLASS=\"lclass" + i + "\">");
		else if (isNav)
			this.wwrite("<LAYER ID=\"layer" + i + "\" CLASS=\"lclass" + i + "\">");

		this.gMonth = i;
		this.gMonthName = Calendar.get_month(this.gMonth);
		vCode = this.getMonthlyCalendarCode();
		this.wwrite(this.gMonthName + "/" + this.gYear + "<BR>");
		this.wwrite(vCode);

		if (isIE)
			this.wwrite("</DIV>");
		else if (isNav)
			this.wwrite("</LAYER>");
	}

	this.wwrite("</font><BR></body></html>");
	this.gWinCal.document.close();
}

Calendar.prototype.wwrite = function(wtext) {
	this.gWinCal.document.writeln(wtext);
}

Calendar.prototype.wwriteA = function(wtext) {
	this.gWinCal.document.write(wtext);
}

Calendar.prototype.cal_header = function() {
	var vCode = "";
	
	vCode = vCode + "<TR>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>S</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>M</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>T</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>W</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>T</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>F</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='16%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>S</B></FONT></TD>";
	vCode = vCode + "</TR>";
	
	return vCode;
}

Calendar.prototype.cal_data = function() {
	var vDate = new Date();
	vDate.setDate(1);
	vDate.setMonth(this.gMonth);
	vDate.setFullYear(this.gYear);

	var vFirstDay=vDate.getDay();
	var vDay=1;
	var vLastDay=Calendar.get_daysofmonth(this.gMonth, this.gYear);
	var vOnLastDay=0;
	var vCode = "";

	/*
	Get day for the 1st of the requested month/year..
	Place as many blank cells before the 1st day of the month as necessary. 
	*/

	vCode = vCode + "<TR>";
	for (i=0; i<vFirstDay; i++) {
		vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(i) + "><FONT SIZE='2' FACE='" + fontface + "'> </FONT></TD>";
	}

	// Write rest of the 1st week
	for (j=vFirstDay; j<7; j++) {
		vCode = vCode + "<TD WIDTH='14%' align=right" + this.write_weekend_string(j) + "><FONT SIZE='2' FACE='" + fontface + "'>" + 
			"<A HREF='#' " + 
				"onClick=\"self.opener.document." + this.gReturnItem + ".value='" + 
				this.format_data(vDay) + 
				"';window.close();\">" + 
				this.format_day(vDay) + 
			"</A>" + 
			"</FONT></TD>";
		vDay=vDay + 1;
	}
	vCode = vCode + "</TR>";

	// Write the rest of the weeks
	for (k=2; k<7; k++) {
		vCode = vCode + "<TR>";

		for (j=0; j<7; j++) {
			vCode = vCode + "<TD WIDTH='14%' align=right" + this.write_weekend_string(j) + "><FONT SIZE='2' FACE='" + fontface + "'>" + 
				"<A HREF='#' " + 
					"onClick=\"self.opener.document." + this.gReturnItem + ".value='" + 
					this.format_data(vDay) + 
					"';window.close();\">" + 
				this.format_day(vDay) + 
				"</A>" + 
				"</FONT></TD>";
			vDay=vDay + 1;

			if (vDay > vLastDay) {
				vOnLastDay = 1;
				break;
			}
		}

		if (j == 6)
			vCode = vCode + "</TR>";
		if (vOnLastDay == 1)
			break;
	}
	
	// Fill up the rest of last week with proper blanks, so that we get proper square blocks
	for (m=1; m<(7-j); m++) {
		if (this.gYearly)
			vCode = vCode + "<TD WIDTH='14%' align=right" + this.write_weekend_string(j+m) + 
			"><FONT SIZE='2' FACE='" + fontface + "' COLOR='gray'> </FONT></TD>";
		else
			vCode = vCode + "<TD WIDTH='14%' align=right" + this.write_weekend_string(j+m) + 
			"><FONT SIZE='2' FACE='" + fontface + "' COLOR='gray'>" + m + "</FONT></TD>";
	}
	
	return vCode;
}

// FSLL update top hightlight day passed

Calendar.prototype.format_day = function(vday) {
	var vNowDay = gNow.getDate();
	var vNowMonth = gNow.getMonth();
	var vNowYear = gNow.getFullYear();

	if (vday == this.gDay)
		s = "<B>" + vday + "</B>";
	else
		s = vday;

	if (vday == vNowDay && this.gMonth == vNowMonth && this.gYear == vNowYear)
		s = "<FONT COLOR=\"RED\">" + s + "</FONT>";
	return s;
}

Calendar.prototype.write_weekend_string = function(vday) {
	var i;

	// Return special formatting for the weekend day.
	for (i=0; i<weekend.length; i++) {
		if (vday == weekend[i])
			return (" BGCOLOR=\"" + weekendColor + "\"");
	}
	
	return "";
}

Calendar.prototype.format_data = function(p_day) {
	var vData;
	var vMonth = 1 + this.gMonth;
	vMonth = (vMonth.toString().length < 2) ? "0" + vMonth : vMonth;
	var vMon = Calendar.get_month(this.gMonth).substr(0,3).toUpperCase();
	var vFMon = Calendar.get_month(this.gMonth).toUpperCase();
	var vY4 = new String(this.gYear);
	var vY2 = new String(this.gYear.substr(2,2));
	var vDD = (p_day.toString().length < 2) ? "0" + p_day : p_day;

	switch (this.gFormat) {
		case "MM\/DD\/YYYY" :
			vData = vMonth + "\/" + vDD + "\/" + vY4;
			break;
		case "MM\/DD\/YY" :
			vData = vMonth + "\/" + vDD + "\/" + vY2;
			break;
		case "MM-DD-YYYY" :
			vData = vMonth + "-" + vDD + "-" + vY4;
			break;
		case "MM-DD-YY" :
			vData = vMonth + "-" + vDD + "-" + vY2;
			break;

		case "DD\/MON\/YYYY" :
			vData = vDD + "\/" + vMon + "\/" + vY4;
			break;
		case "DD\/MON\/YY" :
			vData = vDD + "\/" + vMon + "\/" + vY2;
			break;
		case "DD-MON-YYYY" :
			vData = vDD + "-" + vMon + "-" + vY4;
			break;
		case "DD-MON-YY" :
			vData = vDD + "-" + vMon + "-" + vY2;
			break;

		case "DD\/MONTH\/YYYY" :
			vData = vDD + "\/" + vFMon + "\/" + vY4;
			break;
		case "DD\/MONTH\/YY" :
			vData = vDD + "\/" + vFMon + "\/" + vY2;
			break;
		case "DD-MONTH-YYYY" :
			vData = vDD + "-" + vFMon + "-" + vY4;
			break;
		case "DD-MONTH-YY" :
			vData = vDD + "-" + vFMon + "-" + vY2;
			break;

		case "DD\/MM\/YYYY" :
			vData = vDD + "\/" + vMonth + "\/" + vY4;
			break;
		case "DD\/MM\/YY" :
			vData = vDD + "\/" + vMonth + "\/" + vY2;
			break;
		case "DD-MM-YYYY" :
			vData = vDD + "-" + vMonth + "-" + vY4;
			break;
		case "DD-MM-YY" :
			vData = vDD + "-" + vMonth + "-" + vY2;
			break;
		case "YYYY-MM-DD" :
			vData = vY4 + "-" + vMonth + "-" + vDD;
			break;

		default :
			vData = vMonth + "\/" + vDD + "\/" + vY4;
	}

	return vData;
}

function Build(p_item, p_month, p_year, p_format, p_day) {
	var p_WinCal = ggWinCal;
	gCal = new Calendar(p_item, p_WinCal, p_month, p_year, p_format, p_day);

	// Customize your Calendar here..
	gCal.gBGColor="white";
	gCal.gLinkColor="black";
	gCal.gTextColor="black";
	gCal.gHeaderColor="#777777";

	// Choose appropriate show function
	if (gCal.gYearly)	gCal.showY();
	else	gCal.show();
}

function show_calendar() {
	/* 
		p_month : 0-11 for Jan-Dec; 12 for All Months.
		p_year	: 4-digit year
		p_format: Date format (mm/dd/yyyy, dd/mm/yy, ...)
		p_item	: Return Item.
		p_day	: day if you wish to highlight in this month // FSLL
	*/

	p_item = arguments[0];
	if (arguments[1] == null)
		p_month = new String(gNow.getMonth());
	else
		p_month = arguments[1];
	if (arguments[2] == "" || arguments[2] == null)
		p_year = new String(gNow.getFullYear().toString());
	else
		p_year = arguments[2];
	if (arguments[3] == null)
 		p_format = "MM/DD/YYYY";
	else
		p_format = arguments[3];
	// hack by FSLL
	if (arguments[4] == null)
		p_day = null;
	else
		p_day = arguments[4];

	vWinCal = window.open("", "Calendar", 
		"width=130,height=200,status=no,resizable=no");
	vWinCal.opener = self;
	ggWinCal = vWinCal;

	Build(p_item, p_month, p_year, p_format,p_day);
}
/*
Yearly Calendar Code Starts here
*/
function show_yearly_calendar(p_item, p_year, p_format) {
	// Load the defaults..
	if (p_year == null || p_year == "")
		p_year = new String(gNow.getFullYear().toString());
	if (p_format == null || p_format == "")
		p_format = "MM/DD/YYYY";

	var vWinCal = window.open("", "Calendar", "scrollbars=yes");
	vWinCal.opener = self;
	ggWinCal = vWinCal;

	Build(p_item, null, p_year, p_format);
}


//FSLL 
function known_format(p_format)
{
	if (p_format == "MM/DD/YYYY")
	{
		return true;
	}
	else if (p_format == "DD/MM/YYYY")
	{
		return true;
	}
	else if (p_format == "YYYY-MM-DD")
	{
		return true;
	}
	else
		return false;
}

//FSLL 
function show_calendar_FSLL(p_field,p_format)
{
	s = new String(p_field.value);
	
        if (p_format=='')
            p_format = "MM/DD/YYYY";
        if (!known_format(p_format))
	{
		alert("Unsupported format:" + p_format);
		return false;
	}

	if (s == "")
	{
		d = new Date();
		s_day = new String(d.getDate());
		s_month = new String(d.getMonth()+1);
		s_year = new String(d.getFullYear().toString());
	}
	else
	{
		if (p_format == "MM/DD/YYYY")
		{
			s_month = s.substr(0,2);
			s_year = s.substr(6,4);		
			s_day = s.substr(3,2);
		}
		else if (p_format == "DD/MM/YYYY")
		{
			s_day = s.substr(0,2);
			s_year = s.substr(6,4);		
			s_month = s.substr(3,2);
		}
		else if (p_format == "YYYY-MM-DD")
		{
			s_year = s.substr(0,4);
			s_month = s.substr(5,2);		
			s_day = s.substr(8,2);
		}
	}

	if (s_month.substr(0,1) == 0)
		s_month = s_month.substr(1,1);
	show_calendar(p_field.form.name + '.elements[\''+p_field.name+'\']',parseInt(s_month)-1,s_year,p_format,s_day);
}

function changeMonthYear(vname)
{
	setValue( '_' + vname + '_cal_tp', 'month');
	formSubmit('');
}

function gotoDay( tp, vname,  month, day) {
	setValue( vname + '_cal_month', month);
	setValue( '_' + vname + '_cal_day', day);
	setValue( '_' + vname + '_cal_tp', tp);
	formSubmit(''); 
}

function toggle_treeview(nName, collapse, expand) {
	var nodeName=document.getElementById("node_" + nName);
	var imgName=document.images["img_" + nName];
	if (nodeName.style.display == "none") {
		nodeName.style.display = "block";
		if( collapse == null)
			imgName.src = "..\\images\\standardform\\collapse.gif"
		else
			imgName.src = collapse;
		setValue("tg_" + nName, "1" )	
	}
	else {
		nodeName.style.display = "none";
		if( expand == null )
			imgName.src = "..\\images\\standardform\\expand.gif"
		else
			imgName.src = expand;
		setValue("tg_" + nName, "0" )	
	}
}


function showTabSelect(ntab, tp){
	ftrace("showTabSelect")
	var tpg = "_tabpage_" + tp
	var ctab = getValue( tpg )
	if( ctab == "" ) 
		ctab = "1"
	setDisplay( tpg + "_" + ctab, false )
	setDisplay( tpg + "_" + ntab, true )
	setValue( tpg, ntab )
}

function showTab(ntab, tp)
{
	ftrace("showTab")
	var tpg = "_tabpage_" + tp
	var ctab = getValue( tpg )
	if( ctab == "" ) 
		ctab = "1"
	setDisplay( tpg + "_" + ctab, false )
	setDisplay( tpg + "_" + ntab, true )
	setClass( "_tab_" + tp + "_" + ctab, "tab" ) 
	setClass( "_tab_" + tp + "_" + ntab, "tabselected" ) 
	setValue( tpg, ntab )
}

function hightlight(m, s) {
	m.className = s;
}

function highlight(m, s) {
	m.className = s;
}

function setSelect(s)
{
	var p = document.ContentForm;
	for (var i=0;i< p.elements.length;i++)
		if ( p.elements[i].type == "select-one" ) 
			p.elements[i].style.visibility = s;
}

function toogleDisplay(p, p2, sty) {
	var s = document.all[p];
	var s2 = document.all[p2];
	if( s.style.display == "block" )
	{
		s.style.display = "none";
		if( s2 != null )
			s2.className = sty + "_close";
	}
	else
	{
		s.style.display = "block"; 
		if( s2 != null )
			s2.className = sty + "_open";
	}
}

function changePortal(form) {
	portalSubmit(s.options[s.selectedIndex].value);
}

function findMenuPos(dir, obj, offset)
{
	var cobj = obj;
	for( var cur = 0; obj.offsetParent; obj = obj.offsetParent)
	{
		if( offset == 0 && obj.tagName == 'UL' )
		{
			break;
		}
		if( dir == 0 && obj.tagName == 'UL' && obj.className != 'ly_mn_Lp')
		{
			if( obj.parentNode.id != 'classic_pmenu' )
				break;
			else
				cur += cobj.offsetWidth;
		}
		cur += dir == 0 ? obj.offsetLeft : obj.offsetTop
	}
	return cur;
}

function showmenu(e,menu,offset){
	var p = getID(menu);
	if( p != null ) 
	{
		var s = p.style;
		eventX = findMenuPos(0, e, offset);
		eventY = findMenuPos(1, e, offset);
		if(offset == 0)
			eventY +=  e.offsetHeight;
		else 
			eventX +=  e.clientWidth;
		var dx = document.body.clientWidth-eventX - p.offsetWidth;
		var dy = document.body.clientHeight-eventY - p.offsetHeight;
		s.left = eventX + (dx < 0 ? dx : 0) ;
		s.top= eventY + (dy < 0 ? dy: 0);
		setSelect("hidden");
		s.display="block"
	}
	clearhidemenu(menu);
}

var timeOut = new Array();

function closeMenu(menu){
	var im = menu.split("_")
	var mn = "appmenu"
	for( var i=1; i < im.length; i++)
	{
		mn += "_" + im[i];
		var p = getID(mn)
		if( p != null )
		{
			if( p.className == 'ly_mn_Lp' )
				timeOut[mn] = setTimeout("hidemenu(\'" +  mn + "\')", (5 - i) * 50);
		}
	}
}

function hidemenu(menu){ 
	var p = document.getElementById(menu);
	if (p != null) {
		p.style.display = "none";
		setSelect("visible");
	}
}

function clearhidemenu(menu){
		var im = menu.split("_")
		var mn = "appmenu"
		for( var i=1; i < im.length; i++)
		{
			mn += "_" + im[i];
			if( timeOut[mn] != null )
			{
				clearTimeout(timeOut[mn]);
				timeOut[mn] = null;
			}
		}
}

var pmenu = null

function setMenu(menu, id)
{
	if( pmenu != null )
		pmenu.style.display = "none"
	else {
		var k = getID(getValue("menuSelected"))
		if( k != null )
			pmenu.style.display = "none"
	}		
	setValue('_menu_LS', id)
	var p = getID(menu)
	if( p != null )
	{
		var s = p.style
		pmenu = s
		s.display = "inline"
	}
	else
		pmenu = null
}


var format="HTML"
var textEdit;

function setEditor(ed) {
	textEdit = window.frames[ed.id];
}

function swapMode(b) {
	swapModes()
	b.innerHTML = format + " Mode"
}

function doFormat(command) {
	if (format=="HTML") {
		if (arguments[1] == null) 
			textEdit.document.execCommand(command)
		else 
			textEdit.document.execCommand(command,false, arguments[1])
		textEdit.focus();
	}
}

function doPickImage() {
	popupForm('_en_imagepicker','_EDIT','P', 
	'toolbar=0,location=0, directories=0,status=1, menubar=0,scrollbars=1,resizable=1,copyhistory=0,width=600,height=300' ,'','') 
}

function swapModes() {
	if (format=="HTML") {
		textEdit.document.body.innerText = textEdit.document.body.innerHTML
		format="Text"
	} else {
		textEdit.document.body.innerHTML = textEdit.document.body.innerText
		format="HTML"
	}
	textEdit.focus()
}

