/**
 * Copyright (c) 2006 Applix, Inc. All rights reserved.
 */



var ua = navigator.userAgent.toLowerCase();
var isMac = (-1 != ua.indexOf("mac"));
var waitingForResponse = false;
var isIE =  (-1 != navigator.appName.indexOf("Microsoft"));

function eweditmask (maskstr) {
	this.maskSpecial = '09#L?Aa&C@';
	this.setMask(maskstr);
};

eweditmask.prototype.isdigit = function (ch) {
	return '0123456789'.indexOf(ch) >= 0;
};

eweditmask.prototype.isspace = function (ch) {
	return ' \t\n\r'.indexOf(ch) >= 0;
};

eweditmask.prototype.isalpha = function (ch) {
	var num = ch.charCodeAt(0);
	return ((num >= 'A'.charCodeAt(0) && num < 'Z'.charCodeAt(0)) ||
			(num >= 'a'.charCodeAt(0) && num < 'z'.charCodeAt(0)));
};

eweditmask.prototype.isalnum = function (ch) {
	return this.isdigit(ch) || this.isalpha(ch);
};

eweditmask.prototype.ispwdchar = function (ch) {
	var num = ch.charCodeAt(0);
       	return (num >= 33 && num <= 127) || (num >= 161 && num <= 255);
			
};

eweditmask.prototype.setMask = function (maskstr) {
	this.maskstr = (!maskstr) ? '' : maskstr;
	var newmask = '';
	var newliteral = '';
	var len = this.maskstr.length;
	for (var ix = 0; ix < len; ++ix) {
		var maskch = maskstr.charAt(ix);
		if ('\\' == maskch) {
			newmask += '\x08';
			newliteral += maskstr.charAt(++ix);
		}
		else if (this.maskSpecial.indexOf(maskch) >= 0) {
			newmask += maskch;
			newliteral += '\x08';
		}
		else {
			newmask += '\x08';
			newliteral += maskch;
		}
	}
	this.mask = newmask;
	this.literal = newliteral;
};

eweditmask.prototype.isValidChar = function (maskch, ch) {
	switch (maskch) {
	case '0':
	case '9':
		return this.isdigit(ch);
	case '#':
		return this.isdigit(ch) || this.isspace(ch) || ('+' == ch) || ('-' == ch);
	case 'L':
		return this.isalpha(ch);
	case '?':
		return this.isalpha(ch) || this.isspace(ch);
	case 'A':
		return this.isalnum(ch);
	case 'a':
		return this.isalnum(ch) || this.isspace(ch);
	case '&':
	case 'C':
		return true;
	case '@':   
        	return this.ispwdchar(ch);
	
	}
	return false;
};

eweditmask.prototype.applyMask = function (instr) {
	if (null == instr || '' == instr || '' == this.maskstr)
		return instr;
	var masklen = this.mask.length;
	var instrlen = instr.length;
	var outstr = '';
	var pos = 0;
	for (var ix = 0; ix < masklen && pos < instrlen; ++ix) {
		var maskch = this.mask.charAt(ix);
		var litch = this.literal.charAt(ix);
		var ch = instr.charAt(pos++);
		if ('\x08' == maskch) {
			outstr += litch;
			if (ch != litch)
				--pos;
		}
		else if (this.isValidChar(maskch,ch)) {
			outstr += ch;
		}
		else {
			--ix;
		}
	}
	return outstr;
};

eweditmask.prototype.stripMask = function (instr) {
	if (null == instr || '' == instr || '' == this.maskstr)
		return instr;
	var masklen = this.mask.length;
	var instrlen = instr.length;
	var outstr = '';
	var pos = 0;
	for (var ix = 0; ix < masklen && pos < instrlen; ++ix) {
		var maskch = this.mask.charAt(ix);
		var litch = this.literal.charAt(ix);
		var ch = instr.charAt(pos++);
		if ('\x08' == maskch) {
			if (litch != ch)
				--pos;
		}
		else if (this.isValidChar(maskch,ch)) {
			outstr += ch;
		}
	}
	return outstr;
};

function loadstring(string)
{
 	if (string == null)
		return "";
	
	var str = new String(string);
	var len = str.length;
	
	for (var ix = 0; ix <=len; ix++)  {
	
		var c =  string.charAt(ix);
		var c1 = string.charCodeAt(ix);
		if( c1== 8216 || c1== 8217 || c1==8220 || c1==8221){
		var newstr = str.replace(c, "'");
		str = newstr;
		}
	}
		
	return str;
}
function checkbnssupport(){
	var bnssupport = false;
	
	var uA = navigator.userAgent;
	if(isIE){
		if("undefined" == typeof ScriptEngine) {
		   var maversion = 1;
		   var miversion = 1;
		} else {
		   var maversion = ScriptEngineMajorVersion();
		   var miversion = ScriptEngineMinorVersion();
		}

		if((maversion>=5&&miversion>=5)||maversion>=6)
			bnssupport = true;;
		}
	if(!isIE){
		var netversion = uA.substring(uA.indexOf("Netscape"),uA.length);
		var netscapeversion = netversion.substring(netversion.indexOf("/")+1,netversion.length);
		var versionarray = netscapeversion.split('.');
		
		if(versionarray[0]>=7)
			bnssupport = true;
		else if(versionarray[0]==6&&(versionarray[1]>=1))
			bnssupport = true;
		}
	
	return bnssupport;
};
var bnssupport = checkbnssupport();
function toUTF (str) {
	if (!str || '' == str)
		return str;
	var len = str.length;
	var str1 = loadstring(str);
	if(bnssupport){
		return(encodeURIComponent(str1));
		}
	var outstr = '';
	for (var ix = 0; ix < len; ++ix) {
		var chcode = str1.charCodeAt(ix);
		if (chcode < 0x80) {	
			outstr += String.fromCharCode(chcode);
		}
		else if (chcode < 0x800) {		
			outstr += String.fromCharCode(0xc0 | (0x1f & (chcode >> 6)));
			outstr += String.fromCharCode(0x80 | (0x3f & (chcode)));
		}
		else if (chcode < 0x10000) {		
			outstr += String.fromCharCode(0xe0 | (0x0f & (chcode >> 12)));
			outstr += String.fromCharCode(0x80 | (0x3f & (chcode >> 6)));
			outstr += String.fromCharCode(0x80 | (0x3f & (chcode)));
		}
		else {	
			outstr += String.fromCharCode(0xf0 | (0x03 & (chcode >> 18)));
			outstr += String.fromCharCode(0x80 | (0x3f & (chcode >> 12)));
			outstr += String.fromCharCode(0x80 | (0x3f & (chcode >> 6)));
			outstr += String.fromCharCode(0x80 | (0x3f & (chcode)));
		}
	}
	return escape(outstr);
};

function fromUTF (str) {
	if (!str || '' == str)
		return str;
	if(bnssupport){
		return(decodeURIComponent(str));
			}
	str = unescape(str);
	var len = str.length;
	var outstr = '';
	var c1, c2, c3, c4;
	for (var ix = 0; ix < len;) {
		c1 = 0xff & str.charCodeAt(ix++);
		var chcode = c1;
		if (c1 < 0x80) {
			;
		}
		else if ((0xc0 == (c1 & 0xe0)) && (ix < len)) {
			c2 = 0xff & str.charCodeAt(ix++);
			chcode = ((c1 & 0x1f) << 6);
			chcode |= (c2 & 0x3f);
		}
		else if ((0xe0 == (c1 & 0xf0)) && (ix+1 < len)) {
			c2 = 0xff & str.charCodeAt(ix++);
			c3 = 0xff & str.charCodeAt(ix++);
			chcode = ((c1 & 0x0f) << 12);
			chcode |= ((c2 & 0x3f) << 6);
			chcode |= (c3 & 0x3f);
		}
		else if ((0xf0 == (c1 & 0xf8)) && (ix+2 < len)) {
			c2 = 0xff & str.charCodeAt(ix++);
			c3 = 0xff & str.charCodeAt(ix++);
			c4 = 0xff & str.charCodeAt(ix++);
			chcode = ((c1 & 0x03) << 18);
			chcode |= ((c2 & 0x3f) << 12);
			chcode |= ((c3 & 0x3f) << 6);
			chcode |= (c4 & 0x3f);
		}
		outstr += String.fromCharCode(chcode);
	}
	return outstr;
};

function displayObjAtt(path, filename, newwin) {
	var url = getBaseURL() + path + '/' + filename;
	window.resizeBy(500,450);
	location.replace(url);		
	return false;	
};

function getBaseURL () {
	var url = location.href;
	var pos = url.lastIndexOf('?');
	if (pos < 0)
		pos = url.length;
	pos = url.lastIndexOf('/',pos-1);
	return url.substring(0,pos+1);
};

function getHostURL () {
	var host = location.host;
	var protocol = location.protocol;
	return protocol + '//' + host + '/';
};

function displayReportFiles(path, filename, newwin) {
	var features = 'resizable=yes,scrollbars=yes,height=500,width=450';
	var url = getBaseURL() + path + '/' + filename;
	
	var win = window.open(url, newwin, features);
	if ( win != null )  
		win.focus();
	
	return false;	
};

function lookupFrameFromTop (frameName, frameTop) { 
	var win;
	if ( 'undefined' == typeof(frameTop) )
		win = window.top;
	else
		win = frameTop.window;

	return getFrameFromTop(win, frameName);
};

function getFrameFromTop (win, frameName) { 
	for (var ix = 0; ix < win.frames.length; ix++) {
		if (win.frames[ix].name == frameName) {
			return win.frames[ix];
		}
		else {
			var f = getFrameFromTop(win.frames[ix].window, frameName);
			if (f) {
				return f;
			}
		}
	}
	return null;
};

function getElement (id) {
	var elem = (document.all)?document.all[id]:document.getElementById(id);
	if ( 'undefined' == typeof(elem) )  {
		if ( this.name == 'AxObjectMain' ) {
			elem = parent.document.getElementById(id);
		}
		var ifrmMain = this.frames['AxObjectMain'];
		if ( 'undefined' != typeof(ifrmMain) && ifrmMain != null )  {
			elem = ifrmMain.document.getElementById(id);
		}
	}

	return ('undefined' == typeof(elem)) ? null : elem;
};

function getFirstClass (sClassName) {

	if (null==sClassName || '' == sClassName || 'undefined' == typeof(sClassName))
		return sClassName;
	
	var localArray = sClassName.split(' ');
	if (localArray.length<=1)
		return sClassName;
	else
		return localArray[0];
};

function updateWinTitle () {
	if (top && top.document)
		top.document.title = document.title;

	setNewWindowState();
	m_baseURL = getBaseURL();
};

function initBlank()  {
	if ( window.name == 'frm_formarea' )
		updateWinTitle();
	else if ( window.opener != null || typeof(window.opener) != 'undefined' ) {
		if ( setNewWindowState() )
			setTimeout('closeWindowByName(' + top.window.name + ');', 300);
	}
};


// XLT
 var confirmDiscardLabel = 'Changes/Edits made to the form will be discarded?';



function frmSubmit (name, value, row, col) {
	var okfrompopup;
	ev = window.event;
	if('undefined' != ev && null != ev && isIE)
		setCurrentElem(ev);
	var form;
	if('undefined' != window.opener && null != window.opener && window.name == 'ifrm' )
	{
		form = window.opener.document.forms['ent_form'];
		maindoc = window.opener.document;
	}
	else
	{
		form = document.forms['ent_form'];
		var maindoc =window.document;
	}
	
	if ('handleAsyncTimeout' == value ) {
		if ( 'handleAsyncTimeout' == name ){
			var mainfrm = lookupFrame('frm_formarea');
			if (mainfrm != null)
				form = mainfrm.window.document.forms['ent_form'];
			if('undefined' == form || null == form){
				url = "w2k_form_handler.asp?"; 
				url += 'name=' + toUTF(name);
				url += '&value=' + toUTF(''+value);
				url += '&row=' + escape((null == row) ? '' : row);
				url += '&col=' + escape((null == col) ? '' : col);
				location.replace(url);

				}
			}
	}	
	
	if (!useClientEvent())
	{
		if('frm_clear' == name  || 'frm_cancel' == name || 'frm_new' == name || 'cancel' == name)
		{
			if ((null != form.modified) && ('0' != form.modified.value)) {
				var discard = confirm(confirmDiscardLabel);
				if (!discard)
					return;
			}
			if('frm_new' != name && 'frm_clear' != name){
				if ( (isPopUp == 'true') && (top.window.opener != null || typeof(top.window.opener) != 'undefined' )) {
					top.window.close();
				}
			}
		}
		if('frm_ok' == name )
		{
			if ( (isPopUp == 'true')) {
				okfrompopup = 'true';
			}
		}
	}
	if('undefined' == form || null == form)
		return;
	form.ctrlName.value = name;
	form.ctrlValue.value = value;
	form.ctrlRow.value = (null == row) ? '' : row;
	form.ctrlCol.value = (null == col) ? '' : col;
	if (!isIE) {
		form.method='Post';
		form.target="";
	}
	var handler;
	if ('undefined' != typeof(formHandler)) 
		handler = formHandler;
	else
		handler = form.action;
		
	var url = getBaseURL() + handler + '?';
	
	url += 'uid=' + form.uid.value;
	url += '&name=' + toUTF(name);
	url += '&value=' + toUTF(''+value);
	url += '&row=' + escape((null == row) ? '' : row);
	url += '&col=' + escape((null == col) ? '' : col);
	if ( okfrompopup == 'true'){
		url += '&okfrompopup=' + okfrompopup;
	}

	if (url.length > 1000)
	{
		waitingForResponse = true;
		frmMake(name, value, row, col) ;
	}
	else {

		if ( useClientEvent() ) {
			var uid = form.uid.value;
			processClientAction(uid, 'formreplace', name, value, row, col, window);
			return;
		}

		waitingForResponse = true;
		if (this.name == 'AxObjectMain' )
			parent.location.replace(url);
		else
			location.replace(url);
	}
};

function BreakItUp(name,val)
{
   
  var FormLimit = 102350

  var TempVar = new String
  var form = document.forms['ent_form'];

  TempVar = val;

  if (TempVar.length > FormLimit)
  {
    
    form.ctrlValue.value  = TempVar.substr(0, FormLimit)
    TempVar = TempVar.substr(FormLimit)

    while (TempVar.length > 0)
    {
      var objTEXTAREA = form.document.createElement("TEXTAREA")
      objTEXTAREA.style.visibility = 'hidden' 
      objTEXTAREA.name = "ctrlValue"
      objTEXTAREA.value = TempVar.substr(0, FormLimit)
      form.appendChild(objTEXTAREA)
      TempVar = TempVar.substr(FormLimit)
    }
  }

};

function frmMake(name, value, row, col) {
	
	var form = document.ent_form;
	form.ctrlName.value = name;
	form.ctrlValue.value = value;
	form.ctrlRow.value = (null == row) ? '' : row;
	form.ctrlCol.value = (null == col) ? '' : col;
	BreakItUp(name,value);
	var newleft = self.screenLeft;
	var newtop = self.screenTop;
	var sFeatures;
	sFeatures = 'left=' + newleft + ',top=' + newtop + ',';
	sFeatures += ' height=100, width=100,  menubar=no, scrollbars=no, titlebar=no, status=no';
	var uid = document.ent_form.uid.value;
	
	mywindow = window.open('','ifrm',sFeatures);
	
	var handler = valuechangeHandler;
	
	form.action=getBaseURL() + handler + '?query=scriptcommands';
	form.target = "ifrm";
	form.acceptCharset = "utf-8";	
	form.submit();
	
	setTimeout('processNextEventi()',0);
	
	
};

function updateiframevalues(visibleFormId)
{
if('undefined' != window.opener && null != window.opener)
{
	var form = window.opener.document.forms['ent_form'];
	maindoc = window.opener.document;
}
else
	{var form = document.forms['ent_form'];
	var maindoc = window.document;}

	var ewobj = document.getElementsByTagName('area');
			
		if (null != ewobj && ('undefined' != typeof(ewobj))&& ewobj.length>0) {
			var node = ewobj.item(0);
			if ('3' == node.getAttribute('type')) {
					
					form.ctrlName.value = 'frm_cancel';
					form.ctrlValue.value = '';
					form.ctrlRow.value = '';
					form.ctrlCol.value = '';
					form.uid.value = node.getAttribute('objid');
					form.target = '';
					form.submit();
					window.status = window.defaultStatus = '';
					return;
					}
				}
	var nodes=document.getElementsByTagName('input');
	
	var node=nodes.item(0);
	var id=node.getAttribute('id');
	
	var docstate = 0;
	window.status = window.defaultStatus = '';
	
	for (var ix = 0; ix < nodes.length; ++ix) {
		var node = nodes.item(ix);
		var id = node.getAttribute('id');
		var ctrl = null;
		if (null != id)
			{
			if('undefined' != window.opener && null != window.opener)
				ctrl = window.opener.document.getElementById(id);
			else
				ctrl = document.getElementById(id);
				}
		var attr = null;
		if (null == ctrl) {
			if ('1' == node.getAttribute('iserror')) {
				attr = fromUTF(node.getAttribute('value'));
				alert(attr);
				eventqueue = new Array();		
				waitingForResponse = false;
				frmSubmit('error_ok',null,null,null);
				return;
			}
			else if ('1' == node.getAttribute('isscript')) {
				attr = node.getAttribute('value');
				if (null != attr) {
					attr = fromUTF(attr);
					eval(attr);
				}
			}
			else if (null != (attr = node.getAttribute('ismodified'))) {
			
				if (null != maindoc.ent_form && null != maindoc.ent_form.modified)
					maindoc.ent_form.modified.value = attr;
				if (null != (attr = node.getAttribute('value'))) {
					maindoc.title = fromUTF(attr);
					if (top && top.document)
						top.document.title = document.title;
						
				}
			}
			continue;
		}
		if (null == ctrl.style && ctrl.length > 0 && 'radio' == ctrl[0].type) {
			var radiogrp = ctrl;
			var radioval = node.getAttribute('value')-0;
			for (var rx = 0; rx < radiogrp.length; ++rx) {
				setCtrlStyleAttrs(radiogrp[rx],node);
				radiogrp[rx].checked = (rx == radioval);
			}
			continue;
		}
		attr = node.getAttribute('strings');
		if (null != attr) {
			var longstr = fromUTF(attr);
			var strs = longstr.split('\n');
			if ('ewlist' == ctrl.className || 
                'ewcombo' == ctrl.className ||
				'ewcellcombo' == ctrl.className ||
                'ewcomboreadonly ewcombo') {
				var numopts = ctrl.options.length;
				for (var ox = numopts-1; ox >= 0; --ox)
					ctrl.options.remove(ox);
					for (ox = 0; ox < strs.length; ++ox) {
						var opt = maindoc.createElement("OPTION");
						opt.text = strs[ox];
						opt.value = strs[ox];
						ctrl.options.add(opt);
							}
						}
			}
		attr = node.getAttribute('value');
		
		if (null != attr && "" != attr) {
		
			var value = fromUTF(attr);
			switch (getFirstClass(ctrl.className)) {
			case 'ewlabel':
			case 'ewtable':
			case 'ewdatasheet':
			case 'ewhyperlink':
			case 'ewpicture':
				setPostWindowCtrlText(ctrl,value);
				break;
			case 'ewimgbutton':
				break;
			case 'ewcheckbutton':
			case 'ewcheckbuttonreadonly':
				value = 0-value;
			default:
				setPostWindowCtrlValue(ctrl,value);
				break;
			}
		}
	

	}
	window.close();	
};	


function frmCtrlValue (ctrl) {
	switch (ctrl.type) {
	case 'radio':
		if(isIE) {
			var objMain = window.frames['AxObjectMain'];
			if ( objMain != null )
				var grp = objMain.window.document.all[ctrl.name];
			else
				var grp = document.all[ctrl.name];
		}
		else
			var grp = ctrl.form[ctrl.name];
		var grplen = grp.length;
		for (var ix = 0; ix < grplen; ++ix) {
			if (grp[ix].checked)
				return ""+ix;
		}
		return ""+(-1);
	case 'checkbox':
		return (ctrl.checked) ? "1" : "0";
	case 'select-one':
	case 'select':
		if (ctrl.className&&0<=ctrl.className.indexOf('ewcomboe'))
			return "" + ctrl.value;
		else
			return "" + ctrl.selectedIndex;
	case 'select-multiple':
		var value = "";
		grplen = ctrl.options.length;
		for (ix = 0; ix < grplen; ++ix) {
			if (ctrl.options[ix].selected) {
				if ("" != value)
					value += ",";
				value += ix;
			}
		}
		return value;
	}
	if(ctrl.className == "ewrichtexthtml"){
		if (parent.document.getElementById("divrtf") != null || document.getElementById("divrtf") != null)
		{
			var oRTE = frames[ctrl.id].document;
			var val;
			if (oRTE != null && oRTE.body != null)
				val = oRTE.body.innerHTML;
			return val;
		}
	}

	return ctrl.value;
};

var checkMessageInterval = 0;
var firstElement = null;
var asyncMessageHandler = null;
var valuechangeHandler = null;
var queryDetailsHandler = null;
var datatreeDetailsHandler = null;
var errorBeepURL = null;
var waitMessage = '';
var isPopUp = '';
var selectedRow = '';
var selgrid = '';

var checkmsghandle = null;
var eventqueue = new Array();

function isSelectCtrl (el) {
	return (el && ('ewlist' == getFirstClass(el.className) || 'select-multiple' == el.type));
};

function ewevent (ev) {
	if (null == ev)
		ev = window.event;
	if (!isIE) {
		var elem = ev.target;
		this.ewevent = true;
		this.target = elem;
		this.type = ev.type;
		this.which = ev.which;
	} else {
		var elem = ev.srcElement;
		this.ewevent = true;
		this.srcElement = elem;
		this.type = ev.type;
		this.keyCode = ev.keyCode;
	}
	this.shiftKey = ev.shiftKey;
	this.ctrlKey = ev.ctrlKey;
	if (isSelectCtrl(elem)) {
		this.selectvalue = frmCtrlValue(elem);
	}
};

ewevent.prototype.process = function () {
	switch (this.type) {
	case 'click':
		return handleclick(this);
	case 'change':
		return handlechange(this);

	}
};

function addEventToQueue (ev) {
	if (!ev)
		ev = window.event;
	if (!ev || ev.ewevent)
		return;
	var eltype;
	if (!isIE)
		eltype = (ev.target) ? ev.target.type : '';
	else
		 eltype = (ev.srcElement) ? ev.srcElement.type : '';
	switch (ev.type) {
	case 'button':
		if (!isIE)
			eventqueue[eventqueue.length] = new ewevent(ev);
		return;
	case 'click':
	case 'change':
		if (!eventqueue.length) {
			eventqueue[eventqueue.length] = new ewevent(ev);
			return;
		}
		setTimeout('beep(1)',0);
		break;
	case 'keyup':
		if ('text' == eltype || 'textarea' == eltype || 'password' == eltype)
			setTimeout('beep(1)',0);
		break;
	}
};

function processNextEvent () {
	if (!eventqueue.length)
		return false;
	var ev = eventqueue[0];
	eventqueue = eventqueue.slice(1);
	ev.process();
	return true;
};
function processNextEventi () {
	waitingForResponse = false;
	if (!eventqueue.length)
		return false;
	var ev = eventqueue[0];
	eventqueue = eventqueue.slice(1);
	
	ev.process();
	return true;
};
function processPendingEvents () {
		setTimeout('beep(0)',0);
		if(isIE){
		while (eventqueue.length > 0 && !waitingForResponse)
		processNextEvent();}
		else{
		while (eventqueue.length > 0 && waitingForResponse)
		processNextEvent();
		waitingForResponse = false;
		}
};

function setCtrlStyleAttrs (ctrl, node) {
	if (null == ctrl || null == ctrl.style)
		return;
	var attr = null;
	if (null != (attr = node.getAttribute('hidden'))) {
		if ('0' != attr && '' != attr)
			ctrl.style.visibility = 'hidden';
		else if ('hidden' == ctrl.style.visibility)
			ctrl.style.visibility = '';
	}
	if (null != (attr = node.getAttribute('color')))
		if (ctrl.className.indexOf('ewcheck')>=0)
			ctrl.parentNode.style.color = fromUTF(attr);
		else
			ctrl.style.color = fromUTF(attr);
	if (null != (attr = node.getAttribute('background'))){
		if (ctrl.className.indexOf('ewradiobutton')>=0||ctrl.className.indexOf('ewcheck')>=0)
			ctrl.parentNode.style.backgroundColor = fromUTF(attr);
		else
			ctrl.style.backgroundColor = fromUTF(attr);
	}
	if (null != (attr = node.getAttribute('font-size')))
		ctrl.style.fontSize = fromUTF(attr);
	if (null != (attr = node.getAttribute('font-weight')))
		ctrl.style.fontWeight = fromUTF(attr);
	if (null != (attr = node.getAttribute('font-style')))
		ctrl.style.fontStyle = fromUTF(attr);
	if (null != (attr = node.getAttribute('font-face')))
		ctrl.style.fontFamily = fromUTF(attr);
	if (null != (attr = node.getAttribute('bitmap')))
		ctrl.style.backgroundImage = fromUTF(attr);

	attr = node.getAttribute('readonly');
	if ((null!=attr)&&(''!=attr)){
		setCtrlReadOnly(ctrl,('0' != attr));
	}
	attr = node.getAttribute('disabled');
	if ((null!=attr)&&(''!=attr))
	{
		setCtrlDisabled(ctrl,('0' != attr));
	}
};

function isHidden (elem) {
	if (elem && 'string' == typeof(elem))
		elem = getElement(elem);
	if (!elem)
		return true;
	for (;elem && 1 == elem.nodeType; elem = elem.parentNode) {
		if (elem.style && ('hidden' == elem.style.visibility || 'none' == elem.style.display))
			return true;
	}
	return false;
};

var currentElem = null;

function frmHandleValChange (cname, ctrl, row, col) {
	if (!isChangeable(ctrl) && !isWorkflowButton(ctrl) )
		return false;
	if(document.getElementById(cname)&&document.getElementById(cname).className&&
		0<=document.getElementById(cname).className.indexOf('ewcombotext'))
		cname=cname.substr(0,cname.length-1);

	if ( useClientEvent() ) {
		var uid = -1;
		if (null != document.ent_form && null != document.ent_form.uid)
			uid = document.ent_form.uid.value;

		processClientAction(uid, 'valuechange', cname, frmCtrlValue(ctrl), row, col);
		return true;
	}

	return frmGetXMLValues(cname,frmCtrlValue(ctrl),row,col);
};

function isWorkflowButton(ctrl) {
	if ( !useClientEvent() )
		return false;

	if (!ctrl || !ctrl.id)
		return false;

	var clsname = ctrl.className;
	if ( clsname != null && clsname.indexOf('ewwflbutton') >= 0 )
		return true;

	return false;
};

function frmRefresh () {
	return frmGetXMLValues('','','','');
};

function frmValChange (ctrl) {
	if (isDialogPending(null))
		return false;
	if (false == frmHandleValChange(ctrl.name,ctrl,'',''))
		frmSubmit(ctrl.name,frmCtrlValue(ctrl),null,null);

	return false;
};

function cellValChange (sprd, ctrl, row, col) {
	if (isDialogPending(null))
		return false;
	if (false == frmHandleValChange(sprd,ctrl,row,col))
		frmSubmit(sprd,frmCtrlValue(ctrl),row,col);

	return false;
};

var helpwindow = null;

function showCtrlHelp (helpurl) {
	var url = helpurl.toLowerCase();
	if (null == helpwindow || helpwindow.closed) {
		var features = 'resizable=yes,scrollbars=yes,height=500,width=450';
		helpwindow = window.open('','Help',features);
	} 
	helpwindow.location.href = getBaseURL() + url;
	helpwindow.focus();
	return false;
};

function setCtrlReadOnly (ctrl,readonly) {
	if (readonly == ctrl.readOnly)
		return;
	if(isMac && isIE)
		readonly = !readonly;
	var clsname = getFirstClass(ctrl.className);
	if(clsname!='ewcombo'&&clsname!='ewlist'&&clsname!='ewradio'&&clsname!='ewbutton'&&clsname!='ewimgbutton')
		ctrl.readOnly = readonly;
	if(clsname=='ewbutton'||clsname=='ewimgbutton'||
		clsname=='ewbuttonreadonly'||clsname=='ewimgbuttonreadonly')
		ctrl.disabled=readonly;
	if(clsname=='ewradio'){
		var objChildNode = null;
		for (var i=0;i<ctrl.childNodes.length;i++) {
			objChildNode = ctrl.childNodes[i];
			if (objChildNode.className&&0<=objChildNode.className.indexOf('ewradiobutton'))
				setCtrlDisabled(objChildNode,readonly);
		}
		return true;
	}
	if (!clsname || 0 != clsname.indexOf('ew'))
		return;
	var clsnames = clsname.split(' ');
	if (null != clsnames && clsnames.length > 1)
		clsname = clsnames[0];
	if (false == readonly) {
		if (clsname.indexOf('readonly') > 0)
			clsname = clsname.replace('readonly','');
	}
	else {
		if (-1 == clsname.indexOf('readonly'))
			clsname += 'readonly';
	}
	ctrl.className = clsname;
};

function setCtrlDisabled (ctrl,disabled) {
	if (disabled == ctrl.disabled)
		return;
	if(isMac && isIE)
	disabled = !disabled;
	var clsname = getFirstClass(ctrl.className);
	ctrl.disabled = disabled;
	if(clsname.indexOf('ewcheckbutton')>=0){
		if(ctrl.parentNode.className.indexOf('ewcheckdiv')>=0)
			ctrl.parentNode.disabled = disabled;
	}
	if(clsname=='ewradio'){
		var objChildNode = null;
		for (var i=0;i<ctrl.childNodes.length;i++) {
			objChildNode = ctrl.childNodes[i];
			if (objChildNode.className&&0<=objChildNode.className.indexOf('ewradiobutton'))
				setCtrlDisabled(objChildNode,disabled);
		}
	}
	if (!clsname || 0 != clsname.indexOf('ew'))
		return;
	var clsnames = ctrl.className.split(' ');
	if (null != clsnames && clsnames.length > 1)
		clsname = clsnames[0];
	if (false == disabled) {
		if (clsname.indexOf('readonly') > 0)
			clsname = clsname.replace('readonly','');
		if(clsnames.length>0){
			for(var idx=1;idx<clsnames.length;idx++){
				if(clsnames[idx].indexOf('readonly')==-1)
					clsname+=' '+clsnames[idx];
			}
		}
	}
	else {
		if (-1 == clsname.indexOf('readonly'))
			clsname += 'readonly';
	}
	ctrl.className = clsname;
};

function setCtrlAttr (id,name,value) {
	var ctrl = getElement(id);
	if (null == ctrl)
		return;
	switch (name) {
	case 'readonly':
		setCtrlReadOnly(ctrl,value);
		break;
	case 'disabled':
		setCtrlDisabled(ctrl,value);
		break;
	}
};

function setActiveTab (id) {
	var elem = getElement(id);
	if (null != elem)
		showTab(elem);
};

function setCtrlStyle (id, name, value) {
	var ctrl = getElement(id);
	if ((null == ctrl) || ('undefined' == typeof(ctrl.style)) ||
		(ctrl.style[name] == value))
		return;
	ctrl.style[name] = value;
};

function setCtrlText (id, value, currentctrlidval) {
	var ctrl = getElement(id);
	if (null == ctrl)
		return;
	if (getFirstClass(ctrl.className) == "ewhyperlink")
		ctrl.outerHTML = value;
	else
	{
		ctrl.innerHTML = value;
		if (currentctrlidval != null)
			setFirstElement (currentctrlidval, false)
	}
};

function setPostWindowCtrlText (ctrl, value) {
	if (null == ctrl)
		return;
	if (getFirstClass(ctrl.className) == "ewhyperlink")
		ctrl.outerHTML = value;
	else
		ctrl.innerHTML = value;
};
function setCtrlHTML (id, value) {
	var ctrl = getElement(id);
	if (null == ctrl)
		return;
	ctrl.outerHTML = value;
};

function setCtrlValue (id, value) {
	var ctrl = getElement(id);
	if (null == ctrl)
		return;
	if(ctrl.className == "ewcombotext" || ctrl.className == "ewcomboe")
	{
		initComboEText(id, value);
		return;
	}
	if(ctrl.className == "ewrichtexthtml" || ctrl.className == "ewrichtexthtmlreadonly"){
		if (parent.document.getElementById("divrtf") != null || document.getElementById("divrtf") != null)
			{
			enableDesignMode(id, value, ctrl.readOnly);
			var info = getCtrlInfo(ctrl.id);
			if (null == info)
				setCtrlInfo(ctrl.id,'',false);
			else
				info.elemValue = frmCtrlValue(ctrl);
			return;
			}
	}
	switch (ctrl.type) {
	case 'checkbox':
		ctrl.checked = value;
		break;
	case 'radio':

		if(isIE) {
			var objMain = window.frames['AxObjectMain'];
			if ( objMain != null )
				var grp = objMain.window.document.all[ctrl.name];
			else
				var grp = document.all[ctrl.name];
		}
		else 
			var grp = ctrl.form[ctrl.name];
		for (var ix = 0; ix < grp.length; ++ix)
			grp[ix].checked = (ix == value);
		break;
	case 'select-one':
	case 'select':
		ctrl.selectedIndex = value-0;
		break;
	case 'select-multiple':
		var options = ctrl.options;
		for (ix = 0; ix < options.length; ++ix) {
			options[ix].selected = false;
		}
		if (!value)
			break;
		var valuearray = value.split(",");
		for (ix = 0; ix < valuearray.length; ++ix) {
			var dex = valuearray[ix];
			if (dex >= 0 && dex < options.length)
				options[dex].selected = true;
		}
		break;
	default:
		ctrl.value = value;
		break;
	}
	var info = getCtrlInfo(ctrl.id);
	if (null == info)
		setCtrlInfo(ctrl.id,'',false);
	else
		info.elemValue = frmCtrlValue(ctrl);
};

function setPostWindowCtrlValue (ctrl, value) {
	
	if (null == ctrl)
		return;
	if(ctrl.className == "ewcombotext" || ctrl.className == "ewcomboe")
	{
		initComboEText(id, value);
		return;
	}	
	switch (ctrl.type) {
	case 'checkbox':
		ctrl.checked = value;
		break;
	case 'radio':

		if(isIE) {
			var objMain = window.frames['AxObjectMain'];
			if ( objMain != null )
				var grp = objMain.window.document.all[ctrl.name];
			else
				var grp = document.all[ctrl.name];
		}
		else 
			var grp = ctrl.form[ctrl.name];
		for (var ix = 0; ix < grp.length; ++ix)
			grp[ix].checked = (ix == value);
		break;
	case 'select-one':
	case 'select':
		ctrl.selectedIndex = value-0;
		break;
	case 'select-multiple':
		var options = ctrl.options;
		for (ix = 0; ix < options.length; ++ix) {
			options[ix].selected = false;
		}
		if (!value)
			break;
		var valuearray = value.split(",");
		for (ix = 0; ix < valuearray.length; ++ix) {
			var dex = valuearray[ix];
			if (dex >= 0 && dex < options.length)
				options[dex].selected = true;
		}
		break;
	default:
		ctrl.value = value;
		break;
	}
	var info = getCtrlInfo(ctrl.id);
	if (null == info)
		setCtrlInfo(ctrl.id,'',false);
	else
		info.elemValue = frmCtrlValue(ctrl);
};

var comboList = new Array();

function initComboValue (id, value) {
	comboList[comboList.length] = [id,value];
};

function updateComboValues () {
	for (var ix = 0; ix < comboList.length; ++ix) {
		var elem = comboList[ix];
		setCtrlValue(elem[0],elem[1]);
	}
};
function initComboEText(elem,value){

	var ctrl = getElement(elem);
	var txtctrl = getElement(elem+'E');
	if(null!=ctrl&&null!=txtctrl) {
		if(isNaN(value)){
			if(null!=ctrl&&null!=txtctrl) {
				if(ctrl.options.length>=0){
					for (var ix=0;ix<ctrl.options.length;ix++) {
						if (ctrl.options[ix].selected) {
							txtctrl.value=ctrl.value;
						}
					}
				}
			}
		} else {
			if(ctrl.options.length>=0){
				ctrl.options[value].selected = true;
				txtctrl.value = ctrl.value;
			}
		}
	}
};

function updateSelectDisplay() {

	var objSelectObjects = document.getElementsByTagName('SELECT');
	if (objSelectObjects&&objSelectObjects.length>=0){
		for (var i=0;i<objSelectObjects.length;i++){
			if (0<=objSelectObjects[i].className.indexOf('readonly')){
				objSelectObjects[i].disabled = false;
			}
		}
	}
};

var msgdlg = null;

function closeMessageDialog () {
	if (null != msgdlg)
		msgdlg.close();
};

function dlgctrl (id,type,value,action) {
	if (null == id)
		id = value;
	this.id = id;
	this.type = type;
	this.value = value;
	this.action = action;
	if ('entry' == type) {
		this.size = 8;
		this.maxlength = 32;
	}
};

dlgctrl.prototype.execute = function () {
	if (null != this.action)
		return eval(this.action);
};

dlgctrl.prototype.htmlstr = function () {
	var hstr = '';
	switch (this.type) {
	case 'button':
		hstr += '<button class="ewdialogbutton" id="'+this.id+'">'+this.value+'</button>';
		break;
	case 'entry':
		hstr += '<input class="ewdialogentry" type="text" id="' + this.id + '" value="' + this.value + '" size="' + this.size + '" maxlength="' + this.maxlength + '">';
	case 'label':
	default:
		hstr += '<label class="ewdialoglabel" id="'+this.id+'">'+this.value+'</label>';
		break;
	}
	return hstr;
};

function messageDialog (type, msg, title, ctrls) {
	this.type = type;
	this.title = title;
	this.body = new Array();
	if (null != msg)
		this.body[0] = new dlgctrl(null,'label', msg, null);
	if (null == ctrls) {
		ctrls = [new dlgctrl(null,'button','OK','closeMessageDialog();')];
	}
	this.ctrls = ctrls;
	this.open();
};

messageDialog.prototype.addToBody = function (ctrl) {
	if (null == this.body)
		this.body = new Array();
	this.body[this.body.length] = ctrl;
};

messageDialog.prototype.open = function () {
	closeMessageDialog();
	msgdlg = this;
};

messageDialog.prototype.execute = function (elem) {
	var ctrls = this.ctrls.concat(this.body);
	for (ix = 0; ix < ctrls.length; ++ix) {
		var ctrl = ctrls[ix];
		if (elem.id == ctrl.id)
			return ctrl.execute();
	}
	return false;
};

messageDialog.prototype.close = function () {
	msgdlg = null;
};

function infoMessage (msg) {
	new messageDialog('info',msg,'Information',null);
};

function alertMessage (msg) {
	new messageDialog('alert',msg,'Alert',null);
};

function postMessage (msg, ispended) {
	new messageDialog('post',msg,'Message',null);
};

function errorMessage (msg) {
	new messageDialog('error',msg,'Error',null);
};

function confirmDialog (msg,yesaction,noaction,cancelaction) {
	var ctrls = new Array(3);
	ctrls[0] = new dlgctrl(null,'button','Yes',yesaction);
	ctrls[1] = new dlgctrl(null,'button','No',noaction);
	ctrls[2] = new dlgctrl(null,'button','Cancel',cancelaction);
	new messageDialog('confirm',msg,'Confirm',ctrls);
};

function beep (loop) {
	var beeper = getElement('errorbeeper');
	if (!beeper)
		return;
	if (!loop) {
		beeper.loop = 0;
	}
	else {
		if (beeper.loop < 2)
			beeper.loop += loop;
		beeper.src = errorBeepURL;
	}
};

function isDialogPending (ev) {
	if (null == ev)
		ev = window.event;
	if (isIE) {
		if ('complete' != document.readyState || waitingForResponse) {
			addEventToQueue(ev);
			if (ev)
				ev.returnValue = false;
			return true;
		}
		if (null == msgdlg)
			return false;
		if (ev)
			ev.cancelBubble = true;
		var elem = ev.srcElement;
	} else {
		if (waitingForResponse) {
			addEventToQueue(ev);
			if (ev)
				ev.returnValue = false;
			return true;
		}
		if (null == msgdlg)
			return false;
		if (ev)
			ev.cancelBubble = true;
		var elem = ev.target;
	}
	switch (ev.type) {
	case 'click':
		msgdlg.execute(elem);
		break;
	case 'keyup':
		break;
	}
	return true;
};

var ctrlinfo = new Array();
var ssinfo = new Array();

function getsscell (elem) {
	if (null == elem)
		return null;
	switch (getFirstClass(elem.className)) {
	case 'ewcellcheckbutton':
	case 'ewcelltextfield':
	case 'ewcellcombo':
		var namear = elem.id.split('_');
		if (null != namear && 3 == namear.length) {
			var parent = namear[0];
			var row = 1*namear[1];
			var col = 1*namear[2];
			if (null != ssinfo[parent]) {
				var cell = ssinfo[parent][col];
				if (null != cell) {
					return ({parent:parent, row:row, col:col, mask:cell.mask});
				}
			}
		}
	}
	return null;
};

function nameoffunc (f) {
	var nm = f.toString();
	if (nm.indexOf(')') > 0)
		nm = nm.substring(0,nm.indexOf(')')+1);
	return (null == nm || 0 == nm.length) ? 'anonymous' : nm;
};

function printstacktrace (pre) {
	var s = (null != pre) ? pre+'\n' : '';
	var ix = 1;
	for (var c = arguments.caller; null != c; c = c.caller) {
		s += '  ' + ix + '. ' + nameoffunc(c.callee) + '\n';
		if (c == c.caller)
			break;
		++ix;
	}
	return s;
};

function getCtrlInfo (name) {
	var info = null;

	var objMain = window.frames['AxObjectMain'];
	if ( objMain != null ) 
		info = objMain.ctrlinfo[name];
	else
		info = ctrlinfo[name];

	return info;
};

function setCtrlInfo (name, maskstr, hasAction) {
	if (null == name)
		return;
	var info = getCtrlInfo(name);
	if (null == info)
		info = new eweditmask(maskstr);
	else
		info.setMask(maskstr);
	var elem = getElement(name);
	info.elemValue = (null != elem) ? frmCtrlValue(elem) : null;
	info.sscell = getsscell(elem);
	if (null != info.sscell)
		info.setMask(info.sscell.mask);
	info.hasAction = hasAction;
	var objMain = window.frames['AxObjectMain'];
	if ( objMain != null ) 
		objMain.ctrlinfo[name] = info;
	else
		ctrlinfo[name] = info;
};

function setCellEditMask (name, mask, parent, row, col) {
	if (null != name) {
		setCtrlInfo(name,mask,false);
		if (null == ssinfo[parent])
			ssinfo[parent] = new Array();
		var info = getCtrlInfo(name);
		info.sscell = {parent:parent, row:row, col:col, mask:mask};
		ssinfo[parent][col] = {parent:parent, row:row, col:col, mask:mask};
	}
};

function ctrlValChange (elem) {
	if (!elem || !arguments.length) {
		var ev = window.event;
		if (!ev)
			return;
		var elem = currentElem;
		var info = (elem && elem.id) ? getCtrlInfo(elem.id) : null;
		if (elem && (null == info || info.elemValue != frmCtrlValue(elem))) {
			addEventToQueue(ev);
			ctrlValChange(elem);

			if ( useClientEvent() )	
				processNextEvent();
			return;
		}
		if (isIE)
			elem = ev.srcElement;
		else
			elem = ev.target;
	}
	if (!elem || !elem.id)
		return;
	var info = getCtrlInfo(elem.id);
	if (!info)
		return;
	var cell = info.sscell;
	if (cell)
		cellValChange(cell.parent,elem,cell.row,cell.col);
	else
		frmValChange(elem);
};

function initCtrlValue (elem) {
	if (!isChangeable(elem))
		return;
	var info = getCtrlInfo(elem.id);
	if (null == info)
		setCtrlInfo(elem.id,'',false);
	else if (null == frmCtrlValue(elem))
		info.elemValue = frmCtrlValue(elem);
	if (('ewlist' == getFirstClass(elem.className) || 'ewcombo' == getFirstClass(elem.className) ||
		 'ewcellcombo' == getFirstClass(elem.className) ||'ewcomboe' == getFirstClass(elem.className)) && !elem.onchange) {
		elem.onchange = ctrlValChange;
		elem.onchanger = 1;
	}
};
function setCtrlChanger(elem) {
	if (!isChangeable(elem))
		return;
	setCtrlInfo(elem.id,'',false);
	if (('ewlist' == getFirstClass(elem.className) || 'ewcombo' == getFirstClass(elem.className) ||
		 'ewcellcombo' == getFirstClass(elem.className))) {
		elem.onchange = ctrlValChange;
		elem.onchanger = 1;
	}
	return;
};
function setCurrentElem (ev) {
	var elem;
	if (isIE)
		elem = ev.srcElement;
	else
		elem = ev.target;
	var info = null;
	var cell = null;
	return checkElemChange(elem,ev);
};

function checkElemChange(elem,ev) {

	if (elem.className == 'rteImage' || elem.className == 'rteImageLowered'  || elem.className == 'rteImageRaised') 
		return false;
	
	if (elem && currentElem)
		if (elem.id == currentElem.id) {
			currentElem = elem;
			return false;
		}
	var info = null;
	var cell = null;
	var curelem = currentElem;
	currentElem = elem;
	if (curelem && (curelem.onclick || curelem.onchange)) {
		if (1 == elem.onchanger && 'ewlist' == getFirstClass(elem.className) &&
			'select-multiple' != elem.type) {
			elem.onchanger++;
			if(null!=ev){
				if (null != ev.selectvalue)
					setCtrlValue(elem.id,ev.selectvalue);
			}
			ctrlValChange(elem);
		}
		if(null!=ev)
			ev.cancelBubble = false;
		currentElem = null;
		return true;
	}
	if (curelem && curelem != elem) {
		info = getCtrlInfo(curelem.id);
		if (null != info && info.elemValue != frmCtrlValue(curelem)) {
			ctrlValChange(curelem);
			return true;
		}
	}
	return false;
};

function handleonblur(elem) {
	if (elem) {
		if (elem && currentElem) {
			if (elem.id != currentElem.id) 
				return false;
		}
		info = getCtrlInfo(elem.id);
		if (null != info && info.elemValue != frmCtrlValue(elem)) {
			ctrlValChange(elem);
			setCtrlInfo(elem.id,'',false);
			return true;
		}
	}
	return false;
};

function handlechange (ev) {
	if (null == ev)
		return;
	var elem;
	if (isIE)
		elem = ev.srcElement;
	else
		elem = ev.target;
	if (isHidden(elem))
		return;
	if (!elem.onchange)
		return;
	if (isSelectCtrl(elem) && ev.selectvalue != frmCtrlValue(elem)) {
		setCtrlValue(elem.id,ev.selectvalue);
		ctrlValChange(elem);
	}
	currentElem = null;
};

function isChangeable (elem) {
	if (!elem || !elem.id)
		return false;
	return ('text' == elem.type || 'password' == elem.type || 'ewrichtexthtml' == elem.className ||
			'ewtextarea' == elem.className || 'textarea' == elem.type || 'select' == elem.type ||
			'select-one' == elem.type || 'select-multiple' == elem.type ||
			'radio' == elem.type || 'checkbox' == elem.type);
};
var isReport = false;

function MSIEVersion(){
	var uA = navigator.userAgent;
	var pos = uA.indexOf("MSIE");
	var version = uA.substring(pos + 5 , pos + 6)
	return version;
};

function updateEWForm () {
	if ('function' == typeof(updateEWFormValues))
		setTimeout('updateEWFormValues()',0);
	if (null != firstElement)
		setFirstElement(firstElement);
	else if(selectedRow != null && selectedRow != ""){
		id = "ROW" + "." + selectedRow;
		setFirstElement(id);
	}
	else
		findFirstElement();
	if (parent.document.getElementById("divrtf") != null || document.getElementById("divrtf") != null){
		enableDesignModeOnLoad();
	}
	if (checkMessageInterval > 0)
		checkmsghandle = setTimeout('checkMessages()',checkMessageInterval);

	if (top && top.document){	
			if(!isIE ){
				if(isReport){
					top.document.title = unescape(document.title);
				}
				else
					top.document.title = document.title;
			}
			else
				if ( MSIEVersion() > 5)
					top.document.title = document.title;
	}
	setNewWindowState();
};

function updateDBObject () {
	if ('function' == typeof(updateEWFormValues))
		setTimeout('updateEWFormValues()',0);

	if (null != firstElement)
		setFirstElement(firstElement);
	else
		findFirstElement();

	var form = document.ent_form;
	if ( form.modified != null )
		setObjectModified(form.uid.value, form.modified.value, document.title);
};

function setFirstElement (id, bFromDash) {
	if(id.indexOf("GRD") != -1){
		if (selgrid != null && selgrid != "")
			id += "." + selgrid;
	}
	var elem = document.getElementById(id);
	if (null != elem) {
			if (null != elem.focus && !isHidden(elem)) {
				if (!elem.readOnly && !elem.disabled) {
					if ( 'undefined' != typeof(bFromDash) && bFromDash )
						initCtrlValue(elem);
					else	
						elem.focus();
				}
			if ('text' == elem.type)
				elem.select();
			if((id.indexOf("GRD") != -1) || (id.indexOf("ROW") != -1)){
				elem.scrollIntoView(false);
			}
			var info = getCtrlInfo(id);
			if (null != info && null != info.sscell){
				elem.scrollIntoView(false);
				}
		}
	}
};

function findFirstElement (bFromDash) {
	var iLowestIndex = 1000;
		var ctrlLowest;
		var len;
		var iLoop;
		var elem;
		var nodes;
		var entfrm = document.forms['ent_form'];
		if ((null != entfrm) && ('undefined' != typeof(entfrm))) {
		
		var form = document.forms['visible_form_' + entfrm.uid.value];
		if ((null != form) && ('undefined' != typeof(form))) {
			
			if (isIE)
				{
				  len = document.all.length;
				  nodes = document.all;
				 }
			else
				{
				  nodes = form.elements;
				  len = nodes.length; 
				 }
			
			for (iLoop = 0; iLoop < len; iLoop++) {
				if (null != nodes[iLoop].tabIndex && 0 < nodes[iLoop].tabIndex) {
					elem = nodes[iLoop];
					switch (getFirstClass(elem.className)) {
					case 'ewtextfield':
					case 'ewcheckbutton':
					case 'ewlist':
					case 'ewcombo':
					case 'ewtextarea' :
					case 'ewcellcombo':
					case 'ewradiobutton':
					case 'ewcellcheckbutton':
						if (null != elem.focus && !isHidden(elem)) {
							if (!elem.readOnly && !elem.disabled)
								if (elem.tabIndex < iLowestIndex) {
									iLowestIndex = elem.tabIndex ;
									ctrlLowest = elem;
								}
						}
						break;
					case 'ewrichtexthtml' :
						if (null != elem.focus && !isHidden(elem)) {
							if (!elem.readOnly && !elem.disabled)
								if (elem.tabIndex < iLowestIndex) {
									iLowestIndex = elem.tabIndex ;
									ctrlLowest = elem;
								}
						}
						if (parent.document.getElementById("divrtf") != null || document.getElementById("divrtf") != null)
							enableDesignMode(elem.id, elem.innerHTML, elem.readOnly);
						break;

					}
				}
			}
				if ( ctrlLowest != null )
					if ( 'undefined' != typeof(bFromDash) && bFromDash )
						initCtrlValue(ctrlLowest);
					else
						ctrlLowest.focus();
			
		
		}
	}
};


function enableDesignModeOnLoad(){
		var len;
		var iLoop;
		var elem;
		var nodes;
		var entfrm = document.forms['ent_form'];
		if ((null != entfrm) && ('undefined' != typeof(entfrm))) {
			var form = document.forms['visible_form_' + entfrm.uid.value];
			if ((null != form) && ('undefined' != typeof(form))) {

				if (isIE)
					{
					  len = document.all.length;
					  nodes = document.all;
					 }
				else
					{
					  nodes = form.elements;
					  len = nodes.length; 
					 }

				for (iLoop = 0; iLoop < len; iLoop++) {
					if (null != nodes[iLoop].tabIndex && 0 < nodes[iLoop].tabIndex) {
						elem = nodes[iLoop];
						switch (getFirstClass(elem.className)) {
							case 'ewrichtexthtml' :
							case 'ewrichtexthtmlreadonly' :
							enableDesignMode(elem.id, elem.innerHTML, elem.readOnly);
							break;
							}
						}
					}
			}
		}
};
var messengerList = null;

function messenger (dex,elem) {
	this.dex = dex;
	this.element = elem;
	this.init();
};

messenger.prototype.init = function () {
	this.isbusy = false;
	this.deliverto = null;
	this.address = null;
};

messenger.prototype.run = function (url,deliverto,address) {
	this.isbusy = true;
	this.deliverto = deliverto;
	this.address = address;
	this.element.src = url+'&msrid='+this.dex;
	return this;
};

messenger.prototype.returned = function (code, data) {
	this.isbusy = false;
	var callfunc = this.deliverto;
	var arg = this.address;
	this.init();
	if (null != callfunc)
		callfunc(arg,code,data);
};

function initMessengers () {
	if (null != messengerList)
		return;
	messengerList = new Array();
	for (var ix = 0; ix < 8; ++ix) {
		var elem = getElement('messenger'+ix);
		if (null == elem)
			break;
		messengerList[ix] = new messenger(ix,elem);
	}
};

function pickMessenger () {
	initMessengers();
	for (var ix in messengerList) {
		var msr = messengerList[ix];
		if (msr.isbusy)
			continue;
		msr.isbusy = true;
		return msr;
	}
	return null;
};

function messengerReturn (mx, code, data) {
	if (null == messengerList)
		return;
	var msr = messengerList[mx];
	if (null != msr && msr.isbusy)
		msr.returned(code,data);
};

function getMessage (url,deliverto,address) {
	var msr = pickMessenger();
	if (null != msr) {
		return msr.run(url,deliverto,address);
	}
	return null;
};

function refreshdoc () {
	frmSubmit(null,null,null,null);
};

function asyncInfoMessage (str) {
	alert(str);	
};

function asyncPostMessage (mode,icon,title,body) {
	alert(body); 
};

function displayReport (displayer, objid) {
	var url = getBaseURL() + displayer + '?objid='+objid;
	var displayer = window.frames['msgDisplayer'];
	if ( displayer != null )
		displayer.location.replace( url );
	else{	
		var asyncframe = lookupFrame('asyncwin');
		var win;
		if(asyncframe != null){
				win = asyncframe.winlist[0];
			if(win && win != null && win != ""){
				win.location.replace( url );
				win.focus();
				asyncframe.winlist[0] = null;
				}
		}
		else
			location.replace(url);
	}
};

function displayExport (relPath, clientRef) {
	var features = 'resizable=yes,scrollbars=yes,menubar=yes,height=500,width=450';
	var url = getBaseURL() + relPath;
	var win = window.open(url, clientRef, features);

	if (null != win) {
		win.focus();
	}
};

function displayObject (displayer, objid, winname, enablePopup) {
	var features = 'resizable=yes,scrollbars=yes,height=500,width=450';
	var url;
	if ( enablePopup == "false"){
		url = getBaseURL() + displayer + '?objid='+objid +"&ispopup=false";
		var m_frame = getBaseFrame();
		m_frame.window.location.replace(url);
		return false;
		}
	else{
		url = getBaseURL() + displayer + '?objid='+objid +"&ispopup=true";
		var win = window.open(url,winname,features);
		if (null != win) {
			cacheNewWindow(win);
			win.focus();
		}
		return false;
	}
};


function PopupReportWindow(report_id, prev_id)  {
	var features = 'location=no,menubar=no,toolbar=no,fullscreen=no,resizable=yes,scrollbars=yes,height=200,width=300';
	
	var handler;
	if ( filesourceHandler == null )
		return;
	else
		handler = filesourceHandler;

	var url = getBaseURL() + handler + '?objid=' + report_id;
	var win = window.open('', report_id, features);
	if ( win != null )  {
		win.location.replace(url);
		cacheNewWindow(win);
		win.focus();
	}

	var prev_url = getBaseURL() + handler + '?objid=' + prev_id;
	setTimeout('location.replace("' + prev_url + '");', 500);
};

function ewlogout (msg) {
if ( !bDoneLogout){
	if (null != msg) {
		var lo = confirm(Date()+'\n'+msg);
		if (!lo)
			frmSubmit('handleAsyncTimeout','handleAsyncTimeout',null,null);	
		else
			parent.location.replace("w2k_main_handler.asp?actiontype=logout");
	}
	else{
	   			
		parent.location.replace("w2k_main_handler.asp?actiontype=logout");
		// XLT
		alert( "You are going to be logged out");
		}
	}
};



function handleMessage (arg, code, data) {
	if ((null == data) || ('string' != typeof(data)))
		return;
	var msgcount = 0;
	var delem = data.split('::');
	switch ( delem[0] ) {
	case 'logout':
		ewlogout(null);
		break;
	case 'inactivelogout':
		ewlogout(fromUTF(delem[1]));
		break;
	case 'refresh':
		refreshdoc();
		break;
	case 'infomessage':
		asyncInfoMessage(fromUTF(delem[1]));
		msgcount = delem[2];
		break;
	case 'postmessage':
		asyncPostMessage(delem[1],delem[2],fromUTF(delem[3]),fromUTF(delem[4]));
		msgcount = delem[5];
		break;
	case 'report':
		var report_win = null;

		var displayreport = true;
		displayreport = closeWindowByName( delem[2] );	

		if ( displayreport || !useClientEvent() )	
			displayReport(delem[1],delem[2]);

		msgcount = delem[3];
		break;
	case 'popform':
		displayObject(delem[1],delem[2], delem[3],delem[4]);
		msgcount = delem[4];
		break;
	case 'refreshform':
		var objid = delem[2];
		if ( useClientEvent() ) {
			var target = delem[3];
			var form_obj;
			if ( target == '_base' )
				frm_obj = getBaseFrame();
			else
				frm_obj = lookupWindowByName(target);

			if ( null != frm_obj ) {
				m_clientframe.applyUpdate(frm_obj, WF_EVENT_OBJECT_REPLACE, objid, WF_FORM); 
			}
		}
		else {
			var url = getBaseURL() + delem[1] + '?objid='+objid;
			var m_frame = getBaseFrame();
			m_frame.window.location.replace(url);
		}
		msgcount = delem[4];
		break;
	case 'export':
		var export_win = null;
		var clientRef = delem[2];

		var msg = fromUTF(delem[1]);
		var type = delem[3];

		switch ( type )  {
		case '0':		
			var msgtype = delem[4];
			var code = delem[5];

			processExportProgress(clientRef, msgtype, code, msg);
			msgcount = delem[6];
			break;

		case '2':		
			var displayexport = true;
			displayexport = closeWindowByName( clientRef );

			if ( displayexport )
				displayExport(msg, clientRef);

			msgcount = delem[4];
			break;
		}
		break;
	case 'reconnect':
		var msgName = fromUTF(delem[1]);
		var namelist = msgName.split('::');
// XLT
		var confirmMsg = 'You have lost the connection to the Integra Application Server.\nData displayed in the following cube viewers or dashboards may not be consistent:'; 
		for ( var ix = 0; ix < namelist.length; ix++ ) {
			confirmMsg = confirmMsg + '\n' + fromUTF(namelist[ix]);
		}
// XLT
		confirmMsg = confirmMsg + '\nClick OK to close these objects.';
		if ( confirm(confirmMsg) ) {
			processObjectAutoClose(delem[2]);
		}
		msgcount = delem[3];
		break;
	case 'infochanged':
		var bAlert = delem[2];
		var objid = delem[3];
		msgcount = delem[7];
		if ( bAlert == 1 ) {
			alert(fromUTF(delem[6]));
		}
		if ( objid == '-1')
			break;

		if ( useClientEvent() ) {
			var target = delem[5];
			var form_obj;
			var objtype = delem[4];
			if ( target == '_base' )
				frm_obj = getBaseFrame();
			else
				frm_obj = lookupWindowByName(target);

			if ( null != frm_obj ) {
				m_clientframe.applyUpdate(frm_obj, WF_EVENT_OBJECT_REPLACE, objid, objtype); 
			}
		}
		else {
			var url = getBaseURL() + delem[1] + '?objid='+objid;
			var m_frame = getBaseFrame();
			m_frame.window.location.replace(url);
		}
		break;
	}
	if ( useClientEvent() ) {
		if (msgcount > 0) {
			setTimeout('retrieveMessages()',100);
		}
		else
			startMessageListener();
	}
	else {

	}
};

function processObjectAutoClose(msgId) {
	if ( useClientEvent() ) {
		processClientAction(msgId, 'autoclose', 'reconnect', '', '', '', window);
	}
};


var exportMsgQ = new Array();
function exportMsg(clientRef, msgtype, code, msg) {
	this.clientRef = clientRef;
	this.msgtype = msgtype;
	this.code = code;
	this.msg = msg;
};

exportMsg.prototype.process = function (export_win) {
	showExportProgress(export_win, this.msgtype, this.code, this.msg);
};

function processPendingExportMsg() {
	if ( exportMsgQ.length > 0 ) {
		var em = exportMsgQ[0];
		var export_win = lookupWindowByName(em.clientRef);

		if ( export_win == null ) 
			exportMsgQ = exportMsgQ.slice(1);
		else if ( export_win != null && export_win.document.readyState == 'complete' ) {
			exportMsgQ = exportMsgQ.slice(1);
			em.process(export_win);
		}
		setTimeout('processPendingExportMsg();', 200);
	}
};

function processExportProgress(clientRef, msgtype, code, msg) {
	var export_win = lookupWindowByName( clientRef );

	if ( export_win != null )  {
		if ( exportMsgQ.length > 0 || export_win.document.readyState != 'complete' ) {
			exportMsgQ[exportMsgQ.length] = new exportMsg(clientRef, msgtype, code, msg);
			setTimeout('processPendingExportMsg()', 200);
			return;
		}
		showExportProgress(export_win, msgtype, code, msg);
	}
};


function showExportProgress(export_win, msgtype, code, msg) {
	if ( export_win != null )  {
		var msgbox = null;
		var barbox = null;
		var divstr;
		var divbar;

		switch ( msgtype )  {
		case '1':	
			switch ( code ) {
			case '0':	
				msgbox =  export_win.lookup('AxExportProgress', export_win.window.document);	
				if ( msgbox != null )  {
					divstr = '<div class=\"ewexportprogress\">' + msg + '</div>';
					msgbox.innerHTML = divstr;
				}
				

				break;
			case '1':	
				var imgbar = export_win.lookup('AxExportProgressImg', export_win.window.document);
				if ( imgbar == null )  {
					barbox = export_win.lookup('AxExportProgressBar', export_win.window.document);
					if ( barbox != null ) {
						divbar = '<div class=\"ewexportprogressbar\">';
						divbar = divbar + '<img src=\"images/bluebar.gif\" height=\"24px\" name=\"AxExportProgressImg\" id=\"AxExportProgressImg\">';
						divbar = divbar + '</div>';
						barbox.innerHTML = divbar;
					}
					imgbar = export_win.lookup('AxExportProgressImg', export_win.window.document);
				}
				imgbar.style.width = msg + '%';
				break;
			}
			break;
			
		case '2':	
			msgbox =  export_win.lookup('AxExportProgress', export_win.window.document);	
			if ( msgbox != null )  {
				msg = code + ': ' + msg;
				divstr = '<div class=\"ewerror ewexporterror\">' + msg + '</div>';
				msgbox.innerHTML = divstr;
			}
			break;

		}

	}
};

function retrieveMessages () {
	var handler = 'message_handler.jsp';
	var url = getBaseURL() + handler + '?uid=0&query=handleNextMessage';
	var retriever = window.frames['msgRetriever'];
	if ( retriever == null || typeof(retriever) == 'undefined' )
		return;

	if ( typeof(retriever.onload) == 'undefined' || retriever.onload == null )
		retriever.onload = checkMessageReturn;
	retriever.location.replace(url);
};

function checkMessageReturn()  {
	var retriever = window.frames['msgRetriever'];
	if ( typeof(retriever.gotMessage) == 'undefined' || retriever.gotMessage == null )
		setTimeout('retrieveMessages()',2000);
};

function listen()  {
	var listener = window.frames['msgNotifier'];
	if ( listener.sessionTimeout != null && typeof(listener.sessionTimeout) != 'undefined' )
		return;

	if ( typeof(listener.msgNumber) == 'undefined' || listener.msgNumber == null || listener.msgNumber == 0 )
		setTimeout('startMessageListener()', 2000);
	else
		retrieveMessages();
};

function startMessageListener () {
	var handler = 'message_handler.jsp';
	var url = getBaseURL() + handler + '?uid=0&query=messageListener';
	var listener = window.frames['msgNotifier'];
	if( listener != null )
		listener.location.replace(url);
};


function async_listen(){
	setTimeout("startasyncmessagelistener()",2000);
};

function startasyncmessagelistener () {
	var ewvalues = document.all('ewvalues');
	
	ewvalues.onreadystatechange = handleasyncmessage;
	var url = getBaseURL() + "message_handler.asp" + '?uid=0&query=messageListener';
	
	ewvalues.load(url)
	if (null != document.body.style)
		document.body.style.cursor = 'default';
	setTimeout("async_listen()",2000);
};

function handleasyncmessage(){
	var xmldoc = null;
	var err = null;
	var ewvalues = null;
	ewvalues = getElement('ewvalues');
	if (isMac || null == ewvalues)
		return;
	xmldoc = ewvalues.XMLDocument;
	var docstate = 0;
	if (null != xmldoc)
		docstate = xmldoc.readyState;
	if (docstate < 4)
		return;
	err = xmldoc.parseError;
    	if (  err != null && err.errorCode != 0) {
    	
		resetEventStatus();
		return;
    	}
	else {
		if(xmldoc.childNodes(1) != null){
			var attr = xmldoc.childNodes(1).getAttribute('value');
			if (null != attr) {
				attr = fromUTF(attr);
				handleMessage('', 0,attr);
			}
		}
	}
};



function checkMessages () {
	clearTimeout(checkmsghandle);
	if (checkMessageInterval > 0)
		checkmsghandle = setTimeout('checkMessages()',checkMessageInterval);
	var handler = asyncMessageHandler;
	var url = getBaseURL() + handler + '?uid=0&query=handleNextMessage';
	return getMessage(url,handleMessage,1);
};

function sprdAddRow (sprd) {
	return frmSubmit(sprd,'addrow','-1','-1');
};

function sprdDeleteRow (sprd,row) {
	return frmSubmit(sprd,'deleterow',row,'-1');
};

function sprdSelectRow (sprd,row) {
	return frmSubmit(sprd,'selectrow',row,'-1');
};

function sprdCellQuery (sprd,row,col) {
	return frmSubmit(sprd,'querycell',row,col);
};

function ewtabgroup  (tabName, maxbuttons,width) {
	this.tgName = tabName;
	this.LeftButton = 1;
	this.MaxButtons = maxbuttons;
	this.MaxWidth = width;
	this.TabButtons = new Array();
	this.ForceShift = false;
	this.Direction = '';
};

function buttonShift(tabGroup, direction,localcall) {

	if(!localcall)
		tabGroup.ForceShift=true;
	tabGroup.Direction = direction;
	if (direction == 'left')
		tabGroup.LeftButton--;
	else {
		tabGroup.LeftButton++;
	}
	if (tabGroup.LeftButton < 1) {
		tabGroup.LeftButton = 1;
	}
	if (tabGroup.LeftButton >= tabGroup.MaxButtons) {
		tabGroup.LeftButton = tabGroup.MaxButtons;
	}
	fixTab(tabGroup, true);
};

function getTabButtons(tabGroup) {

	var tabDivName = 'but_' + tabGroup.tgName + 'Layer';
	var tabDivElement = document.getElementById(tabDivName);
	var tmpArray = new Array();
	var j;
	var k=0;
	
	for (j=0;j<tabDivElement.childNodes.length;j++) {
		if (tabDivElement.childNodes[j].className=='ewtabactivebutton'||tabDivElement.childNodes[j].className=='ewtabbutton'){
			tmpArray[k++] = tabDivElement.childNodes[j];
		}
	}

	tabGroup.TabButtons = tmpArray;

};

function fixTab(tabGroup, bPressed) {
	
	getTabButtons(tabGroup);

	var tName = 'but_' + tabGroup.tgName + 'Layer';
	var tNumber = 0;
	var lastButton = tabGroup.MaxButtons;
		
	var tabbutton;

	var bTurnOnShift = false;

	var butl = document.getElementById('but_' + tabGroup.tgName + 'leftshift');
	var butr = document.getElementById('but_' + tabGroup.tgName + 'rightshift');
	for (tNumber = 0; tNumber < (tabGroup.TabButtons.length); ) {
		tabbutton = tabGroup.TabButtons[tNumber];
		tabbutton.style.display = '';

		if ((tabbutton.offsetLeft - tabbutton.parentNode.offsetLeft) + tabbutton.offsetWidth >  tabGroup.MaxWidth) {
			
			bTurnOnShift = true;
			lastButton = tNumber;
			break;
		}

		if (tNumber < tabGroup.LeftButton-1) {
			tabbutton.style.display = 'none';
			}
		else {
			
			tabbutton.style.display = '';
			if ((tabbutton.offsetLeft - tabbutton.parentNode.offsetLeft) + tabbutton.offsetWidth >  tabGroup.MaxWidth) {
				bTurnOnShift = true;
				lastButton = tNumber;
				break;
			}
		}
		tNumber++;
	}



	for(var l=0;l<tabGroup.TabButtons.length;l++) {
		if (tabGroup.TabButtons[l].className=='ewtabactivebutton'){
			var theActiveButton=tabGroup.TabButtons[l];
			break;
		}
	}

	if (!tabGroup.ForceShift&&((theActiveButton.offsetLeft - tabbutton.parentNode.offsetLeft)+theActiveButton.offsetWidth)>(tabGroup.MaxWidth-(butl.offsetWidth+butr.offsetWidth))){
		buttonShift(tabGroup,'right',true);
	}

	if (bTurnOnShift || bPressed) {
		butl.style.display = '';
		butr.style.display = '';
		if (isMac)
			document.getElementById('but_' + tabGroup.tgName + 'Layer').style.width = ( tabGroup.MaxWidth - ((butl.offsetWidth + butr.offsetWidth))+'px');
		else
			document.getElementById('but_' + tabGroup.tgName + 'Layer').style.width = ( tabGroup.MaxWidth - ((butl.offsetWidth + butr.offsetWidth)));
	} else {
			butl.style.display = 'none';
			butr.style.display = 'none';
		if (isMac)
			document.getElementById('but_' + tabGroup.tgName + 'Layer').width = tabGroup.MaxWidth + 'px';
		else
			document.getElementById('but_' + tabGroup.tgName + 'Layer').width = tabGroup.MaxWidth;
			}
	
	
	if ((tabGroup.TabButtons[tabGroup.TabButtons.length-1].offsetLeft+tabGroup.TabButtons[tabGroup.TabButtons.length-1].offsetWidth)<(tabGroup.MaxWidth-(butl.offsetWidth+butr.offsetWidth))){
		butr.disabled=true;
		butr.src = "images/tabbtnrightshiftdisabled.gif"
	} else {
		butr.disabled=false;
		butr.src = "images/tabbtnrightshift.gif"
	}

	if (tabGroup.LeftButton==1){
		butl.disabled=true;
		butl.src = "images/tabbtnleftshiftdisabled.gif"
	} else {
		butl.disabled=false;
		butl.src = "images/tabbtnleftshift.gif"
	}
};

function grdSorter (ctrl,col,asc) 
{	
	if (isDialogPending(null))
		return;
	frmSubmit(ctrl,'grdsorter',asc,col);
};

function ctrlRefresh(node)  {
	var objid = node.getAttribute('objid');
	var ctrl = (null != objid) ? getElement(objid) : null;
	if ( ctrl == null )
		return;

	setCtrlStyleAttrs(ctrl, node);

	var attr = node.getAttribute('value');
	if (null != attr) {
		var value = fromUTF(attr);
		switch (getFirstClass(ctrl.className)) {
		case 'ewlabel':
		case 'ewtable':
		case 'ewdatasheet':
		case 'ewhyperlink':
		case 'ewpicture':
			setCtrlText(objid,value);
			break;
		case 'ewcheckbutton':
		case 'ewcheckbuttonreadonly':
			value = 0-value;
		default:
			setCtrlValue(objid,value);
			break;
		}
	}
	if (null != document.body.style)
		document.body.style.cursor = 'auto';
};

function checkFileSize () {
  var fileName;
  var filesize;
  var f = document.getElementById("attach_file");
  if( f != null && f != "")
  	fileName = f.value;
  var action;
  if (!useClientEvent())
  	action = "checkfilesize.asp";
  else
  	action="checkfilesize.jsp";
  	
  if ( fileName != null && fileName != ""){
  	var url = action + "?fileName=" + fileName;
  	var ewvalues = getElement('ewvalues');
 	if (isMac || null == ewvalues || null != ewvalues.xmlsrc)
 		return false;
	setWarningOff();
 	ewvalues.onreadystatechange = handleAttachFile;
 	ewvalues.load(url)
 	if (null != document.body.style)
 		document.body.style.cursor = 'default';
  	}
  };
  
function  handleAttachFile(){
	var xmldoc = null;
	var err = null;
	var filesize, maxupload;
	var ewvalues = null;
	ewvalues = getElement('ewvalues');
	if (isMac || null == ewvalues)
		return;
	xmldoc = ewvalues.XMLDocument;
	var docstate = 0;
	if (null != xmldoc)
		docstate = xmldoc.readyState;
	if (docstate < 4)
		return;
	err = xmldoc.parseError;
    	if (  err != null && err.errorCode != 0) {
		resetEventStatus();
		return;
    	}
	else {
		if(xmldoc.childNodes(1) != null){
			filesize = xmldoc.childNodes(1).getAttribute('value');
			}
	}
	var f = document.getElementById("attach_file");
	maxupload = f.size;
	if (maxupload == "")
	   maxupload = 100000000; 
	if ( filesize > maxupload)
		alert("Maximum file size exceeded");
	else{
	    	var frm = document.forms['ent_attach_put'];
	    	frm.submit();
	    }
	    	

};

var oPopup1;

function showtooltip(str){
	oPopup1 = window.createPopup();
	var oPopupBody = oPopup1.document.body;
	oPopupBody.style.border = "1px black solid"
	oPopupBody.style.backgroundColor = "#fafad2";
	oPopupBody.style.fontSize = "8pt";
	oPopupBody.style.fontFamily = "tahoma, Arial, monospace";
	oPopupBody.innerHTML = str;
	oPopup1.show(0, 0, 0, 30);
	var realWidth = oPopupBody.scrollWidth;
	oPopup1.hide();
	oPopup1.show(0,0,30,0)
	var realHeight = oPopupBody.scrollHeight;
	oPopup1.hide();
	oPopup1.show(event.clientX , event.clientY,realWidth ,realHeight,  document.body);
};

function hidetooltip(){
oPopup1.hide();

};




function updateewvalues (xmlvalues) {
	var xmldoc = null;
	var err = null;
	var ewvalues = null;

	if ( xmlvalues != null )  {
		xmldoc = xmlvalues;		
	}
	else  {
		ewvalues = getElement('ewvalues');
		if (isMac || null == ewvalues)
			return;
		xmldoc = ewvalues.XMLDocument;		
		var docstate = 0;
		if (null != xmldoc)
			docstate = xmldoc.readyState;
		if (docstate < 4)
			return;
		err = xmldoc.parseError;
	}	

    	if ( xmlvalues == null && err != null && err.errorCode != 0) {
// XLT
    		var errmsg = 'An error occured updating values, please try again.\n';
// XLT
    		errmsg += 'If the problem persists, please contact the webmaster';
		alert (errmsg);
		document.getElementById('ctrlName').value = 'frm_cancel';
		document.getElementById('ctrlValue').value = '';
		document.getElementById('ctrlRow').value = '';
		document.getElementById('ctrlCol').value = '';
		var entform = document.forms['ent_form'];
		entform.target = '';
		entform.submit();

		resetEventStatus();
		return;
    	}
	else {
		var ewobj = xmldoc.getElementsByTagName('ewobject');
		if (null != ewobj && ('undefined' != typeof(ewobj)) && ewobj.length > 0) {
				var node = ewobj.item(0);
				if (null != node && '3' == node.getAttribute('type')) {
				
					var handler = filesourceHandler;
		
					var objid = node.getAttribute('objid');
					var url = getBaseURL() + handler + '?objid='+objid;
					setWarningOff();	
					if (this.name == 'AxObjectMain' )
						parent.location.replace(url);
					else
						location.replace(url);
					setWarningOn();

					resetEventStatus();
					return;
				}
		}
		var nodes = xmldoc.getElementsByTagName('ewcontrol');
		for (var ix = 0; ix < nodes.length; ++ix) {
			var node = nodes.item(ix);
			var id = node.getAttribute('id');
			ctrl = (null != id) ? getElement(id) : null;
			var attr = null;
			if (null == ctrl) {
				if ('1' == node.getAttribute('iserror')) {
					attr = fromUTF(node.getAttribute('value'));
					alert(attr);
					eventqueue = new Array();		
					frmSubmit('error_ok',null,null,null);
				}
				else if ('1' == node.getAttribute('isscript')) {
					attr = node.getAttribute('value');
					if (null != attr) {
						attr = fromUTF(attr);
						eval(attr);
					}
				}
				else if (null != (attr = node.getAttribute('ismodified'))) {
					if (null != document.ent_form && null != document.ent_form.modified)
						document.ent_form.modified.value = attr;
					if (null != (attr = node.getAttribute('value'))) {
						document.title = fromUTF(attr);
						if (!isDashObject() && top && top.document){
							if(isIE){
								if ( MSIEVersion() > 5)
									top.document.title = document.title;
								}
							else
								top.document.title = document.title;}
					}
					setObjectModified(document.ent_form.uid.value, document.ent_form.modified.value, document.title);
				}
				continue;
			}
			if ( null == ctrl.style && ctrl.length > 0 && 
                 'radio' == ctrl[0].type) {
				var radiogrp = ctrl;
				var radioval = node.getAttribute('value')-0;
				for (var rx = 0; rx < radiogrp.length; ++rx) {
					setCtrlStyleAttrs(radiogrp[rx],node);
					radiogrp[rx].checked = (rx == radioval);
				}
				continue;
			}
			setCtrlStyleAttrs(ctrl,node);
			attr = node.getAttribute('strings');
			if (null != attr) {
				var longstr = fromUTF(attr);
				var strs = longstr.split('\n');
				if ('ewlist' == ctrl.className || 
                    'ewcombo' == ctrl.className ||
					'ewcellcombo' == ctrl.className || 
                    'ewcomboe' == ctrl.className ||
                    'ewcomboreadonly ewcombo' == ctrl.className ) {
					var numopts = ctrl.options.length;
					for (var ox = numopts-1; ox >= 0; --ox)
						ctrl.options.remove(ox);
					for (ox = 0; ox < strs.length; ++ox) {
						var opt = document.createElement("OPTION");
						opt.text = strs[ox];
						opt.value = strs[ox];
						ctrl.options.add(opt);
					}
				}
			}
			attr = node.getAttribute('value');
			if (null != attr) {
				var value = fromUTF(attr);
                var first_class = getFirstClass(ctrl.className);
				switch ( first_class ) {
                case 'ewchecklabel':
                case 'ewradiolabel':
                    setCtrlText(id,value);
                    break;
				case 'ewlabel':
				case 'ewtable':
				case 'ewdatasheet':
					var currentctrlidval = node.getAttribute('currctrlid');
					setCtrlText(id,value, currentctrlidval);
					break;
				case 'ewhyperlink':
				case 'ewpicture':
					setCtrlText(id,value);
					break;
				case 'ewcheckbutton':
				case 'ewcheckbuttonreadonly':
					value = 0-value;
				default:
					setCtrlValue(id,value);
					break;
				}
			}
		}
		if (ewvalues != null && ewvalues.xmlsrc) {
			var xctrl = getElement(ewvalues.xmlsrc);
			if (xctrl && 'radio' != xctrl.type && !xctrl.disabled &&
				xctrl.focus && !isHidden(xctrl)) {
			}
			ewvalues.xmlsrc = null;
		}
		resetEventStatus();
		setTimeout('processPendingEvents()',0);
	}
};

function frmGetXMLValues (htmlid, value, row, col) {
	if ( null == ewvalues)
		ewvalues = parent.document.getElementById('ewvalues');
	var ewvalues = getElement('ewvalues');
	if (isMac || null == ewvalues || null != ewvalues.xmlsrc)
		return false;
	ewvalues.onreadystatechange = updateewvalues;
	var uid = -1;
	if(htmlid.indexOf("TXTHTML") != -1 && (value == "<P>&nbsp;</P>"))
		value ="";
	if (null != document.ent_form && null != document.ent_form.uid)
		uid = document.ent_form.uid.value;
	var handler = valuechangeHandler;
	if (!handler)
		return false;
	var url = getBaseURL() + handler + '?query=xmlvalues&uid=' + uid;
	url += '&htmlid=' + toUTF(htmlid);
	url += '&value=' + toUTF(''+value);
	url += '&row=' + escape(''+row);
	url += '&col=' + escape(''+col);
	if (url.length > 1000)
		return false;
	ewvalues.xmlsrc = (null != currentElem) ? currentElem.id : htmlid;
	setCtrlInfo(htmlid,'',false);
	if (!ewvalues.load(url))
		return false;

	markEventPending();
	return true;
};

function sprdPageAction(action, htmlid)
{
	var ewvalues = getElement('ewvalues');
	if (isMac || null == ewvalues || null != ewvalues.xmlsrc)
		return false;
	ewvalues.onreadystatechange = updateewvalues;
	var uid = -1;
	if (null != document.ent_form && null != document.ent_form.uid)
		uid = document.ent_form.uid.value;
	var handler = valuechangeHandler;
	if (!handler)
		return false;
	var url = getBaseURL() + handler + '?query=tablenav&uid=' + uid;
	url += '&htmlid=' + toUTF(htmlid);
	url += '&value=' + toUTF(''+action);	
	if (!ewvalues.load(url))
		return false;

	markEventPending();
	return true;
};

function markEventPending() {
	window.status = window.defaultStatus = fromUTF(waitMessage);
	waitingForResponse = true;
	if (null != document.body.style)
		document.body.style.cursor = 'wait';
	if (window.event)
		window.event.cancelBubble = true;
	if (currentElem && 'radio' != currentElem.type && currentElem.blur)
		currentElem.blur();
};

function resetEventStatus() {
	window.status = window.defaultStatus = '';
	if (null != document.body.style)
		document.body.style.cursor = 'auto';
	waitingForResponse = false;
};


function handleonfocus (elem)
{
	var objMain = window.frames['AxObjectMain'];
	if ( objMain != null ) {
		if ( objMain.document.readyState == 'complete' )
			objMain.handleonfocus(elem);
		return;
	}

	if (isHidden(elem))
		return true;
	initCtrlValue(elem);
	
	if(elem.className == "ewrichtexthtml"){
		if (parent.document.getElementById("divrtf") != null || document.getElementById("divrtf") != null)
		{
			parent.document.getElementById("divrtf").style.visibility = "visible"
			if(parent.document.getElementById(elem.id) == null){
				initRTE("images/", "", "");
				writeRichText(elem.id, '', 400, 200, true, false);
			}
		}
	}
	if(elem.className == "ewtextfield" || elem.className == "ewtextarea"){
		if (parent.document.getElementById("divrtf") != null ){
			var elemdiv = parent.document.getElementById("divrtf");
			parent.document.getElementById("divrtf").style.visibility = "hidden"
			elemdiv.innerHTML = "";
			
			}
	}
	return checkElemChange(elem,null);
};

function handleondrop(elem) 
{
	var objMain = window.frames['AxObjectMain'];
	if ( objMain != null ) {
		if ( objMain.document.readyState == 'complete' )
			objMain.handleonfocus(elem);
		return;
	}
	
	if (isHidden(elem))
		return true;
	initCtrlValue(elem);
};

document.onclick = function handleclick (ev) {
	if (null == ev)
		ev = window.event;

	var objMain = window.frames['AxObjectMain'];
	if ( objMain != null ) {
		if ( objMain.document.readyState == 'complete' )
			objMain.handleclick(ev);
		return;
	}

	if (isDialogPending(ev))
		return;
	var elem = ev.srcElement;
	if (isHidden(elem))
		return;
	if (null != elem && elem.isDisabled){
		if(elem.disabled)
		return;
		}
	if (elem.className == 'rteImage' || elem.className == 'rteImageLowered' || elem.className == 'rteImageRaised') 
		return;

	initCtrlValue(elem);
	if (setCurrentElem(ev)) {
		if ( useClientEvent() ) {
			handleclick(ev);
			return;
		}
		if (waitingForResponse) {
			addEventToQueue(ev);
			if (ev)
				ev.returnValue = false;
		}
		return;
	}
	if ( useClientEvent() ) {
		if(getFirstClass(elem.className) == 'ewhyperlink') {
			ev.returnValue=false;
			processClientAction("", "hyperlink", elem.id, "", "", "", "");
		}
		else {
			if(getFirstClass(elem.className) == 'ewhyperlinkimg') {
				ev.returnValue=false;
				if(elem.parentElement != null)
					processClientAction("", "hyperlink", elem.parentElement.id, "", "", "", "");
				else{
					var id = elem.id.substr(0, elem.id.length - 3);
					processClientAction("", "hyperlink", id, "", "", "", "");
					}			
			}
		}

	}
	if (elem.onclick || elem.onchange) {
		if (1 == elem.onchanger && 'ewlist' == getFirstClass(elem.className) &&
			'select-multiple' != elem.type) {
			elem.onchanger++;
			if (null != ev.selectvalue)
				setCtrlValue(elem.id,ev.selectvalue);
			ctrlValChange(elem);
		}
		ev.cancelBubble = false;
		currentElem = null;
		return;
	}
	var info = null;
	var props = null;
	switch (getFirstClass(elem.className)) {
	case 'ewbutton':
	case 'ewimgbutton':
	case 'ewimgclose':
	case 'ewcheckbutton':
	case 'ewradiobutton':
		frmValChange(elem);
		currentElem = null;
		break;
	case 'ewcellcheckbutton':
		ctrlValChange(elem);
		currentElem = null;
		break;
	case 'ewformtoolbarbutton':
	case 'ewformbuttonbarbutton':
		info = getCtrlInfo(elem.id);
		if (null == info || false == info.hasAction)
			return frmValChange(elem);
		currentElem = null;
		break;
	case 'ewtabbutton':
	case 'ewtabactivebutton':		
		ctrlValChange(elem);
	case 'ewcellqrybutton':
		props = elem.id.split('_');
		return sprdCellQuery(props[1],props[2],props[3]);
	case 'ewcelladdbutton':
		return sprdAddRow(elem.id.substr(4));
	case 'ewcelldelbutton':
		props = elem.id.split('_');
		return sprdDeleteRow(props[1],props[2]);
	case 'ewcellselectcheck':
		props = elem.id.split('_');
		return sprdSelectRow(props[1],props[2]);
	case 'ewnavbutton_top':
	case 'ewnavbutton_prev':
	case 'ewnavbutton_next':
	case 'ewnavbutton_end':
		props = elem.id.split('_');
		if ( useClientEvent() ) {
			var uid = -1;
			if (null != document.ent_form && null != document.ent_form.uid)
				uid = document.ent_form.uid.value;

			processClientAction(uid, 'tablenav', props[2], props[1], '', '');
			return true;
		}
		return sprdPageAction(props[1],props[2]);
	case 'ewhyperlink':
		if(!useClientEvent()){
			if (ev)
				ev.returnValue = false;
			executeHyperlink(elem.id);
			break;
		}
	case 'ewhyperlinkimg':
		if(!useClientEvent()){
			if (ev)
				ev.returnValue = false;
			var id = elem.id.substr(0, elem.id.length - 3);
			executeHyperlink(id);
		}
	}
};

document.onkeydown = function handlekeydown (ev) {
	if (null == ev)
		ev = window.event;

	var objMain = window.frames['AxObjectMain'];
	if ( objMain != null ) {
		if ( objMain.document.readyState == 'complete' )
			objMain.handlekeydown(ev);
		return;
	}

	if (isDialogPending(ev))
		return;
	var elem = ev.srcElement;
	if (isHidden(elem))
		return;
	initCtrlValue(elem);
	if (setCurrentElem(ev))
		return;
};

document.onkeyup = function handlekeyup (ev) {
	if (null == ev)
		ev = window.event;

	var objMain = window.frames['AxObjectMain'];
	if ( objMain != null ) {
		if ( objMain.document.readyState == 'complete' )
			objMain.handlekeyup(ev);
		return;
	}

	if (isDialogPending(ev))
		return;
	var elem = ev.srcElement;
	if (isHidden(elem))
		return;
	if (null == elem || null == elem.id)
		return;
	if (setCurrentElem(ev))
		return;
	if (13 == ev.keyCode) {
		if ('checkbox' == elem.type) {
			elem.checked = !elem.checked;
		}
		handleclick(ev);
	}
	else if ( ('text' == elem.type || 'password' == elem.type) && null != elem.id) {
		var info = getCtrlInfo(elem.id);
		if (null != info) {
			switch (ev.keyCode) {
			case 9:
				break;
			case 27:
				elem.value = info.elemValue;
				break;
			default:
				if (null != info.maskstr && info.maskstr.length > 0)
					elem.value = info.applyMask(elem.value);
			}
		}
	}
};


function executeHyperlink (id) {
	if (null == id)
		return;
	var objMain = lookupFrameFromTop("AxObjectMain");
	var ctrl = objMain.window.document.all[id];
	var win = window.open(ctrl.href, "", "");
	if (null != win) {
		win.focus();
	}
};


function EWPopupWindow (win,title,caption) {
	this.title = title;
	this.caption = caption;
	this.parentwin = win;	
	this.text = '';
	this.features = 'resizable=yes,scrollbars=yes,height=125,width=550';
	this.pwindow = this.parentwin.open('',title,this.features,true);
};

EWPopupWindow.prototype.setText = function (text) {
	if (this.pwindow.closed)
		this.pwindow = this.parentwin.open('',this.title,this.features,true);
	var d = this.pwindow.document;
	d.open();
	d.write('<html><head><title>' + this.caption + '</title></head><body>');
	d.write(text);
	d.write('</body></html>');
	d.close();
};

function qrySelect (num) {
	if (isDialogPending(null))
		return;

	frmSubmit('select',num,null,null);
};

function qryNav (action) {
	if (isDialogPending(null))
		return;

	if (seltype == "multiple")
	{
		var list = '';
		list = getSelectList();
	}
	
	frmSubmit('tableNav',action,list,null);
};

function qrySorter (col) {
	if (isDialogPending(null))
		return;
	frmSubmit('sorter',col,null,null);
};

var seltype = "single";
var radiosel = '';
var checksel = new Array();
var zoomCapArr = new Array();
var zoomDataArr = new Array();
var rowsel = '';

function gotZoomText (value,code,data) {

	if (data)
		data = fromUTF(data);	

	zoomCapArr[value] = zoomCaption;
	zoomDataArr[value] = data;
	document.getElementById('zoomfld').innerHTML = zoomCapArr[value];
	var val1 = document.getElementById('zoomfld').innerText
	document.getElementById('zoomfld').innerHTML = zoomDataArr[value];
	var val2 = document.getElementById('zoomfld').innerText
	document.getElementById('zoomfld').innerHTML = val1 + '<br>' + val2;	
	
	setZoomText(value);
};

function setQueryZoomText (details) {
	if ( details == null )
		return;
	var zt = details.split('|');
	
	var ix = zt[0];
	var data = fromUTF(zt[1]);

	zoomCapArr[ix] = zoomCaption;
	zoomDataArr[ix] = data;
	document.getElementById('zoomfld').innerHTML = zoomCapArr[ix];
	var val1 = document.getElementById('zoomfld').innerText
	document.getElementById('zoomfld').innerHTML = zoomDataArr[ix];
	var val2 = document.getElementById('zoomfld').innerText
	document.getElementById('zoomfld').innerHTML = val1 + '<br>' + val2;
	
	if (null != document.body.style)
		document.body.style.cursor = 'auto';
};

function setZoomText (value) {
	
	if (zoomCapArr[value] && zoomDataArr[value]) {
		document.getElementById('zoomfld').innerHTML = zoomCapArr[value];
		var val1 = document.getElementById('zoomfld').innerText
		document.getElementById('zoomfld').innerHTML = zoomDataArr[value];
		var val2 = document.getElementById('zoomfld').innerText
		document.getElementById('zoomfld').innerHTML = val1 + '<br>' + val2;	
		return;
	}
	
	if ( useClientEvent() ) {
		var uid = -1;
		if (null != document.ent_form && null != document.ent_form.uid)
			uid = document.ent_form.uid.value;


		
		processClientAction(uid, 'getzoomtext', 'zoomtext', value, '', '');
		return;
	}
		
	document.getElementById('zoomfld').innerHTML = zoomCaption;
	var val1 = document.getElementById('zoomfld').innerText	
	document.getElementById('zoomfld').innerHTML = val1;			
	
	var handler = queryDetailsHandler;
	var url = getBaseURL()+handler+'?uid='+document.ent_form.uid.value+'&query='+value;
	getMessage(url,gotZoomText,value);
};

function displayZoomText (value) {
	setZoomText(value);
};

var zoomCaption = '';

function setZoomCaption (caption) {
	zoomCaption = fromUTF(caption);
};

function qrySelectRow (ctrl) {
	if (isDialogPending(null))
		return;
	if ('' != zoomCaption)
		displayZoomText(ctrl.value);
	if ("checkbox" == ctrl.type) {
		seltype = "multiple";
		checksel[ctrl.value] = ctrl.checked;
	}
	else if ("radio" == ctrl.type)
		radiosel = ctrl.value;
};

function getSelectList () {
	if ("single" == seltype)
		return radiosel;
	var list = '';
	for (var nm in checksel) {
		if (checksel[nm]) {
			if ('' != list)
				list += ',';
			list += nm;
		}
	}
	return list;
};

function qryBtnClick (ctrl) {
	if (isDialogPending(null))
		return;
	var list = '';
	switch ( ctrl.name ) {
	case "select":
		list = getSelectList();
		if ('' == list) {
			alert('Please select row(s) and click ' + ctrl.value);
			return;
		}
		break;
	case "sort":
		displaySortPage();
		return;
	case "timer":
		displayTimerPage(ctrl);
		return;
	}
	frmSubmit(ctrl.name,list,null,null);
};

function updateSels(data)
{
	seltype = "multiple";
	var rowsel;
	rowsel = data.split(',');

	for (var nm in rowsel) 
		checksel[rowsel[nm]] = true;	
};

function displayTimerPage(elem) {
	var handler = queryHandler;
	if ( handler == null || typeof(handler) == 'undefined' )
		return;

	var uid = document.ent_form.uid.value;

	var url = handler + '?uid=' + uid + '&name=timer&value=';
	var options = "dialogWidth: 280px; dialogHeight: 160px; edge: raised; center: yes; help: no; scroll: no; resizable: no; status: no;";
	var retVal = window.showModalDialog(url,"", options);

	if ( retVal == null || typeof(retVal) == 'undefined' || retVal == "Cancel" )
		retVal = 'Cancel';
	else
		setTimerButtonImage(elem, retVal);

	if ( useClientEvent() )
		processClientAction(uid, 'valuechange', 'set_timer', retVal,null, null);
	else
		frmSubmit('set_timer', retVal,null, null);
}

function setTimerButtonImage(elem, retVal) {
	var delem = retVal.split(',');
	if ( delem == null )
		return;

	if ( delem[1] == 1 )
		elem.src = 'images/timer_on.gif';
	else
		elem.src = 'images/timer_off.gif';
}

function displaySortPage() {
	var handler = queryHandler;
	if ( handler == null || typeof(handler) == 'undefined' )
		return;

	var uid = document.ent_form.uid.value;

	var url = handler + '?uid=' + uid + '&name=sort&value=';
	var options = "dialogWidth: 400px; dialogHeight: 360px; edge: raised; center: yes; help: no; scroll: yes; resizable: yes; status: no;";
	var retVal = window.showModalDialog(url,"", options);

	if ( retVal == null || typeof(retVal) == 'undefined' || retVal == "Cancel" || retVal == 'sort_cancel') {
		if ( useClientEvent() )
			processClientAction(uid, 'valuechange', 'sort_cancel', 'sort_cancel',null, null);
		else
			frmGetXMLValues('sort_cancel', 'sort_cancel',null, null);
	}
	else {
		frmSubmit('sort_ok', retVal, null, null);
	}
}


function ewcal (doc) {
	this.date = new Date();
	if ('undefined' == typeof(calDayAbbreviations)) 
		this.dd = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
	else
		this.dd = calDayAbbreviations;

	if ('undefined' == typeof(calMonthNames)) 
		this.MM = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
	else
		this.MM = calMonthNames;
	if ('undefined' == typeof(calDateSeparator)) 
		this.Separator  = '/';
	else
		this.Separator  = calDateSeparator;
	if ('undefined' == typeof(calDateOrder)) 
		this.DateOrder  = 'MDY';
	else
		this.DateOrder  = calDateOrder;
	this.doc = doc;
};

ewcal.prototype.datestr = function () {
	var dt = this.date;
	var str = '';
	str += dt.getFullYear() + '/';
	str += (dt.getMonth()+1) + '/';
	str += dt.getDate();
	return str;
};

ewcal.prototype.monthgrid = function () {
	var str = '';
	var date = this.date;
	str += '<table class="ewcaltable" cols=7 border=1 cellspacing=1 cellpadding=1 align="center">';
	str += '<tr class="ewcalrow" >';
	str += '<td width=50 align="center">';
	var dts = this.datestr();
	str += '<a href="javascript:gotodate(\''+dts+'\',\'-12\');">&lt;&lt;</a></TD>';
	str += '<td width=50 align="center"><a href="javascript:gotodate(\''+dts+'\',\'-1\');">&lt;</a></td>';
	str += '<td width=150 colspan=3 align="center">' + this.MM[date.getMonth()] + '&nbsp;' + date.getFullYear() + '</TD>';
	str += '<td width=50 align="center"><a href="javascript:gotodate(\''+dts+'\',\'+1\');">&gt;</a></td>';
	str += '<td width=50 align="center"><a href="javascript:gotodate(\''+dts+'\',\'+12\');">&gt;&gt;</a></td>';
	str += '</tr><tr class="ewcalrow" >';

	for (var ix = 0; ix < this.dd.length; ++ix) {
		str += '<td width=50 align="center">' + this.dd[ix] + '</td>';
	}
	str += '</tr>';

	var curdate = date.getDate();

	var d = null;
	d = new Date(date.getFullYear(),date.getMonth(),1);
	var firstday = d.getDay();	

	d.setMonth(date.getMonth()+1);
	d.setDate(d.getDate()-1);
	var lastdate = d.getDate();

	for (ix = 0; ix < firstday; ++ix) {
		str += '<td bgcolor="#22FF88">&nbsp;</td>';
	}
	for (ix = 1; ix <= lastdate; ++ix) {
		str += '<td ';
		if (ix == curdate) {
			str += ' bgcolor="yellow">';
		}
		else {
			str += ' bgcolor="#BBCCCC">';
		}
		str += '<a href="javascript:gotodate(\''+dts+'\',\'\','+ix+');">&nbsp;'+ix+'</a></td>';
		if (6 == (ix+firstday-1)%7) {
			str += '</tr><tr class="ewcalrow" >';
		}
	}
	var iMaxLoop = 0;
	while((firstday+ix-1)%7!=0 && iMaxLoop < 7) {
		++iMaxLoop;
		str+='<td bgcolor="#22FF88" >&nbsp;</td>';ix++;
	}
	str += '</tr></table>';

	return str;
};

function doaction (ctrl) {
	
	
	var name = ctrl.name;
		
	var form = document.ent_form;
			
	if (form.ctrlNoDate.value == "0")
		var value = ctrl.form.datefld.value + ' ';	
	else
		value = "";	
		
	if (form.ctrlNoTime.value == "0")
	 value += ctrl.form.hour.value + ':' + ctrl.form.minute.value;
	 
	 var url = getBaseURL() + form.action + '?';
	 url += 'uid=' + form.uid.value;
	 url += '&name=' + toUTF(name);
	 url += '&value=' + toUTF(''+value);
									
	if ( useClientEvent() ) 
		processClientAction(form.uid.value, 'formreplace', name, value, '', '');
	else 
		location.replace(url);
		
};


function timeval (ctrl) {
	var foo = '';
};

var mycal = new ewcal(document);

function initCal (dtstr) {

	var dtNow = new Date();




	if (null==calDateHour||''==calDateHour||null==calDateMinute&&''==calDateMinute) {
		calDateHour = dtNow.getHours();
		calDateMinute = dtNow.getMinutes();
	}

	var ctrlComboHour = document.getElementById('hour');
	var ctrlComboMinute = document.getElementById('minute');

	if (null!=calDateHour&&Number(calDateHour)>=0)
	ctrlComboHour.selectedIndex = Number(calDateHour);
	if (null!=calDateMinute&&Number(calDateMinute)>=0)
	ctrlComboMinute.selectedIndex = Number(calDateMinute);

	var ctrlTextDateFld = document.getElementById('datefld');

	if (null!=ctrlTextDateFld) {
		ctrlTextDateFld.style.display='none';
	}

	var dt = null;
	if (null==calDateYear||''==calDateYear)
		dt = dtNow;
	else {
		dt = new Date(calDateYear,calDateMonth-1,calDateDay);
	}
	mycal.date = dt;
};

function refresh_caldisp () {
	var dt = mycal.date;
	var datestring = dt.getFullYear() + '-' + (dt.getMonth()+1) + '-' + dt.getDate();
	var dtfld = document.getElementById('datefld');
	if ('undefined' != typeof(dtfld))
		dtfld.value = datestring;
	var cd = document.getElementById('caldisp');
	if ('undefined' != typeof(cd))
		cd.innerHTML = mycal.monthgrid();	
};

function gotodate (s, where, d) {
	var dt = new Date(s);
	if (null == dt || typeof(dt) == "undefined")
		alert(s + ': is not a dateable');
	if ('-12' == where) {
		dt.setMonth(dt.getMonth()-12);
	}
	else if ('-1' == where) {
		dt.setMonth(dt.getMonth()-1);
	}
	else if ('+1' == where) {
		dt.setMonth(dt.getMonth()+1);
	}
	else if ('+12' == where) {
		dt.setMonth(dt.getMonth()+12);
	}
	else {
		var submitSelection = true;
		dt.setDate(d);
	}
	mycal.date.setFullYear(dt.getFullYear());
	mycal.date.setMonth(dt.getMonth());
	mycal.date.setDate(dt.getDate());
	refresh_caldisp();
	var ctrlSelectBtn = document.getElementById('select');
	if (submitSelection&&'undefined'!=ctrlSelectBtn&&null!=ctrlSelectBtn) {
		doaction(ctrlSelectBtn);
	}
	
};



var ewicon = null;

function preloadImages () {
	if (null != ewicon)
		return;
	ewicon = new Array();
	var icx = 0;
	ewicon[icx] = new Image(); ewicon[icx++].src = 'images/folder_open.gif';
	ewicon[icx] = new Image(); ewicon[icx++].src = 'images/folder_closed.gif';
	ewicon[icx] = new Image(); ewicon[icx++].src = 'images/leaf.gif';
	ewicon[icx] = new Image(); ewicon[icx++].src = 'images/plus.gif';
	ewicon[icx] = new Image(); ewicon[icx++].src = 'images/minus.gif';
};

function ewtree (doc) {
	if (null == ewicon)
		preloadImages();
	this.nodes = new Array();
	this.list = null;
	this.seldex = -1;
	this.selnode = null;
	this.doc = doc;
	this.initvalue = '';
	this.expnode = null;
};

function gotNodeInfo (cbinfo,code,data) {
	var tnode = cbinfo[0];
	if (null != data){
		 if(isIE)
			data = fromUTF(data);
		 else
		  	data = unescape(data);
		}
	if ('details' == cbinfo[1]) {
		tnode.setDetails(data);
	}
	else if ('info' == cbinfo[1]) {
		tnode.setNodes(data);
	}
	refreshtreeview();
};

ewtree.prototype.setNodeInfo = function (query, cbinfo) {
	var handler = datatreeDetailsHandler;
	if(isIE)
	query = toUTF(query);
	var url = getBaseURL()+handler+'?uid=' + document.ent_form.uid.value + '&query=' +query;
	getMessage(url,gotNodeInfo,cbinfo);
};

ewtree.prototype.selectNode = function (nodename) {
	this.initvalue = nodename;
	var nodefound = false;
	for (var ix = 0; ix < this.nodes.length; ++ix) {
		var node = this.nodes[ix];
		if (node.name == nodename) {
			node.select(true);
			nodefound = true;
			break;
		}
		else if (0 == nodename.indexOf(node.name+'-')) {
			nodefound = node.selectNode(nodename.substr(node.name.length+1));
			if (nodefound)
				break;
		}
	}
	if (nodefound) {
		refreshtreeview();
	}
};

ewtree.prototype.addToList = function (node) {
	var item = this.list.length;
	this.list[item] = node;
	node.item = item;
	for (var ix = 0; ix < node.nodes.length; ++ix)
		this.addToList(node.nodes[ix]);
};

ewtree.prototype.sortList = function () {
	if (0 == this.nodes.length)
		return;
	this.list = new Array();
	for (var ix = 0; ix < this.nodes.length; ++ix){
		if( ix == this.nodes.length -1)
			this.nodes[ix].lastnode = true;
		this.addToList(this.nodes[ix]);
	}
};

ewtree.prototype.addTreeNode = function (tnode) {
	tnode.datatree = this;
	this.nodes[this.nodes.length] = tnode;
};

ewtree.prototype.displaystr = function () {
	if (0 == this.nodes.length)
		return '<b>no tree</b>';
	this.sortList();
	var str = '';
	for (var ix = 0; ix < this.nodes.length; ++ix)
		str += this.nodes[ix].displaystr();
	return str;
};

function ewtnode (parent, nodeinfo) {
	var info = nodeinfo.split('|');
	this.parent = parent;
	if(isIE)
		this.name = fromUTF(info[0]);
	else
		this.name = unescape(info[0]);
	this.numnodes = (info[1])*1;
	this.icon = null;
	this.isopen = false;
	this.isselected = false;
	this.level = 0;
	this.nodes = new Array();
	this.item = 0;
	this.nodepath = ((null != parent) ? parent.nodepath+'-' : '') + this.name;
	this.datatree = (null != parent) ? parent.datatree : null;
	this.details = null;
	this.detailsloaded = false;
	this.lastnode = false;
	this.open_icon = (null != info[2]) ? info[2] : 'images/folder_open.gif';
	this.close_icon = (null != info[3]) ? info[3] : 'images/folder_closed.gif';
	if (0 == this.numnodes) {
		this.open_icon = this.close_icon = (null != info[3]) ? info[3] : 'images/leaf.gif';
	}
};

ewtnode.prototype.open = function () {
	this.isopen = !this.isopen;
	if (null != this.datatree)
		this.datatree.expnode = this;

	if (this.isopen && this.numnodes > 0 && this.nodes.length == 0)
		this.loadNodes();

	if ( !this.isopen || (this.isopen && this.numnodes > 0 && this.nodes.length > 0) )
		this.setNodeState();
};

ewtnode.prototype.select = function (isselected) {
	this.isselected = isselected;
	if (null != this.datatree)
		this.datatree.selnode = (isselected) ? this : null;

	if ( isselected )
		this.details = this.getDetails();
};

ewtnode.prototype.selectNode = function (nodename) {
	if (!this.isopen) {
		this.open();
	}
	if (0 == this.nodes.length) {
		setTimeout('mytreeinitvalue()',100);
		return;
	}
	for (var ix = 0; ix < this.nodes.length; ++ix) {
		var node = this.nodes[ix];
		if (node.name == nodename) {
			node.select(true);
			return true;
		}
		else if (0 == nodename.indexOf(node.name+'-')) {
			if (node.selectNode(nodename.substr(node.name.length+1)))
				return true;
		}
	}
	return false;
};

ewtnode.prototype.addNode = function (len,ix,nodeinfo) {
	var node = new ewtnode(this,nodeinfo);
	node.level = this.level+1;
	if(len-1 == ix)
		node.lastnode = true;
	this.nodes[this.nodes.length] = node;
};

ewtnode.prototype.setDetails = function (details) {
	this.details = details;
	this.detailsloaded = true;
};

ewtnode.prototype.getDetails = function () {
	if ( useClientEvent() ) {
		var uid = -1;
		if (null != document.ent_form && null != document.ent_form.uid)
			uid = document.ent_form.uid.value;

		processClientAction(uid, 'getzoomtext', 'nodedetails', this.nodepath, '', '');
		return '';
	}
	this.datatree.setNodeInfo('nodedetails:'+this.nodepath,[this,'details']);
	return '';
};

ewtnode.prototype.setNodes = function (infostr) {
	if (null == infostr || '' == infostr)
		return;
	var strs = infostr.split('|||');
	for (var ix = 0; ix < strs.length; ++ix)
		this.addNode(strs.length,ix,strs[ix]);
};

ewtnode.prototype.loadNodes = function () {
	if ( useClientEvent() ) {
		var uid = -1;
		if (null != document.ent_form && null != document.ent_form.uid)
			uid = document.ent_form.uid.value;

		processClientAction(uid, 'getchildnodes', 'nodeinfo', this.nodepath, '', '');

	}
	else
		this.datatree.setNodeInfo('nodeinfo:'+this.nodepath,[this,'info']);
};

ewtnode.prototype.setNodeState = function () {
	if ( useClientEvent() ) {
		var uid = -1;
		if (null != document.ent_form && null != document.ent_form.uid)
			uid = document.ent_form.uid.value;

		processClientAction(uid, 'setnodestate', 'nodestate', this.nodepath, '', '');
	}
	else {
		this.datatree.setNodeInfo('nodestate:'+this.nodepath,[this,'info']);
		refreshtreeview();
	}
};

ewtnode.prototype.displaystr = function () {
	var str = '';	var lastid= "";
	if(this.lastnode){
	  lastid = "lastid";
	  this.lastnode = false;
	  }
	str += '<table id ="' + lastid +'"border=0 cellspacing=0 cellpadding=0>';
	str += '<tbody class="ewtablebody">';
	str += '<tr><td width=14 nowrap>';
	if (this.isopen) {
		str += '<span title="Collapse" onclick="return nodeexpand('+this.item+');">';
		str += '<img src="images/minus.gif" border=0 align="center">';
		str += '</span>';
	}
	else if (this.numnodes > 0) {
		str += '<span title="Expand" onclick="return nodeexpand('+this.item+');">';
		str += '<img src="images/plus.gif" border=0 align="center">';
		str += '</span>';
	}
	else {
		str += '&nbsp;';
	}
	str += '</td><td nowrap';
	if (this.isselected){
		str += ' class="ewselectTreeNode"';
		}
	str += '>';
	str += '<span style="cursor:default;" onclick="return nodeselect('+this.item+');" ondblclick="return nodeexpand('+this.item+');">';
	if (this.isopen) {
		str += '<img src="' + this.open_icon + '" border=0>';
	}
	else if (this.numnodes > 0) {
		str += '<img src="' + this.close_icon + '" border=0>';
	}
	else {
		str += '<img src="' + this.open_icon + '" border=0>';
	}
	str += this.name;
	str += '</span>';

	str += '</td></tr>';
	if (this.isopen) {
		str += '<tr><td></td><td>';
		for (var ix = 0; ix < this.nodes.length; ++ix)
			str += this.nodes[ix].displaystr();
		str += '</td></tr>';
	}
	str += '</tbody>';
	str += '</table>';

	if (this.isselected) {
		var nn = document.getElementById('nodename');
		if ( nn != null )
			nn.innerHTML = this.nodepath;
		var nd = document.getElementById('nodedetails');
		if ( nd != null ) {
			nd.innerHTML = this.details;
			var val = document.getElementById('nodedetails').innerText
			document.getElementById('nodedetails').innerHTML = val;
		}	
	}
	return str;
};

var mytree = null;

function treeSubmit (ctrl) {
	mytree = null;
	var form = document.ent_form;
	form.ctrlName.value = ctrl;
	form.ctrlValue.value = document.getElementById('nodename').innerHTML;
	form.target = "";
	form.method = "post";
	
	var handler;
	if ('undefined' != typeof(formHandler)) 
		handler = formHandler;
	else
		handler = form.action;

	var url = getBaseURL() + handler + '?';
	var value = document.getElementById('nodename').innerHTML;
	var name = ctrl;
	url += 'uid=' + form.uid.value;
	url += '&name=' + toUTF(name);
	url += '&value=' + toUTF(''+value);
					
	if ( useClientEvent() ) 
		processClientAction(form.uid.value, 'formreplace', name, value, '', '');
	else 
		location.replace(url);

	return false;
};

function mytreeinitvalue () {
	mytree.selectNode(mytree.initvalue);
};

function refreshtreeview () {
	if (null == mytree)
		return;
	document.getElementById('ewtreeview').innerHTML = mytree.displaystr();
	var elem = document.getElementById('lastid');
	if(elem)
		elem.scrollIntoView(false);
};

function nodeexpand (dex) {
	if (null == mytree)
		return false;
	var node = mytree.list[dex];
	if (null == node)
		return false;
	node.open();
	return false;
};

function nodeselect (dex) {
	if (null == mytree)
		return false;
	var node = mytree.list[dex];
	if (null == node || mytree.selnode == node)
		return false;
	if (null != mytree.selnode)
		mytree.selnode.select(false);
	node.select(true);
	return false;
};

function treeRefresh(treenodes) {
	mytree = null;
	eval(treenodes);
	refreshtreeview();

	if (null != document.body.style)
		document.body.style.cursor = 'auto';
};

function setSelectedNodeDetails( details ) {
	if ( mytree != null && mytree.selnode != null ) { 
		mytree.selnode.setDetails( details );
		refreshtreeview();	
	}
	if (null != document.body.style)
		document.body.style.cursor = 'auto';
};
function addChildNodes( info ) {
	if ( mytree != null && mytree.expnode != null ) { 
		mytree.expnode.setNodes( info );
		refreshtreeview();	
	}
	if (null != document.body.style)
		document.body.style.cursor = 'auto';
};



var WF_FORM = '2';
var WF_QUERY = '3';
var WF_DATATREE = '4';
var WF_CHART = '5';
var WF_CALENDAR = '6';
var WF_REPORT = '7';
var WF_TM1CUBEVIEWER = '8';
var WF_DASHBOARD = '9';
var WF_CONTAINER = '10';
var WF_LABEL = '11';
var WF_BUTTON = '12';
var WF_IMAGE = '13';
var WF_COMBOBOX ='14';
var WF_WEBFRAME = '15';

var WF_EVENT_OBJECT_CHANGED = '0';  
var WF_EVENT_TITLEELEMENT_CHANGED = '1';
var WF_EVENT_NEW_OBJECT = '2';
var WF_EVENT_DATA_REFRESH = '3';
var WF_EVENT_ZOOMTEXT_CHANGED = '4';
var WF_EVENT_OBJECT_REPLACE = '5';
var WF_EVENT_CHILDNODES_ADDED = '6';
var WF_EVENT_SET_NODESTATE = '7';
var WF_EVENT_CALLER_REFRESH='8';
var WF_EVENT_OBJECT_CLOSE = '9';
var SHIFT_KEY = 1;
var CTRL_KEY = 2;

var ENT_SPREAD_PROPORTIONAL = 1; 
var ENT_SPREAD_EQUAL = 2;	        
var ENT_SPREAD_REPEAT = 3;	        
var ENT_SPREAD_CLEAR = 4;	        
var ENT_SPREAD_PERCENT = 5;	        
var ENT_SPREAD_LINE = 6;	        
var ENT_SPREAD_GROWTH = 7;	        
var ENT_SPREAD_RELATIVE_PROP = 8;	
var ENT_SPREAD_RELATIVE_PCT = 9;	
var ENT_SPREAD_LEAF_REPEAT = 10;	    
var ENT_SPREAD_LEAF_CLEAR = 11;	    
var ENT_SPREAD_LEAF_SPREAD = 12;	    
var ENT_SPREAD_HOLD = 13;	        
var ENT_SPREAD_RELEASE = 14;	        
var ENT_SPREAD_RELEASE_ALL = 15;	    
var ENT_SPREAD_RELATIVE = 16;	

var m_curWindowNum;
var m_RegisteredWindows = new Array();

function refresh (win) { 
	win.location.reload();
};



function lookupFrame (frameName) { 
	return getFrame(window.top, frameName);
};

function getFrame (win, frameName) { 
	for (var ix = 0; ix < win.frames.length; ix++) {
		if (win.frames[ix].name == frameName) {
			return win.frames[ix];
		}
		else {
			var f = getFrame(win.frames[ix].window, frameName);
			if (f) {
				return f;
			}
		}
	}
	return null;
};

function lookupNearestFrame(frameName, stopAtFrame) {
	if (stopAtFrame == null)
		stopAtFrame = window.top.name;
	return getNearestFrame(window.parent, frameName, stopAtFrame);
};

function getNearestFrame (win, frameName, stopAtFrame) {
	if (win.name == frameName)
		return win;
	for (var ix = 0; ix < win.frames.length; ix++) {
		if (win.frames[ix].name == frameName) {
			return win.frames[ix];
		} else {
			var f = getFrame(win.frames[ix].window, frameName);
			if (f) {
				return f;
			}
		}
	}
	if (win.name == stopAtFrame)
		return stopAtFrame;

	return getNearestFrame(win.parent, frameName, stopAtFrame);
};

function getNearestEnclosingWindow (frameNames) {
	var returnParam = new Array();
	getEnclosingWindow (window.parent, frameNames, returnParam);
	return returnParam[0];
};

function getEnclosingWindow (win, frameNames, returnParam) {
	if (allInWindow(win, frameNames)) {
		returnParam[0] = win;
	}
	else  if (win != win.parent) {
		getEnclosingWindow(win.parent, frameNames, returnParam);
	}
	else
		returnParam[0] = null;
	
};

function allInWindow (parentWindow, frameNames) {
	for (var ix = 0; ix < frameNames.length; ix++) {
		if (!inWindowR(parentWindow, frameNames[ix])) {
			return false;
		}
	}
	return true;
};

function inWindowR (parentWindow, kidFrame) {
	if (inWindow(parentWindow, kidFrame)) {
		return true;
	}
	for (var ix = 0; ix < parentWindow.frames.length; ix++) {
		if (inWindowR(parentWindow.frames[ix].window, kidFrame)) {
		return true;
		}
	}
	return false;
};

function inWindow (parentWindow, kidFrame) {
	for (var ix = 0; ix < parentWindow.frames.length; ix++) {
		if (parentWindow.frames[ix].name == kidFrame) {
		return true;
		}
	}
	return false;
};

function getRef (href) {
	this.window.location.replace(href);
};

function toggleframe () {
	showProps(window.parent, 'parent');
};


var bDoneLogout;
var bWarningon;
function onLogout()
{
	if ( !useClientEvent() ) {
		bDoneLogout = true;
	 	var url = mainHandler + "?actiontype=logout&logintype=rep&interface=menu";
	      	parent.window.location.replace(url);
		return;
	}

	url = mainHandler + "?actiontype=logout&logintype=rep&interface=menu";
    	m_clientframe.clientLogout(url);
};

function doTimeout(mainHandler)
{
	if ( mainHandler == null )
		return;

 	setNewWindowState();
	setWarningOff();
	var url = getBaseURL() + mainHandler + "?actiontype=timeout";
 
 	if ( useClientEvent() ) 
 		m_clientframe.clientLogout(url);
 	else	
 		location.replace(url);
};

function clientLogout(url)
{
	bDoneLogout = true; 
    	var bClosedAll = closeAllNewWindows();
	if ( isWarningOn() && bClosedAll == false ) {	
		setTimeout('resetWarningState()', 500);
		return;
	}
	if( (window.location.href).indexOf("cst_sync_window.jsp") != -1)
		return;
	processClientAction('0', 'logout', 'ewlogout', url, '', '');
};

function doLogout()
{
	if ( mainHandler == null )
		return;

    	if ( bDoneLogout != true ) {
    		setWarningOff();
    		onLogout();
    	}
};
function cst_doLogout()
{
	if ( mainHandler == null )
		return;

    	if ( bDoneLogout != true ) {
    		setWarningOff();
    	}
};
function onFrameExit()  {

	if ( bDoneLogout != true  && bWarningon != true )  {
     	// XLT
     	event.returnValue = "Do you want to logout?";
     	bWarningon = true;
     	setTimeout('resetWarning()', 500);	
     		
     		
  	}
};

function resetWarning(){
	bWarningon = false;
};


function onWindowExit()  {
	if ( bDoneLogout != true )  {
     		// XLT
     		event.returnValue = "Do you want to logout?";
     		bDoneLogout = false;  
  	}
};
function cst_onWindowExit(){
	
	if ( bDoneLogout != true )  {
     		// XLT
     		bDoneLogout = false;  
  	}
};


var c = 0;
function showTooltip (el) {

	window.status = el.title;
}

function hideTooltip (el) {

	window.status = '';
}

function getUniqueWindowName() {
	if ( useClientEvent() )
		return m_clientframe.generateUniqueWinName();
	else
		return null;
};

function generateUniqueWinName() {
	if (typeof(m_curWindowNum) == "undefined")
		m_curWindowNum = 0;
	var name = "AxWindow" + m_curWindowNum;
	m_curWindowNum = Number(m_curWindowNum) + 1;
	return name;
};

function RegisterExportWindow(winName, winHandle) {
	if (typeof(m_curWindowNum) == "undefined")
		m_curWindowNum = 1;
	var newObj = new ExportWindowObj(winName, winHandle);
	m_RegisteredWindows[m_RegisteredWindows.length] = newObj;
}

function ExportWindowObj(winName, winHandle) {
	this.m_winName = winName;
	this.m_winHandle = winHandle;
}

function findWindow(winName) {
	var i, win=null;
	for (i=0; i<m_RegisteredWindows.length; i++) {
		if (m_RegisteredWindows[i].m_winName == winName)
			win = m_RegisteredWindows[i].m_winHandle;
	}
	if (win != null)
		m_RegisteredWindows.splice(i, 1);
	return win;
}

function executeURL(url, refresh_type) {
	if ( useClientEvent() ) {
		var queryString;
		var idx = url.indexOf('?');
		if (idx < 0)
			return;
		queryString = url.substr(idx+1);

		var uid = null;
		if (null != document.ent_form && null != document.ent_form.uid)
			uid = document.ent_form.uid.value;

		if ( uid == null ) {
			var mainFrm = lookupNearestFrame("AxMdbrowserMain");
			if (mainFrm != null || typeof(mainFrm) != "undefined")
				uid = mainFrm.frameElement.getAttribute("objid");
			if ( uid == null )
				uid = -1;
		}
		processClientAction(uid, "cubeviewerevent", "querystring", queryString, refresh_type, "");
	}
}

var REFRESH_NONE = '0';
var REFRESH_GRID = '1';
var REFRESH_TOOLBAR = '2';
var REFRESH_TITLESBAR = '3';
var REFRESH_CUBETREE = '4';
var REFRESH_COLUMNS = '5';
var REFRESH_NONE_CONTINUE_EDIT = '6';

var CONTINUE_EDIT = '1';

function dispatchFrameResponse(refresh_type) {
	switch ( refresh_type ) {
	case REFRESH_GRID:
		refreshDataGrid();
		break;
	case REFRESH_TOOLBAR:
		refreshSelf();
		break;
	case REFRESH_TITLESBAR:
		refreshTitlesFrame();
		break;
	case REFRESH_CUBETREE:
		resetCubeTree();
		break;
	case REFRESH_COLUMNS:
		refreshCubeColumnsFrame();
		break;
	case REFRESH_NONE_CONTINUE_EDIT:
		startCellEdit();
		break;
	case REFRESH_NONE: 
		refreshMessenger();
		break;
	}
};

var m_bDashObj = null;
var m_dbframe = null;
function isDashObject() {
	if ( m_bDashObj == null ) {
		m_dbframe = lookupFrame('frm_dashboard');
		if ( m_dbframe != null ) {
			m_bDashObj = true;
		}
		else
			m_bDashObj = false;
	}
	return m_bDashObj;
};

var m_enableClientEvent = true;	
var m_bUseClientEvent = null;
var m_clientframe = null;
function useClientEvent() {
	if ( !m_enableClientEvent )
		return false;

	if ( m_bUseClientEvent == null ) {
		m_clientframe = lookupFrame('sync_window');
		if ( m_clientframe != null ) {
			m_bUseClientEvent = true;
		}
		else {
			m_bUseClientEvent = false;
		}
	}
	return m_bUseClientEvent;
};

var prev = null;
var isPopupWindow = false;
function setNewWindowState() {
	if ( !m_enableClientEvent )
		return false;

	if ( top.window.opener == null || typeof(top.window.opener) == 'undefined' )
		return false;

	isPopupWindow = true;
	prev = top.window.opener;
	m_bUseClientEvent = prev.m_bUseClientEvent;
	m_clientframe = prev.m_clientframe;
	return true;
};

function cacheNewWindow(win) {
	if ( useClientEvent() )
		m_clientframe.storeNewWindow(win);
	else
		storenewPopUpWindow(win);
	
};

function storenewPopUpWindow(win){
	var asyncframe = getFrameFromTop(win.opener.top ,'asyncwin');
	if( asyncframe != null)
		asyncframe.winlist[0] = win;
};

var winlist = new Array();
function storeNewWindow(win) {
	winlist[winlist.length] = win;
};

function lookupWindowByName(name) {
	if ( !useClientEvent() )
		return null;

	for (var i = 0; i < m_clientframe.winlist.length; i++ )
	{
		try {
			if ( m_clientframe.winlist[i] != null ) {
				if ( m_clientframe.winlist[i].closed ) {
					m_clientframe.winlist[i] = null;
					continue;
				}
				if ( m_clientframe.winlist[i].name == name ) {
					return m_clientframe.winlist[i];
				}
			}	
		}
		catch (e) {
			m_clientframe.winlist[i] = null;
			continue;
		}
	}
	return null;
};

function closeWindow(win) {
	if ( !useClientEvent() )
		return false;

	for (var i = 0; i < m_clientframe.winlist.length; i++ )
	{
		try {
			if ( m_clientframe.winlist[i] == win ) {
				m_clientframe.winlist[i] = null;
				if ( win.closed == false )
					win.close();
				return true;
			}
		}
		catch (e) {
			m_clientframe.winlist[i] = null;
			continue;
		}
	}
	return false;
};

function closeAllNewWindows() {
	var bClosedAll = true;
	for (var i = 0; i < winlist.length; i++)  {
	    try {
		if ( winlist[i] != null )  {
			winlist[i].close();
			if ( winlist[i].closed )
				winlist[i] = null;
			else
				bClosedAll = false;
		}
	    }
	    catch (e)  {
		winlist[i] = null;
	    	continue;
	    }
	}
	return bClosedAll;
};

function storePopupWinHandle(handle)  
{
	cacheNewWindow(handle);
};

function getPopupWinHandle(win_name)
{
	return lookupWindowByName(win_name);
};

function closeWindowByName(win_name)
{
	if ( !useClientEvent() )
		return false;

	for (var i = 0; i < m_clientframe.winlist.length; i++)  {
	    try {	
		if ( m_clientframe.winlist[i] != null ) {
			if ( m_clientframe.winlist[i].closed ) {
				m_clientframe.winlist[i] = null;
				continue;
			}
			if ( m_clientframe.winlist[i].name == win_name )  {
				m_clientframe.winlist[i].close();
				m_clientframe.winlist[i] = null;
				return true;
			}
		}
	    }
	    catch(e) {
		m_clientframe.winlist[i] = null;
	    	continue;
	    }
	}
	return false;
};

function closeAllPopupWindows()
{
	if ( !useClientEvent() )
		return;

	return m_clientframe.closeAllNewWindows();
};

function processClientAction(objid, method, name, value, row, col, hCaller) {
	if ( !useClientEvent() )
		return;

	if ( m_clientframe.document.readyState != 'complete' || localactionqueue.length > 0 ) {
		localactionqueue[localactionqueue.length] = new localaction(objid, method, name, value, row, col, hCaller);
		setTimeout('processPendingLocalAction();', 200);

		if (null != document.body.style)
			document.body.style.cursor = 'wait';

		return;
	}
	submitClientAction(objid, method, name, value, row, col, hCaller);
};

function submitClientAction(objid, method, name, value, row, col, hCaller) {
	if ( m_clientframe.waitingForResponse ) {
		m_clientframe.addClientActionToQueue(objid, method, name, value, row, col, hCaller);
		return;
	}
	m_clientframe.executeClientAction(objid, method, name, value, row, col, hCaller);
};


var localactionqueue = new Array();
function localaction(objid, method, name, value, row, col, hCaller) {
	this.objid = objid;
	this.method = method;
	this.name = name;
	this.value = value;
	this.row = row;
	this.col = col;
	this.hCaller = hCaller;
};

localaction.prototype.process = function () {
	submitClientAction(this.objid, this.method, this.name, this.value, this.row, this.col, this.hCaller);
};

function processPendingLocalAction() {
	if ( localactionqueue.length > 0 ) {
		if ( m_clientframe.document.readyState == 'complete' ) {
			var la = localactionqueue[0];
			localactionqueue = localactionqueue.slice(1);
			la.process();
		}
		setTimeout('processPendingLocalAction();', 200);
	}
	else {
		if (null != document.body.style)
			document.body.style.cursor = 'auto';
	}
};



var ewupdatequeue = new Array();
function applyUpdate(hFrame, eventtype, objid, objtype, data) {
	
	if ( hFrame.document.readyState != 'complete' || ewupdatequeue.length > 0 ) {
		ewupdatequeue[ewupdatequeue.length] = new ewupdate(hFrame, eventtype, objid, objtype, data);
		setTimeout('processPendingUpdate();', 300);
		return;
	}
	else if ( objtype == WF_FORM ) {
		var objmain = hFrame.window.frames['AxObjectMain'];
		if ( objmain != null ) {
			if ( objmain.document.readyState != 'complete' ) {
				ewupdatequeue[ewupdatequeue.length] = new ewupdate(hFrame, eventtype, objid, objtype, data);
				setTimeout('processPendingUpdate();', 300);
				return;
			}
		}
	}
	runUpdate(hFrame, eventtype, objid, objtype, data);
};

function runUpdate(hFrame, eventtype, objid, objtype, data) {
	try {
		switch ( eventtype ) {
		case WF_EVENT_DATA_REFRESH:
			if ( verifyUpdatingObject(hFrame, objid, objtype) ) 
				hFrame.refreshDataGrid();
			break;

		case WF_EVENT_TITLEELEMENT_CHANGED:
			if ( verifyUpdatingObject(hFrame, objid, objtype) ) 
				hFrame.resetTitlesFrame();
			break;

		case WF_EVENT_CALLER_REFRESH:
			if ( verifyUpdatingObject(hFrame, objid, objtype) ) 
				hFrame.dispatchFrameResponse(data);
			break;

		case WF_EVENT_ZOOMTEXT_CHANGED:
			if ( verifyUpdatingObject(hFrame, objid, objtype) ) {
				if ( objtype == WF_DATATREE ) {
					hFrame.setSelectedNodeDetails(data);
				}
				else if ( objtype == WF_QUERY ) {
					hFrame.setQueryZoomText(data);
				}
			}
			break;

		case WF_EVENT_CHILDNODES_ADDED:
			if ( verifyUpdatingObject(hFrame, objid, objtype) ) 
				hFrame.addChildNodes(data);
			break;

		case WF_EVENT_SET_NODESTATE:
			if ( verifyUpdatingObject(hFrame, objid, objtype) ) 
				hFrame.refreshtreeview();
			break;

		case WF_EVENT_OBJECT_CHANGED:
			switch ( objtype )  {
			case WF_LABEL:
			case WF_BUTTON:
			case WF_IMAGE:
			case WF_COMBOBOX:
				hFrame.ctrlRefresh(data);
				break;

			case WF_FORM:
				if ( verifyUpdatingObject(hFrame, objid, objtype) ) {
					var objmain = hFrame.window.frames['AxObjectMain'];
					if ( objmain != null ) 
						objmain.updateewvalues(data);
				}
				break;

			case WF_QUERY:
				break;
			case WF_DATATREE:
				if ( verifyUpdatingObject(hFrame, objid, objtype) ) 
					hFrame.treeRefresh(data);
				break;

			case WF_TM1CUBEVIEWER:
				if ( verifyUpdatingObject(hFrame, objid, objtype) ) 
					hFrame.refreshCubeviewer();
				break;

			case WF_DASHBOARD:
				if ( verifyUpdatingObject(hFrame, objid, objtype) ) 
					hFrame.updateDashboardObjects(data);
				break;

			case WF_WEBFRAME:
				if ( verifyUpdatingObject(hFrame, objid, objtype) ) {
					var frm_url = hFrame.window.frames['web_url'];
					if ( frm_url != null )
						frm_url.location.replace(data);
				}
				break;
			default:
				break;
			}
			break;

		case WF_EVENT_OBJECT_REPLACE:
		case WF_EVENT_OBJECT_CLOSE:
		case WF_EVENT_NEW_OBJECT:	
			var url = m_baseURL + filesourceHandler + '?objid=' + objid;
			setWarningOff();
			hFrame.location.replace( url );
			setWarningOn();
			break;

		default:
			break;
		}
	}
	catch(e) {}
};

function verifyUpdatingObject(hFrame, objid, objtype) {
	var form = hFrame.document.ent_form;
	if ( form != null && form.uid.value == objid ) 
		return true;

	if ( objtype == WF_TM1CUBEVIEWER ) {
		var mainFrm = hFrame.lookupNearestFrame("AxMdbrowserMain");
		var uid = null;
		if (mainFrm != null && typeof(mainFrm) != "undefined")
			uid = mainFrm.frameElement.getAttribute("objid");

		if ( uid == objid )
			return true;
	}
	return false;
};

function ewupdate(hFrame, eventtype, objid, objtype, data) {
	this.hFrame = hFrame;
	this.eventtype = eventtype;
	this.objid = objid;
	this.objtype = objtype;
	this.data = (typeof(data) == 'undefined')? null : data;
};

ewupdate.prototype.process = function () {
	runUpdate(this.hFrame, this.eventtype, this.objid, this.objtype, this.data);
};

function processPendingUpdate() {
	if ( ewupdatequeue.length > 0 ) {
		var eu = ewupdatequeue[0];
		try {
			if ( eu.hFrame.document.readyState == 'complete' ) {
				if ( eu.objtype == WF_FORM ) {
					var objmain = eu.hFrame.window.frames['AxObjectMain'];
					if ( objmain != null ) {
						if ( objmain.document.readyState == 'complete' ) {
							ewupdatequeue = ewupdatequeue.slice(1);
							eu.process();
						}
					}
					else 
						ewupdatequeue = ewupdatequeue.slice(1);
				}
				else {
					ewupdatequeue = ewupdatequeue.slice(1);
					eu.process();
				}
			}
		}
		catch(e) {	
			ewupdatequeue = ewupdatequeue.slice(1);
		}
		setTimeout('processPendingUpdate();', 300);
	}
};


function onObjectClose()  {
	if (null != document.body.style)
		document.body.style.cursor = 'wait';
	if (window.name == 'AxMdbrowserMain')
		closeCubeviewerDependentWindows();
	if ( !isPopupWindow )
		return;

	if ( !useClientEvent() )
		return;

	var winname = top.window.name;
	m_clientframe.processObjectClose(winname);	
};

function closeCubeviewerDependentWindows() {
	try {
		var editWin = getPopupWinHandle('AxMdbrowserEditor');
		if (typeof(editWin) != "undefined" && editWin != null) {
			if (editWin.closed == false)
				editWin.close();
		}
		var persWin = getPopupWinHandle('AxPersonalizeViewSettings');
		if (typeof(persWin) != "undefined" && persWin != null) {
			if (persWin.closed == false)
				persWin.close();
		}
	} catch (e) {}
}

function beforeObjectClose() {
	if (null != document.body.style)
		document.body.style.cursor = 'wait';
	if ( !useClientEvent() ){
		if(top.window.opener != null || typeof(top.window.opener) != 'undefined' ) {
			if (event.clientY < 0){
				var form = document.forms['ent_form'];
				if ( form != null || "undefined" != form){
					var handler;
					if ('undefined' != typeof(formHandler)) 
						handler = formHandler;
					else
						handler = form.action;
					var url = getBaseURL() + handler + '?';
					url += 'uid=' + top.window.name;
					url += '&name=frm_cancel';
					url += '&value=popup_cancel';
					url += '&row=""';
					url += '&col=""';
					location.replace(url);
					}
				}
			}
		return;
	}

	if ( !isWarningOn() || !m_bWindowClose ) {
		if (window.name == 'AxToolbar' && m_bWindowClose)
			closeCubeviewerDependentWindows();
		return;
	}

	if ( isDashObject() ) {
		var str = getModifiedObjects();
		if ( str != null && str != '' ) {
			// XLT
			var confirmStr = 'Following dashboard object(s) has changed:' + '\n';
			confirmStr = confirmStr + str;
			// XLT
			confirmStr = confirmStr + 'Click OK to exit without saving changes.';
			event.returnValue = confirmStr;
			return;
		}
	}
	else if ( window.name == 'AxToolbar' ) {		
		if (m_bDisplayToolbar && m_bViewModified) {
			// XLT
			var str = "By closing the view, you will lose any unsaved information. Continue?"; 
			event.returnValue = str;
			return;
		}
		var persWin = getPopupWinHandle('AxPersonalizeViewSettings');
		if (typeof(persWin) != "undefined" && persWin != null && m_bDisplayToolbar) {
			// XLT
			var str = "By closing the view, you will lose unsaved changes in the personalization editor. Continue?";
			event.returnValue = str;
			return;
		}
	}
	else {	
		var form = window.document.ent_form;
		if ( null != form && null != form.modified && '0' != form.modified.value ) {
			event.returnValue = confirmDiscardLabel;
			return;
		}
		if ( top.window.opener != null || typeof(top.window.opener) != 'undefined' ) {
			top.window.close();
		}
	}
};

var m_bDoWarning = true;
function setWarningOn() {
	if ( !useClientEvent() )
		return;

	if ( m_clientframe.document.readyState != 'complete' )
		return;

	m_clientframe.m_bDoWarning = true;
};

function setWarningOff() {
	if ( !useClientEvent() )
		return;

	if ( m_clientframe.document.readyState != 'complete' )
		return;

	m_clientframe.m_bDoWarning = false;
};

function isWarningOn() {
	if ( !useClientEvent() )
		return false;

	if ( m_clientframe.document.readyState != 'complete' )
		return false;

	return m_clientframe.m_bDoWarning;
};

function resetWarningState() {
	bDoneLogout = false; 
	setWarningOn();
};
var m_bWindowClose = true;
function setWindowClose(bBool) {
	m_bWindowClose = bBool;
};

function processObjectClose(winname) {
	if ( !bDoneLogout )
		setTimeout('checkForWindowClose(' + winname + ');', 100);
};

function checkForWindowClose(winname) {
	if ( lookupWindowByName(winname) == null ) {
		processClientAction(winname, 'windowclose', 'close', 'close', '', '');
	}
};


function ewobject (objid, isModified, objName) {
	this.objid = objid;
	this.name = objName;
	this.isModified = isModified;
};

var m_objList = new Array();
function setObjectModified(objid, isModified, objName) {
	if ( isDashObject() ) {
		if ( m_dbframe.document.readyState != 'complete' )
			setTimeout('setObjectModified(' + objid + ',' + isModified + ',' + objName + ')', 300);
		else {
			m_dbframe.updateObjectStatus(objid, isModified, objName);
		}
	}
};

function updateObjectStatus(objid, isModified, objName) {
	for ( var ix = 0; ix < m_objList.length; ix++ ) {
		if ( m_objList[ix] != null && m_objList[ix].objid == objid ) {
			m_objList[ix].isModified = isModified;
			return;
		}
	}
	m_objList[m_objList.length] = new ewobject(objid, isModified, objName);
};

function removeClosedObject(objid) {
	for ( var ix = 0; ix < m_objList.length; ix++ ) {
		if ( m_objList[ix] != null && m_objList[ix].objid == objid ) {
			m_objList[ix] = null;
			return;
		}
	}
};

function setObjectClosed(objid) {
	if ( isDashObject() ) {
		m_dbframe.removeClosedObject(objid);
	}
};

function getModifiedObjects() {
	var retstr = '';
	for ( var ix = 0; ix < m_objList.length; ix++ ) {
		if ( m_objList[ix] != null && m_objList[ix].isModified != '0' ) {
			retstr = retstr + m_objList[ix].name + '\n';
		}
	}
	return retstr;
};


var m_baseframe = null;
function getBaseFrame() {
	if ( m_baseframe == null )
		m_baseframe = lookupFrameFromTop('frm_formarea');
	return m_baseframe;
};


function onToggleViewElement(href, window) {
	if (event) {
		event.cancelBubble = true;
		event.returnValue = false;
	}
	if (typeof(window) == "undefined" 			 || 
		window == null 							 || 
		window.document.readyState != "complete" || 
		window.document.body.style.cursor == 'wait')
		return;

	window.location.replace(href);
	window.document.body.style.cursor = 'wait';
}

function trim(inStr) {
	if (!inStr || '' == inStr)
		return inStr;
	var ch, outStr, ix, len, tmpStr;

	len = inStr.length;
	outStr = '';
	for (ix=0; ix<len; ix++) {
		ch = inStr.charAt(ix);
		if (ch != ' ') {
			outStr += inStr.substr(ix);
			break;
		}
	}
	tmpStr = outStr;
	len = tmpStr.length;
	outStr = '';
	for (ix=len-1; ix>=0; ix--) {
		ch = tmpStr.charAt(ix);
		if (ch != ' ') {
			outStr = tmpStr.substring(0, ix+1);
			break;
		}
	}
	return outStr;
}

function keyCodeIsDigit(code) {
	if ( code < 106 && code > 95 )
		return true;

	var codeStr = String.fromCharCode(code);
	var bDigit = '0123456789'.indexOf(codeStr);
	if (bDigit >= 0)
		return true;
	else
		return false;
}

function keyCodeIsAlphabet(code) {
	try {
		return ((code >= 'A'.charCodeAt(0) && code < 'Z'.charCodeAt(0)) ||
				(code >= 'a'.charCodeAt(0) && code < 'z'.charCodeAt(0))) 
	} catch(e) { return false; }
}

function keyCodeIsAlphaNumeric(code) {
	return 	keyCodeIsDigit(code) || 
			keyCodeIsAlphabet(code) || 
			keyCodeIsPlusMinusPeriod(code);
}

function keyCodeIsPlusMinusPeriod(code) {
	if (code == 187 || 		
		code == 107 ||		
		code == 189 || 		
		code == 109 ||		
		code == 190 ||		
		code == 110 		
		)
		return true;
	else
		return false;
}

var m_postwin = null;

function handleClientPostWindowXMLData() {
	if ( m_postwin == null ) 
		return;

	var xmlobject = m_postwin.document.getElementById('ewclient');
	if ( xmlobject != null ) {
		var xmldoc = xmlobject.XMLDocument;
		if ( xmldoc == null )
			return;

		updateClientObjects(xmldoc);
	}
};

function handleClientXMLData() {
	var ewclient = getElement('ewclient');

	if (isMac || null == ewclient)
		return;
	var xmldoc = ewclient.XMLDocument;
	var docstate = 0;
	if (null != xmldoc)
		docstate = xmldoc.readyState;
	if (docstate < 4)
		return;

	updateClientObjects(xmldoc);
};

function updateClientObjects (xmldoc) {
	var err = xmldoc.parseError;
    	if (err.errorCode != 0) {
// XLT
    		var errmsg = 'An error occured updating client objects.\n';
// XLT
    		errmsg += 'If the problem persists, please contact the webmaster';
		alert (errmsg);
	
		waitingForResponse = false;
		window.status = window.defaultStatus = '';
		if ( m_postwin != null ) {	
			m_postwin.close();
			m_postwin = null;
		}
		return;
    	}
	else {
		var root = xmldoc.documentElement;
		var nodes = root.childNodes;

		if (nodes == null) {
			window.status = window.defaultStatus = '';
			if (null != document.body.style)
				document.body.style.cursor = 'auto';
			waitingForResponse = false;

			if ( m_postwin != null ) {	
				m_postwin.close();
				m_postwin = null;
			}

			SetTimeout('executePendingClientAction()', 0);
			return;
		}

		for (var ix = 0; ix < nodes.length; ++ix) {
		   var node = nodes.item(ix);
		   if ('1' == node.getAttribute('iserror')) {
			var value = fromUTF(node.getAttribute('value'));
			alert(value);
	   	   }
	  	   else  {
			var objid = node.getAttribute('objid');
			var objName = node.getAttribute('name');
			var eventtype = node.getAttribute('event');
			var objType = node.getAttribute('type');
			
			var frm_obj = null;
			if ( objName == '_base' ) {
				frm_obj = getBaseFrame();
			}
			else if ( eventtype != WF_EVENT_NEW_OBJECT ) {
					frm_obj = lookupWindowByName(objName);
			}

			if (null == frm_obj && eventtype != WF_EVENT_NEW_OBJECT )
				continue;

			switch ( eventtype ) {
			case WF_EVENT_DATA_REFRESH:
			case WF_EVENT_CALLER_REFRESH:
				var value = node.getAttribute('value');
				var frm_tb = lookupFrameFromTop('AxToolbar', frm_obj);
				if ( frm_tb != null )
					applyUpdate(frm_tb, eventtype, objid, objType, value);
				break;

			case WF_EVENT_TITLEELEMENT_CHANGED:
				var frm_tb = lookupFrameFromTop('AxToolbar', frm_obj);
				if ( frm_tb != null )
					applyUpdate(frm_tb, eventtype, objid, objType);
				break;

			case WF_EVENT_ZOOMTEXT_CHANGED:
			case WF_EVENT_CHILDNODES_ADDED:
			case WF_EVENT_SET_NODESTATE:
				var value = node.getAttribute('value');
				var details = null;
				if ( value != null ) 
					details = fromUTF(value);
				applyUpdate(frm_obj, eventtype, objid, objType, details);
				break;

			case WF_EVENT_OBJECT_CHANGED:
				switch ( objType )  {
				case WF_FORM:
					applyUpdate(frm_obj, eventtype, objid, objType, node);
					break;

				case WF_QUERY:
					break;
				case WF_DATATREE:
					var treenodes = fromUTF(node.getAttribute('value'));
					applyUpdate(frm_obj, eventtype, objid, objType, treenodes);
					break;

				case WF_TM1CUBEVIEWER:
					var frm_tb = lookupFrameFromTop('AxToolbar', frm_obj);
					if ( frm_tb != null )
						applyUpdate(frm_tb, eventtype, objid, objType);
					break;

				case WF_DASHBOARD:
					var frm_db = lookupFrameFromTop('frm_dashboard', frm_obj);
					if ( frm_db != null )
						applyUpdate(frm_db, eventtype, objid, objType, node);
					break;

				default:
					break;
				}
				break;

			case WF_EVENT_OBJECT_REPLACE:
			case WF_EVENT_OBJECT_CLOSE:
				removeMenuHighlight();
				applyUpdate(frm_obj, eventtype, objid, objType);
				break;

			case WF_EVENT_NEW_OBJECT:
				if ( frm_obj != null ) { 
					applyUpdate(frm_obj, eventtype, objid, objType);
				}
				else {
					var frm_main = getBaseFrame();
					var url = m_baseURL + filesourceHandler + '?objid=' + objid;
					var height,width;
					height = frm_main.window.document.body.offsetHeight;
					width = frm_main.window.document.body.offsetWidth;
					var features = 'location=no,menubar=no,toolbar=no,fullscreen=no,resizable=yes,scrollbars=yes,status=yes,height=' + height + ',width=' + width;
					var winhandle = window.open(url, objName, features);
					cacheNewWindow(winhandle);
				}
				break;

			default:
				break;
			}
		   }	
		}
	}
	window.status = window.defaultStatus = '';
	if (null != document.body.style)
		document.body.style.cursor = 'auto';
	waitingForResponse = false;

	if ( m_postwin != null ) {	
		m_postwin.close();
		m_postwin = null;
	}
	setTimeout('executePendingClientAction()', 0);
};
function removeMenuHighlight(){
	if(parent.frames)
	{	
		var frm = lookupFrameFromTop("frm_entnavbar");
		if(frm!= null)
		{
			var doc = frm.document ;
			var folders = doc.getElementsByTagName('INPUT');
		
		 	for (var i=0;i<folders.length;i++) 
				{
				if(null!=folders && folders.length>0)
					{
					if(folders[i].style.background = "gold");
					   folders[i].style.background = "rgb(240,240,240)";
					 }
				}
		}
	}
};



var m_baseURL;
function initClientEvent() {
	m_baseURL = getBaseURL();
	useClientEvent();
};

var clientactionqueue = new Array();
function checkCallerModified(objid, name, hCaller) {
	try {
		if ( hCaller != null && typeof(hCaller) != 'undefined' ) {
			if ( 'close' == name ) {
				var str = hCaller.getModifiedObjects();
				if ( str != null && str != '' ) {
// XLT
					var confirmStr = 'Following dashboard object(s) has changed:' + '\n';
					confirmStr = confirmStr + str;
// XLT
					confirmStr = confirmStr + 'Click OK to exit without saving changes.';
					var discard = confirm(confirmStr);
					if (!discard) {
						return true;
					}
				}
			}
			else {		
				var form = hCaller.window.document.ent_form;
				if ( null != form && null != form.modified ) {
					if ('frm_cancel' == name || 'frm_clear' == name || 'frm_new' == name) {
						if ( '0' != form.modified.value ) {
							var discard = confirm(confirmDiscardLabel);
							if (!discard) {
								return true;
							}
						}
						hCaller.setObjectClosed(objid);
					}
					if ('frm_ok' == name)
						hCaller.setObjectClosed(objid);
				}

			}

		}
	}
	catch (e) {}

	return false;
};

function executeClientAction(objid, method, name, value, row, col, hCaller) {
	var handler = clientEventHandler;
	if ( objid == '0' && method == 'logout' && name == 'ewlogout' ) {
    		parent.parent.window.location.replace(value);
		setTimeout('resetWarningState()', 2000);
		return;
	}

	if ( checkCallerModified(objid, name, hCaller) == true ) {
		setTimeout('executePendingClientAction()', 2000);
		return;
	}
	if(method == "hyperlink"){
		executeHyperlink(name);		
		return;
	}
	
	var url;
	url = m_baseURL + handler + '?method=' + method + '&objid=' + objid + '&name=' + toUTF(name) + '&value=' + toUTF(value) + '&row=' + escape(row) + '&col=' + escape(col);

	
	if(url.length > 350000){
// XLT
	alert("Data limit exceeded - please enter lesser data");
	return;
	}
	else
	if ( url.length > 1000 ) { 
		executeClientActionByPost(objid, 'formpost', name, value, row, col);	
	}
	else {
		var ewclient = getElement('ewclient');
		if (isMac || null == ewclient || null != ewclient.xmlsrc)
			return;
	
		ewclient.onreadystatechange = handleClientXMLData;
		if (!ewclient.load(url))
			return;

		waitingForResponse = true;
		window.status = window.defaultStatus = fromUTF(waitMessage);
	
		if (null != document.body.style)
			document.body.style.cursor = 'wait';
	
		if (window.event)
			window.event.cancelBubble = true;
	}
};

function executeClientActionByPost(objid, method, name, value, row, col) {
	var handler = clientEventHandler;

	waitingForResponse = true;
	window.status = window.defaultStatus = fromUTF(waitMessage);

	if (null != document.body.style)
		document.body.style.cursor = 'wait';

	if (window.event)
		window.event.cancelBubble = true;

	var form = document.ent_client;
	form.name.value = name;
	form.value.value = value;
	form.row.value = (null == row) ? '' : row;
	form.col.value = (null == col) ? '' : col;

	var newleft = self.screenLeft;
	var newtop = self.screenTop;
	var sFeatures;
	sFeatures = 'left=' + newleft + ',top=' + newtop + ',';
	sFeatures += ' height=100, width=100,  menubar=no, scrollbars=no, titlebar=no, status=no';
	m_postwin = window.open('','db_ifrm',sFeatures);

	var new_url = m_baseURL + handler + '?method=' + method + '&objid=' + objid;
	form.action= new_url;
	form.target = "db_ifrm";
	form.acceptCharset = "utf-8";	
	form.submit();
};

function executeNextClientAction() {
	if (!clientactionqueue.length)
		return false;
	var ewclientaction = clientactionqueue[0];
	clientactionqueue = clientactionqueue.slice(1);
	ewclientaction.execute();
	return true;
};

function ewclientaction (objid, method, name, value, row, col, hCaller) {
	this.objid = objid;
	this.name = name;
	this.value = value;
	this.row = row;
	this.col = col;
	this.method = method;
	this.hCaller = hCaller;
};

ewclientaction.prototype.execute = function () {
	executeClientAction(this.objid, this.method, this.name, this.value, this.row, this.col, this.hCaller);
};

function addClientActionToQueue (objid, method, name, value, row, col, hCaller) {
	clientactionqueue[clientactionqueue.length] = new ewclientaction(objid, method, name, value, row, col, hCaller);
};

function executePendingClientAction () {
	while (clientactionqueue.length > 0 && !waitingForResponse)
		executeNextClientAction();
};




var isRichText = false;
var rng;
var currentRTE;
var allRTEs = "";
var isGecko;
var isSafari;
var isKonqueror;

var imagesPath;
var includesPath;
var cssFile;


function initRTE(imgPath, incPath, css) {
	var ua = navigator.userAgent.toLowerCase();
	isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1)); 
	isGecko = (ua.indexOf("gecko") != -1);
	isSafari = (ua.indexOf("safari") != -1);
	isKonqueror = (ua.indexOf("konqueror") != -1);
	
	if (document.getElementById && document.designMode && !isSafari && !isKonqueror) {
		isRichText = true;
	}
	imagesPath = imgPath;
	includesPath = incPath;
	cssFile = css;
};

function writeRichText(rte, html, width, height, buttons, readOnly) {
		if (allRTEs.length > 0) allRTEs += ";";
		allRTEs += rte;
		writeRTE(rte, html, width, height, buttons, readOnly);
};

function raiseButton(e) {
	if (isIE) {
		var el = window.event.srcElement;
	} else {
		var el= e.target;
	}
	
	className = el.className;
	if (className == 'rteImage' || className == 'rteImageLowered') {
		el.className = 'rteImageRaised';
	}
};

function normalButton(e) {
	if (isIE) {
		var el = window.event.srcElement;
	} else {
		var el= e.target;
	}
	
	className = el.className;
	if (className == 'rteImageRaised' ) {
		el.className = 'rteImage';
	}
};

function lowerButton(e) {
	if (isIE) {
		var el = window.event.srcElement;
	} else {
		var el= e.target;
	}
	
	className = el.className;
	if (className == 'rteImage' || className == 'rteImageRaised') {
		el.className = 'rteImageLowered';
	}
};

function writeRTE(rte, html, width, height, buttons, readOnly) {
	if (readOnly) buttons = false;
	var elemdiv = parent.document.getElementById("divrtf");
	
	if (isIE) {
		if (buttons && (width < 600)) width = 200;
		var tablewidth = width;
	} else {
		if (buttons && (width < 500)) width = 500;
		var tablewidth = width + 4;
	}
	var toolbarstr = "";
	if (buttons == true) {
		toolbarstr = ('<link rel="stylesheet" type="text/css" href="entweb.css">');
		toolbarstr += ('<div style = "height:24px;overflow:hidden;"  id = \'' + rte + '\'>'); 
		toolbarstr += ('<table class="rteBack" cellpadding=0 cellspacing=0 id="Buttons1_' + rte + '" width="' + "" + '">');
		toolbarstr += ('<tr>');
		toolbarstr += ('<td valign = "top"><img class="rteImage" src="' + imagesPath + 'rte_cut.gif" width="22" height="24" alt="Cut" title="Cut" onClick="FormatText(\'' + rte + '\',\'cut\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td valign = "top"><img class="rteImage" src="' + imagesPath + 'rte_copy.gif" width="22" height="21" alt="Copy" title="Copy" onClick="FormatText(\'' + rte + '\',\'copy\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteImage" src="' + imagesPath + 'rte_paste.gif" width="22" height="21" alt="Paste" title="Paste" onClick="FormatText(\'' + rte + '\',\'paste\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="15" border="0" alt=""></td>');		
		toolbarstr += ('<td><img class="rteImage" src="' + imagesPath + 'rte_bold.gif" width="22" height="22" alt="Bold" title="Bold" onClick="FormatText(\'' + rte + '\',\'bold\', \'\')" onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteImage" src="' + imagesPath + 'rte_italic.gif" width="22" height="22" alt="Italic" title="Italic" onClick="FormatText(\'' + rte + '\',\'italic\', \'\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteImage" src="' + imagesPath + 'rte_underline.gif" width="22" height="22" alt="Underline" title="Underline" onClick="FormatText(\'' + rte + '\',\'underline\', \'\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="15" border="0" alt=""></td>');
		toolbarstr += ('<td><img class="rteImage" src="' + imagesPath + 'rte_left_just.gif" width="22" height="22" alt="Align Left" title="Align Left" onClick="FormatText(\'' + rte + '\',\'justifyleft\', \'\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteImage" src="' + imagesPath + 'rte_centre.gif" width="22" height="22" alt="Center" title="Center" onClick="FormatText(\'' + rte + '\',\'justifycenter\', \'\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteImage" src="' + imagesPath + 'rte_right_just.gif" width="22" height="22" alt="Align Right" title="Align Right" onClick="FormatText(\'' + rte + '\',\'justifyright\', \'\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="15" border="0" alt=""></td>');
		toolbarstr += ('<td><img class="rteImage" src="' + imagesPath + 'numbered_list.gif" width="22" height="22" alt="Ordered List" title="Ordered List" onClick="FormatText(\'' + rte + '\',\'insertorderedlist\', \'\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteImage" src="' + imagesPath + 'list.gif" width="22" height="23" alt="Unordered List" title="Unordered List" onClick="FormatText(\'' + rte + '\',\'insertunorderedlist\', \'\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="15" border="0" alt=""></td>');
		toolbarstr += ('<td><img class="rteImage" src="' + imagesPath + 'outdent.gif" width="22" height="21" alt="Outdent" title="Outdent" onClick="FormatText(\'' + rte + '\',\'outdent\', \'\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteImage" src="' + imagesPath + 'indent.gif" width="22" height="21" alt="Indent" title="Indent" onClick="FormatText(\'' + rte + '\',\'indent\', \'\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="15" border="0" alt=""></td>');
		toolbarstr += ('<td><div id="forecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'fgcolor.gif" width="22" height="21" alt="Text Color" title="Text Color" onClick="FormatText(\'' + rte + '\',\'forecolor\', \'\')"></div onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><div id="hilitecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'bgcolor.gif" width="22" height="21" alt="Background Color" title="Background Color" onClick="FormatText(\'' + rte + '\',\'hilitecolor\', \'\')"></div onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img id = "rte_fontsize" class="rteImage" src="' + imagesPath + 'rte_fontsize.gif" width="22" height="22" alt="FontSize" title="FontSize" onClick="ShowFormatDiv(\'rte_fontsize\',\'' + rte + '\')" onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img id = "rte_fontname" class="rteImage" src="' + imagesPath + 'rte_fontface.gif" width="22" height="22" alt="FontName" title="FontName" onClick="ShowFormatDiv(\'rte_fontname\',\'' + rte + '\')" onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="15" border="0" alt=""></td>');
		toolbarstr += ('<td><img class="rteImage" src="' + imagesPath + 'rte_hyperlink.gif" width="22" height="22" alt="Hyperlink" title="Hyperlink" onClick="FormatText(\'' + rte + '\',\'createlink\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('<td><img class="rteImage" src="' + imagesPath + 'image.gif" width="22" height="22" alt="Image" title="Image" onClick="AddImage(\'' + rte + '\')"onmouseover = "raiseButton()" onmouseout  = "normalButton()" onmousedown = "lowerButton()" onmouseup = "raiseButton()" ></td>');
		toolbarstr += ('</tr>');
		toolbarstr += ('</table>');
		toolbarstr += ('</div>');
	}
		toolbarstr += ('<div width="154" height="104" id="frmFormat" src=""  scrolling="no" style = "visibility:hidden;display:none;position:absolute; border-style:solid;border-width:1px;background-color:lightgrey;">');
		toolbarstr += ('</div>');

	toolbarstr += ('<iframe width="154" height="104" id="cp' + rte + '" src="' + includesPath + 'palette.htm" marginwidth="0" marginheight="0" scrolling="no"  style="visibility:hidden; display: none; position: absolute;"></iframe>');

	elemdiv.innerHTML = toolbarstr;
	elemdiv.style.visibility = "visible";
};

function setFramesource(formatbutton, rte){
	
	if( formatbutton == "rte_fontname"){
		toolbarstr = ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontname\',\'arial\');" style="text-decoration:none;color:black;">Arial</a></font><br>');
		toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial narrow\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontname\',\'arial narrow\');" style="text-decoration:none;color:black;">Arial Narrow</a></font><br>');
		toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial black\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontname\',\'arial black\');" style="text-decoration:none;color:black;">Arial Black</a></font><br>');
		toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'comic sans ms\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontname\',\'comic sans ms\');" style="text-decoration:none;color:black;">Comic Sans MS</a></font><br>');
		toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'courier\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontname\',\'courier\');" style="text-decoration:none;color:black;">Courier</a></font><br>');
		toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'system\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontname\',\'system\');" style="text-decoration:none;color:black;">System</a></font><br>');
		toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'times new roman\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontname\',\'times new roman\');" style="text-decoration:none;color:black;">Times New Roman</a></font><br>');
		toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'verdana\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontname\',\'verdana\');" style="text-decoration:none;color:black;">Verdana</a></font>');
	}
	if( formatbutton == "rte_fontsize"){
		toolbarstr = ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontsize\',\'1\');" style="text-decoration:none;color:black;">Size 1</a></font><br>');
		toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=2><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontsize\',\'2\');" style="text-decoration:none;color:black;">Size 2</a></font><br>');
		toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=3><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontsize\',\'3\');" style="text-decoration:none;color:black;">Size 3</a></font><br>');
		toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=4><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontsize\',\'4\');" style="text-decoration:none;color:black;">Size 4</a></font><br>');
		toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=5><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontsize\',\'5\');" style="text-decoration:none;color:black;">Size 5</a></font><br>');
		toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=6><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontsize\',\'6\');" style="text-decoration:none;color:black;">Size 6</a></font><br>');
		toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=7><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'fontsize\',\'7\');" style="text-decoration:none;color:black;">Size 7</a></font><br>');
	}
	if( formatbutton == "rte_formatblock"){
			toolbarstr = ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'formatblock\',\'Paragraph\');" style="text-decoration:none;color:black;"><p>Paragraph</p></a></font>');
			toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'formatblock\',\'Heading 1\');" style="text-decoration:none;color:black;"><h1>Heading 1</h1></a></font>');
			toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'formatblock\',\'Heading 2\');" style="text-decoration:none;color:black;"><h2>Heading 2</h2></a></font>');
			toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'formatblock\',\'Heading 3\');" style="text-decoration:none;color:black;"><h3>Heading 3</h3></a></font>');
			toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'formatblock\',\'Heading 4\');" style="text-decoration:none;color:black;"><h4>Heading 4</h4></a></font>');
			toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'formatblock\',\'Heading 5\');" style="text-decoration:none;color:black;"><h5>Heading 5</h5></a></font>');
			toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'formatblock\',\'Heading 6\');" style="text-decoration:none;color:black;"><h6>Heading 6</h6></a></font>');
			toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'formatblock\',\'Address\');" style="text-decoration:none;color:black;"><address>Address</Address></a></font>');
			toolbarstr += ('<font onmouseover="this.style.backgroundColor=\'white\'" onMouseOut="this.style.backgroundColor=\'lightgrey\'" face=\'arial\' size=-1><a class=RTESelectItem href=# onclick="setrteFont(\'' + rte + '\',\'formatblock\',\'Formatted\');" style="text-decoration:none;color:black;"><pre>Formatted</pre></a></font>');
	}

	document.getElementById("frmFormat").innerHTML = toolbarstr;
};

function ShowFormatDiv(formatbutton,rte){

		var buttonElement = document.getElementById(formatbutton);
		document.getElementById("frmFormat").style.left = getOffsetLeft(buttonElement, 4) + "px";
		document.getElementById("frmFormat").style.top = (getOffsetTop(buttonElement, 4) + buttonElement.offsetHeight + 4) + "px";
		setFramesource(formatbutton,rte);
		if (document.getElementById("frmFormat").style.visibility == "hidden") {
				document.getElementById("frmFormat").style.visibility = "visible";
				document.getElementById("frmFormat").style.display = "inline";
			} 
		else {
				document.getElementById("frmFormat").style.visibility = "hidden";
				document.getElementById("frmFormat").style.display = "none";
			}


};

function setrteFont(rte, fontprop , fontvalue) {
	var oRTE;
	if (document.all) {
		ifrmMain= frames['AxObjectMain'];
		oRTE = ifrmMain.frames[rte];
		
		var selection = oRTE.document.selection; 
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;
		
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
	
		oRTE.focus();
		oRTE.document.execCommand(fontprop, false, fontvalue);
		oRTE.focus();
		document.getElementById("frmFormat").style.visibility = "hidden";
		document.getElementById("frmFormat").style.display = "none";
		
};

function enableDesignMode(rte, html, readOnly) {
	
	if(html == "" || html == null)
		html = "";
	var frameHtml = "<html id=\"" + rte.id + "\">\n";
	frameHtml += "<head>\n";
		frameHtml += "<style>\n";
		frameHtml += "body {\n";
		frameHtml += "	background: #FFFFFF;\n";
		frameHtml += "	margin: 0px;\n";
		frameHtml += "	padding: 0px;\n";
		frameHtml += "	font-family: arial, sans-serif;\n";
		frameHtml += "	font-size: 8pt;\n";
		frameHtml += "}\n";
		frameHtml += "</style>\n";
		frameHtml += "<script language=\"JavaScript1.2\" src=\"entweb.js\" ></script>"

	frameHtml += "</head>\n";
	frameHtml += "<body>\n";
	frameHtml += html + "\n";
	frameHtml += "</body>\n";
	frameHtml += "</html>";
	
	if (document.all) {
		var oRTE = frames[rte].document;
		oRTE.open();
		oRTE.write(frameHtml);
		oRTE.close();
		if (!readOnly) 
			oRTE.designMode = "On";
		else
			oRTE.designMode = "Off";
	} else {
		try {
			if (!readOnly) document.getElementById(rte).contentDocument.designMode = "on";
			try {
				var oRTE = document.getElementById(rte).contentWindow.document;
				oRTE.open();
				oRTE.write(frameHtml);
				oRTE.close();
				if (isGecko && !readOnly) {
					oRTE.addEventListener("keypress", kb_handler, true);
				}
			} catch (e) {
				alert("Error preloading content.");
			}
		} catch (e) {
			if (isGecko) {
				setTimeout("enableDesignMode('" + rte + "', '" + html + "', " + readOnly + ");", 10);
			} else {
				return false;
			}
		}
	}
};

function updateRTEs() {
	var vRTEs = allRTEs.split(";");
	for (var i = 0; i < vRTEs.length; i++) {
		updateRTE(vRTEs[i]);
	}
};

function updateRTE(rte) {
	if (!isRichText) return;
	
	var oRTE = parent.frames['frmrtf'].frames[rte].document.getElementById(rte);
	var readOnly = false;
	
	if (document.all) {
		if (parent.frames['frmrtf'].frames[rte].frames[rte].document.designMode != "On") readOnly = true;
	} else {
		if (document.getElementById(rte).contentDocument.designMode != "on") readOnly = true;
	}
	
	if (isRichText && !readOnly) {
		if (document.getElementById("chkSrc" + rte).checked) {
			document.getElementById("chkSrc" + rte).checked = false;
			toggleHTMLSrc(rte);
		}
		
		if (oHdnMessage.value == null) oHdnMessage.value = "";
		if (document.all) {
			oHdnMessage.value = frames[rte].document.body.innerHTML;
		} else {
			oHdnMessage.value = oRTE.contentWindow.document.body.innerHTML;
		}
		
		if (stripHTML(oHdnMessage.value.replace("&nbsp;", " ")) == "" 
			&& oHdnMessage.value.toLowerCase().search("<hr") == -1
			&& oHdnMessage.value.toLowerCase().search("<img") == -1) oHdnMessage.value = "";
		if (escape(oHdnMessage.value) == "%3Cbr%3E%0D%0A%0D%0A%0D%0A") oHdnMessage.value = "";
	}
};

function toggleHTMLSrc(rte) {
	var oRTE;
	if (document.all) {
		oRTE = frames[rte].document;
	} else {
		oRTE = document.getElementById(rte).contentWindow.document;
	}
	
	if (document.getElementById("chkSrc" + rte).checked) {
		document.getElementById("Buttons1_" + rte).style.visibility = "hidden";
		document.getElementById("Buttons2_" + rte).style.visibility = "hidden";
		if (document.all) {
			oRTE.body.innerText = oRTE.body.innerHTML;
		} else {
			var htmlSrc = oRTE.createTextNode(oRTE.body.innerHTML);
			oRTE.body.innerHTML = "";
			oRTE.body.appendChild(htmlSrc);
		}
	} else {
		document.getElementById("Buttons1_" + rte).style.visibility = "visible";
		document.getElementById("Buttons2_" + rte).style.visibility = "visible";
		if (document.all) {
			var output = escape(oRTE.body.innerText);
			output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
			output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");
			
			oRTE.body.innerHTML = unescape(output);
		} else {
			var htmlSrc = oRTE.body.ownerDocument.createRange();
			htmlSrc.selectNodeContents(oRTE.body);
			oRTE.body.innerHTML = htmlSrc.toString();
		}
	}
};
var command = "";

function FormatText(rte, command, option) {
	if (isIE) {
		var el = window.event.srcElement;
	} else {
		var el= e.target;
	}
	
	className = el.className;
	if (className == 'rteImageLowered') {
		el.className = 'rteImage';
	}
	if (className == 'rteImage' || className == 'rteImageRaised' ) {
		el.className = 'rteImageLowered';
		}
	var oRTE;
	if (document.all) {
		ifrmMain= frames['AxObjectMain'];
		oRTE = ifrmMain.frames[rte];
		var selection = oRTE.document.selection; 
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;
		
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
	
	try {
		if ((command == "forecolor") || (command == "hilitecolor")) {
			parent.command = command;
			currentRTE = rte;
			
			buttonElement = document.getElementById(command + '_' + rte);
			document.getElementById('cp' + rte).style.left = getOffsetLeft(buttonElement, 4) + "px";
			document.getElementById('cp' + rte).style.top = (getOffsetTop(buttonElement, 4) + buttonElement.offsetHeight + 4) + "px";
			if (document.getElementById('cp' + rte).style.visibility == "hidden") {
				document.getElementById('cp' + rte).style.visibility = "visible";
				document.getElementById('cp' + rte).style.display = "inline";
			} else {
				document.getElementById('cp' + rte).style.visibility = "hidden";
				document.getElementById('cp' + rte).style.display = "none";
			}
		} else if (command == "createlink") {
			try {
				oRTE.focus();
				oRTE.document.execCommand("CreateLink");
				oRTE.focus();
			} catch (e) {
			}
		} else {
			oRTE.focus();
		  	oRTE.document.execCommand(command, false, option);
			oRTE.focus();
		}
	} catch (e) {
		alert(e);
	}
};

function setColor(color) {
	var rte = currentRTE;
	var oRTE;
	if (document.all) {
		ifrmMain= frames['AxObjectMain'];
		oRTE = ifrmMain.frames[rte];

	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}
	
	var parentCommand = parent.command;
	if (document.all) {
		var sel = oRTE.document.selection; 
		if (parentCommand == "hilitecolor") parentCommand = "backcolor";
		if (sel != null) {
			var newRng = sel.createRange();
			newRng = rng;
			newRng.select();
		}
	}
	oRTE.focus();
	oRTE.document.execCommand(parentCommand, false, color);
	oRTE.focus();
	document.getElementById('cp' + rte).style.visibility = "hidden";
	document.getElementById('cp' + rte).style.display = "none";
};

function AddImage(rte) {
	var oRTE;
	if (document.all) {
		ifrmMain= frames['AxObjectMain'];
		oRTE = ifrmMain.frames[rte];
		
		var selection = oRTE.document.selection; 
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;
		
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
	
	imagePath = prompt('Enter Image URL:', 'http://');				
	if ((imagePath != null) && (imagePath != "")) {
		oRTE.focus();
		oRTE.document.execCommand('InsertImage', false, imagePath);
		oRTE.focus();
	}
};

function checkspell() {
	try {
		var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
		tmpis.CheckAllLinkedDocuments(document);
	}
	catch(exception) {
		if(exception.number==-2146827859) {
			if (confirm("ieSpell not detected.  Click Ok to go to download page."))
				window.open("http://www.iespell.com/download.php","DownLoad");
		} else {
			alert("Error Loading ieSpell: Exception " + exception.number);
		}
	}
};

function getOffsetTop(elm, parents_up) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	
	if(!parents_up) {
		parents_up = 10000; 
	}
	while(parents_up>0 && mOffsetParent) {
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	
	return mOffsetTop;
};

function getOffsetLeft(elm, parents_up) {
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	
	if(!parents_up) {
		parents_up = 10000; 
	}
	while(parents_up>0 && mOffsetParent) {
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	
	return mOffsetLeft;
};

function Select(rte, selectname) {
	var oRTE;
	if (document.all) {
		ifrmMain= frames['AxObjectMain'];
		oRTE = ifrmMain.frames[rte];
		
		var selection = oRTE.document.selection; 
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;
		
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
	
	var idx = document.getElementById(selectname).selectedIndex;
	if (idx != 0) {
		var selected = document.getElementById(selectname).options[idx].value;
		var cmd = selectname.replace('_' + rte, '');
		oRTE.focus();
		oRTE.document.execCommand(cmd, false, selected);
		oRTE.focus();
		document.getElementById(selectname).selectedIndex = 0;
	}
};

function kb_handler(evt) {
	var rte = evt.target.id;
	
	if (evt.ctrlKey) {
		var key = String.fromCharCode(evt.charCode).toLowerCase();
		var cmd = '';
		switch (key) {
			case 'b': cmd = "bold"; break;
			case 'i': cmd = "italic"; break;
			case 'u': cmd = "underline"; break;
		};

		if (cmd) {
			FormatText(rte, cmd, true);
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
};

function docChanged (evt) {
	alert('changed');
};

function stripHTML(oldString) {
	var newString = oldString.replace(/(<([^>]+)>)/ig,"");
	
   newString = newString.replace(/\r\n/g," ");
   newString = newString.replace(/\n/g," ");
   newString = newString.replace(/\r/g," ");
	
	newString = trim(newString);
	
	return newString;
};

function trim(inputString) {
   if (typeof inputString != "string") return inputString;
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
	
   while (ch == " ") { 
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
	
   while (ch == " ") { 
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
	
   while (retValue.indexOf("  ") != -1) {
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length);
   }
   return retValue; 
};

