/*
 *
 * MRO Software Confidential
 *
 * (C) COPYRIGHT MRO Software, Inc. 2001-2006
 *
 * The source code for this program is not published or otherwise
 * divested of its trade secrets, irrespective of what has been
 * deposited with the U.S. Copyright Office.
 *
 */


 	//JS Constants
	var KEYCODE_TAB = 9;
	var KEYCODE_BACKSPACE = 8;
	var KEYCODE_ENTER = 13;
	var KEYCODE_LEFT_ARROW = 37;
	var KEYCODE_UP_ARROW = 38;
	var KEYCODE_RIGHT_ARROW = 39;
	var KEYCODE_DOWN_ARROW = 40;
	var KEYCODE_CTRL = 17;
	var KEYCODE_Z =	90; 
	var KEYCODE_SPACEBAR =	32;
    var KEY_CODE_PLUS = 187;
    var KEY_CODE_MINUS = 189;
   	var NUMERIC_PAD_KEY_CODE_PLUS = 107;
    var NUMERIC_PAD_KEY_CODE_MINUS = 109;
	var stopevents=false;
	
	var logfile = "c:\\temp\\MAXIMO_JS_Log.txt";
	var logging = false;
	var messageClearTimer = 5000;
	var SHOW_WAIT_LAYERS=true;
	var wait_locked = false;
	var movingItem = null;
	var DESIGNER_HIGHLIGHT=new webColor("D7E8B1");
	var DESIGNER_DRAGENTER=new webColor("F5E9B8");
	var DESIGNER_DRAGENTER_BORDER=new webBorder(0, "solid", new webColor("#FF9900"));
	//*****************************************************************************
	//Control specific constants 
	//*****************************************************************************
	//For "table" control
	var TABLE_TITLE_SUFFIX = "_title";
	var TABLE_ICON_EXPAND_SUFFIX = "_icon_expand";
	var TABLE_ICON_COLLAPSE_SUFFIX = "_icon_collapse";
	var TABLE_CONTAINER_SUFFIX = "_container";
	var TABLE_HEADER_SUFFIX = "_header";
	var TABLE_HEADER_ICON_PREVROW_ON_SUFFIX = "_prevrow_on";
	var TABLE_HEADER_ICON_PREVROW_OFF_SUFFIX = "_prevrow_off";
	var TABLE_HEADER_ICON_NEXTROW_ON_SUFFIX = "_nextrow_on";
	var TABLE_HEADER_ICON_NEXTROW_OFF_SUFFIX = "_nextrow_off";
	var TABLE_HEADER_ICON_PREVPAGE_ON_SUFFIX = "_prevpage_on";
	var TABLE_HEADER_ICON_PREVPAGE_OFF_SUFFIX = "_prevpage_off";
	var TABLE_HEADER_ICON_NEXTPAGE_ON_SUFFIX = "_nextpage_on";
	var TABLE_HEADER_ICON_NEXTPAGE_OFF_SUFFIX = "_nextpage_off";
	var TABLE_CLEARFILTER_SUFFIX = "_clearfilter";
	var TABLE_FILTER_TOOLTIP = "_filter_tooltip";
	var TABLE_FILTER_ICON = "_filter_icon";
	var TABLE_FILTER_ACTIONS_SUFFIX = "_filter_actions";
	var TABLE_HEADER_ROW_SUFFIX = "_heder_row";
	var TABLE_HEADER_LABEL_SUFFIX = "_heder_label";
	var TABLE_CONTENT_HEADER_SUFFIX = "_content_header";
	var TABLE_CONTENT_HEADER_RESIZE_SUFFIX = "_content_header_resize";
	var TABLE_CONTENT_SUFFIX = "_content";
	var TABLE_CONTENT_TABLE = "_content_table";
	var TABLE_NOROW_MSG_SUFFIX = "_norowmessage";
	var TABLE_FILTER_ROW_SUFFIX = "_filter_content";
	var TABLE_TEMPLATE_ROW_SUFFIX = "_template_content";
	var TABLE_ROW_DETAILS_SUFFIX = "_rowdetails";
	
	//For "tablecol" control	
	var TABLECOL_FILTER_SUFFIX = "_filter_container";
	var TABLECOL_DATA_SUFFIX = "_data_row";
	var TABLECOL_ROW_DETAILS_ICON_EXPAND = "_expand";
	var TABLECOL_ROW_DETAILS_ICON_COLLAPSE = "_collapse";
	var TABLECOL_SELECT_ROW_SUFFIX = "_select";	
	var TABLECOL_SELECTALL_ICON_SUFFIX = "_selectall";
	var TABLECOL_NOT_SORTED = 0;
	var TABLECOL_SORTED_ASC = 1;
	var TABLECOL_SORTED_DESC = 2;
	
	//For "tablebuttons" control
	var TABLEBUTTONS_SUFFIX = "_buttons";
	var TABLEBUTTON_LABEL_SUFFIX = "_button_label";
	
	//For Section control
	var SECTION_HEADER_SUFFIX = "_header";
	var SECTION_LABEL_SUFFIX = "_label";
	var SECTION_CONTENT_SUFFIX = "_content";
	var SECTION_TABLE_SUFFIX = "_table";
	var SECTION_FOOTER_SUFFIX = "_footer";
	
	var FIELD_TYPE_DATE = 3;
	var FIELD_TYPE_DATETIME = 4;

	window.onload=done;
	var clientEventQueue = new Array();
	var queuedEvent = false;
	var g_event_control = null;
	var focusField = null;
	var lastFocusField = null;
	var focusContainer = null;
	var openPages = 1;
	var eventTimeout = null;
	var openDialogs = new Array();
	var waitLayers = new Array();
	var firingControl = null;
	var usefiringcontrol = false;
	var objsHidden = false;
	var stopFocus = false;
	var windowPositions = new Array();
	var currentObject = null;
	var currentPartName = null;
	var moveableTopZ = 100;
	var debugTopZ = 10000;
	var showWindowContentsWhileDragging = false;
	var passwordFields = new Array();
	var stopClick=false;
	
	var	changedFieldLabels=new Array();
	var	changedFieldValues=new Array();
	function alertChanged()
	{
		if(SCREENREADER)
		{
			outStr = "";
			for(i=0;i<changedFieldLabels.length;i++)
			{
				outStr+="\n"+changedFieldLabels[i]+" = "+changedFieldValues[i];
			}
			if(outStr!="")
				alert(outStr)
		}
		changedFieldLabels=new Array();
		changedFieldValues=new Array();
	}
	
	function addUpdateField(label,value)
	{
		if(!undef(label.alt))
		{
			lb = label.alt;
		}
		else if(!undef(label.title))
		{
			lb = label.title;
		}
		if(value=="")
			value="null";
		changedFieldLabels.push(lb);
		changedFieldValues.push(value);
	}
	
	function changedField(label,value)
	{
		this.label=label;
		this.value=value;
	} 	


	function done()
	{
		commframe = document.getElementById("commframe").contentWindow;
		commframe.finishPage();
	}

	function lockWait()
	{
		window.top.wait_locked=true;
	}

	function unLockWait()
	{
		window.top.wait_locked=false;
	}

	function showWait(visible, ownerDialogId)
	{
		if(!SHOW_WAIT_LAYERS)
			return;
		
		if(designmode)
		{
			window.top.showWait(visible, ownerDialogId);
			lockWait();
			return;
		}
		dialogId = ownerDialogId;
		dialog=null;

		waitImage = "wait_clear.gif";
		if(undef(dialogId))
		{
			wait = parent.document.getElementById("shortwait");
		}
		else
		{
			wait = parent.document.createElement("<img class='waitimage' oncontextmenu='event.returnValue=false;' src='"+IMAGE_PATH+waitImage+"'>");
			dialog = parent.document.getElementById(dialogId);
		}
		document.body.style.overFlow="hidden";
		if(wait)
		{
			wait.style.cursor="wait";
			if(dialog==null)
			{
				wait.style.zIndex=moveableTopZ+1;
				wait.style.width=document.body.clientWidth;
				wait.style.display="";
			}
			else
			{
				wait.style.zIndex=parseInt(dialog.style.zIndex)-1;
				wait.id=dialogId+"_waitLayer";
				parent.document.body.insertAdjacentElement("BeforeEnd",wait);
			}
			wait.style.width=document.body.offsetWidth;
			wait.style.height=document.body.offsetHeight;
		}
	}

	function hideWait(id)
	{
		if( wait_locked==true)
			return;

		if(designmode)
		{
			window.top.hideWait(id);
		}
		
		dialogId = id;
		if(!undef(dialogId))
		{
			wait = document.getElementById(dialogId+"_waitLayer");
			if(wait)
				wait.removeNode(true);
		}
		else
		{
			wait = document.getElementById("shortwait");
			if(wait)
			{
				wait.style.zIndex=1;
				wait.style.display="none";
				wait.style.width="1px";
				wait.style.height="1px";
			}
		}

	}

	function hidePopup(k)
	{
		keyed = k;
		fh = document.getElementById("maxpopup");
		if(fh)
		{
			fh.style.display="none";
			fh.removeNode(true);
			if(keyed && fh.owner)
			{
				fh.owner.focus();
				fh.owner.setActive();
			}
			parent.document.getElementById("clientarea").onscroll="";
		}
	}

	function killPopup()
	{
		parent.document.onclick="";
		hidePopup(true);
		enableDoc();
	}

	function clientEvent(eventtype, id, val, prop, row, event2, uid)
	{
		this.event=eventtype;
		this.targetid=id;
		this.value=val;
		this.property=prop;
		this.row = row;
		this.additionalevent=event2;
		this.uniqueid = uid;
	}

	function enableDoc()
	{
		working=false;
		sb=document.getElementById("statusbar")
		if(sb)
		{
			sb.stopProgress();
		}
		if(!designmode && !stopFocus)
		{
			if(focusField)
			{
				setFieldFocus(focusField);
			}
			else if(focusContainer)
			{
				setDefaultFocus();
			}
		}
		clearFiring();
		setTimeout("parent.cancelClientEventStop()",100);
		hideWait();
		stopClick=false;
	}
	
	function disableDoc(wo, cm)
	{	
		working=true;
		closeMenus = cm;
		if(undef(closeMenus))
			closeMenus=true;
			
		if(closeMenus)
			hideMenu();

		showWait();
		sb=document.getElementById("statusbar");
		if(sb)
			sb.startProgress();
	}


	//This is the library of methods which is shared by all controls...
	//NOTE: only shared methods or those which cannot be in a controls behavior belong here
	
	function getMenu(id, x, y, z, part, type)
	{
		partid=part;
		menutype=type;
		if(menutype!=null)
			partid=menutype;
		mWidth = z;
		menuX=x;
		menuY=y;
		if(mWidth)
			menuWidth=mWidth;
		else
			menuWidth=0;
			
		var control = getControl(event.srcElement);
		if (!undef(control.ontable) && control.ontable=="true" && control.query!="true")
			clientEventQueue[clientEventQueue.length]=new clientEvent("showmenu", id, partid);
		else
			sendEvent("showmenu", id, partid);
	}

	function stopClientEvents()
	{
		stopevents=true;
	}

	function ifStopClientEvents()
	{
		return stopevents;
	}

	function cancelClientEventStop()
	{
		stopevents=false;
	}

	function sendNextQueuedEvent()
	{
		if(clientEventQueue!=null && clientEventQueue.length>0)
		{
			if (stopevents)
			{
				clientEventQueue=new Array();
			}
			else
			{
				mxevent = clientEventQueue.shift();
				queuedEvent=true;
				if(mxevent.event=="clientonly")
				{
					processFrontEndEvent(mxevent);
				}
				else
				{
					sendEvent(mxevent.event, mxevent.targetid, mxevent.value, mxevent.property, mxevent.row, mxevent.additionalevent, mxevent.uniqueid);
					return 1;
				}
			}
		}
		return 0;
	}	
	
	function addCommInput(name, value)
	{
		if(working)
			return;
			
		val = value;
		if(undef(val))
			val ="";
		commframedoc = document.getElementById("commframe").contentWindow.document;
		hiddenForm = commframedoc.getElementById("hiddenform");
		newInput = commframedoc.createElement("<input type='hidden' >");
		newInput.name = name;
		newInput.value = val;
		hiddenForm.appendChild(newInput);
	}

	function logString(stringVal)
	{
		log = window.top.document.getElementById("eventlog");
		
		if(log)
		{
			x = log.innerHTML;
			log.innerHTML=stringVal+"<br>"+x;
		}

	}

	function logEvent(eventtype, id, val, prop, row, add, uniqueid)
	{
		if(val==undefined)
			val='';
		if(prop==undefined)
			prop='';
		if(row==undefined)
			row='';
		if(add==undefined)
			add='';
		if(uniqueid==undefined)
			uniqueid='';
		log = window.top.document.getElementById("eventlog");
		
		if(log)
		{
			x = log.innerHTML;
			log.innerHTML="sendEvent("+eventtype+","+id+","+val+","+prop+","+row+","+add+","+uniqueid+")<br>"+x;
		}
	}

	function sendEvent(eventtype, id, val, prop, row, additionalevent, unqueid)
	{	
		if (stopevents)
		{
			clientEventQueue = new Array();
			return;
		}
		//var event=eventtype;
		var targetid=id;
		var value=val;
		var property=prop;
		var eventrow=row;
		var closeMenus = true;
		if(working && queuedEvent!=true)
		{
			clientEventQueue[clientEventQueue.length]=new clientEvent(eventtype, targetid, value, property, row, additionalevent, unqueid);
			return;
		}
		else
		{
			if(eventtype=="changedate")
				closeMenus=false;

			if(queuedEvent!=true)
			{
				disableDoc("0", closeMenus);
			}
		}
		commframedoc = document.getElementById("commframe").contentWindow.document;

		hiddenForm = commframedoc.getElementById("hiddenform");

		if(!hiddenForm)
		{
			//alert("Error: Hidden Form Missing, cannot send '" + eventtype +"'" );
			return;
		}	
		inputs = hiddenForm.elements;

		if(value!=null)
		{
			inputs.namedItem("value").value=value;
			inputs.namedItem("visvalue").value=value;
		}
		
		if(eventtype!=null)
			inputs.namedItem("event").value=eventtype;
		else
		{
			enableDoc();
			return;
		}
		// Check if the control is contained within a table 
		var control =  document.getElementById(id);
		g_event_control = control;
		if(control!=null)
		{
			if(control.getAttribute("ontable")=="true")
			{
				if(control.getAttribute("controlid")!=null)
				{
					targetid = control.getAttribute("controlid");
				}
			}
		}

		if(targetid!=null)
			inputs.namedItem("targetid").value=targetid;
	
		if(property!=null)
			inputs.namedItem("property").value=property;

		if(!undef(eventrow) && (eventrow!=-1) ) 
			inputs.namedItem("row").value=eventrow;

		if(additionalevent!=null) 
			inputs.namedItem("additionalevent").value=additionalevent;

		if(unqueid!=null) 
			inputs.namedItem("uniqueid").value=unqueid;

		var DB = DEBUG
		if(DB!=null && DB<=3)
		{
			if(DB>0)
			{
				logEvent(eventtype, id, val, prop, row, additionalevent, unqueid);
			}
			submitHidden();
		}
		else
		{
			msg = commframedoc.getElementById("message");
			if(DB<7)
			{
				interval = (DB*100)*4;
				msg.innerText="Waiting "+interval/1000+" seconds before submit";
				eventTimeout = window.setTimeout("submitHidden()", interval);
			}
			else
			{
				msg.innerText="(debug>=7):click submit!";				
			}
		}
		queuedEvent=false;
	}
	
	function submitHidden()
	{
		commframedoc = document.getElementById("commframe").contentWindow.document;
		hiddenForm = commframedoc.getElementById("hiddenform");	
		if(eventTimeout)
			window.clearTimeout(eventTimeout);
		if(hiddenForm)
			hiddenForm.submit();
		//else
		//	alert("Error: Hidden Form Missing");
	}

	//Begin methods used by controls to help in client-side-->server-side event handling
	function ltrim (s)
	{
		if(s==true || s==false)
			return s;
		else
			return s.replace( /^\s*/, "" );
	}
	
	function rtrim(s)
	{
		if(s==true || s==false)
			return s;
		else
			return s.replace( /\s*$/, "" );
	}	
	
	function trim(s)
	{
	    s = rtrim(ltrim(s));
		if(s==true || s==false)
			return s;
				
		var objRegex = new RegExp("(^\\s+)|(\\s+$)");
	    s = s.replace(objRegex, "");

		return s;
	}

	function setValue(control, part, row)
	{
		eventtype = "setvalue";
		dflt=part.dflt;
		query=part.query;

		commframedoc = document.getElementById("commframe").contentWindow.document;
		toElid=commframedoc.createElement();
		hiddenForm = commframedoc.getElementById("hiddenform");
		check = control.checked
		
		if(check!=null)
		{
			value = (control.checked!="true")?true:false;
		}
		else
		{
			if (part.readOnly)
				return;
			value = part.value;
			value = trim(value);
			part.value=value;
		}

		if(query=="true")
			eventtype = "setfiltervalue";
		else if(dflt=="true")
			eventtype = "setdefaultvalue";
		
		attr = part.dataattribute;

		var queueevent = false;
		var ontable = (control.getAttribute("ontable")=="true");
		var ischeckbox = (control.getAttribute("controltype")=="checkbox");
		queueevent = ontable && ischeckbox;
		if(attr) 
		{
			if (queueevent)
				clientEventQueue[clientEventQueue.length]=new clientEvent(eventtype, control.id, trim(value), part.dataattribute, row);
			else		
				sendEvent(eventtype, control.id, trim(value), part.dataattribute, row);
		} 
		else
		{
			if (queueevent)
				clientEventQueue[clientEventQueue.length]=new clientEvent(eventtype, control.id, trim(value), "", row);
			else		
				sendEvent(eventtype, control.id, trim(value), "", row);
		}
	}

	function setDefaultValue(control, dataattribute)
	{
		attr = dataattribute;
		value = trim(control.value);
		trim(control.value)=value;
		if(attr)
			sendEvent("setvalue", control.id, value, dataattribute);
		else
			sendEvent("setvalue", control.id, value);
	}

	//End methods used by controls to help in client-side-->server-side event handling


	//Begin methods used by controls to help in server-side-->client-side event handling
	// These methods will be called from the response in the IFRAME 
	function updateValue(controlid, value, part)
	{
			
	}
	
	function updateReadOnly(controlid, readonly, part)
	{

	}

	function updateRequired(controlid, required, part)
	{

	}

	//End methods used by controls to help in server-side-->client-side event handling
	function walkForPart(el, partName)
	{
		part=null;
		try
		{
			ch = el.all;
			
			part = ch.namedItem(el.id+"_"+partName);
			if(part!=null)
				return part;

//		logging=true;
//		log("walkForPart: " + el.controltype +" : "+partName + "["+el.id+"_"+partName+"]");

			len = ch.length;
			for(i=0;i<len;i++)
			{
				child = ch(i);
				if(child.mxpart == partName)
				{
					part = child;
					break;
				}
			}
		}
		catch(error)
		{
			alert("Error with control ["+ctrl.controltype+"].  Cannot find part: "+partName);
		}
		return part;
	}

	//Begin methods used by all controls to help in client-side event handling
	function getPart(el, partName)
	{	
		part=null;
		try
		{
			currentObject = el;
			currentPartName = partName;
			part = eval(el.controltype+"_getPart()");
			if(undef(part))
			{
				part = walkForPart(el, partName);
			}
		}
		catch(error)
		{
			part = walkForPart(el, partName);
		}
		return part;
	}
	
	//Checks for contents of an array, starting at a location passed as a param
	function bIsArrEmpty(arr, startAt)
	{
	    for(i=startAt; i<arr.length; i++){
	        if( (arr[i]!=""))
	        {
	            return false;
	        }
	    }
	    return true;
	}
	
	//check to see if a value is null, empty or undefined
	function undef(p)
	{
	    var bUndef = false;
	    switch(typeof(p))
	    {
	        case "undefined": bUndef = true; break;
	        case "null": bUndef = true; break;
	        case "object": if(p==null) bUndef = true; break;
	        case "number": if(null==p) bUndef = true;break;
	        case "string":
	            if(""==p) bUndef = true;
	            if("null"==p) bUndef = true;
	            if("undefined"==p) bUndef = true;
	            break;
	    }
	    return bUndef;
	}
	
	//checks value for true or case Insensitive "true" (handles nulls)
	function isTrue(val)
	{
		if(undef(val))
		{
			return false;
		}
		if(val==true || val.toLowerCase()=="true")
		{
			return true;
		}
		return false;
	}
	//End methods used by all controls to help in client-side event handling

	function getPartName(el)	
	{
		if(el && el.id)
		{	
			partName = el.id.substr(el.id.lastIndexOf("_")+1);
			return partName;
		}
		return "";
	}

	function getContainer(el, mxpart)
	{
		while(el!=null && el.mxpart!=mxpart)
		{
			el=el.parentElement;
		}
		return el;
	}

	function getControl(el)
	{
		while(el!=null && el.control!="true")
		{
			el=el.parentElement;
		}
		return el;
	}

	function treeLine(lineId, text, parent, parentElementId)
	{ 
		this.lineId = lineId;
		this.text = text;
		this.parent = parent;
		this.parentElementId = parentElementId;
	}

	function showMessage(type, text)
	{
		messageImageSpan = document.getElementById("titlebar_error_image");
		message = document.getElementById("titlebar_error");
		if(!messageImageSpan || !message)
			return;
		source=IMAGE_PATH;
		switch(type)
		{
			case 0:
				source="";
				break;
			case 1: //information
				source += "information.gif"
				break;
			case 2: //warning
				source += "exclamation.gif"
				break;
			case 3: //error
				source += "error.gif"
				break;
			default:
				message.innerHTML="&nbsp;"
				return
				break;
		}
		message.innerHTML="";
		if(source!="")
		{
			messageimage = document.createElement("<img src='"+source+"' align='absmiddle'>");
			messageImageSpan.insertAdjacentElement("beforeEnd", messageimage);
		}
		message.innerText="   "+text;
		window.setTimeout(removeUserMessage, messageClearTimer);
	}

	function removeUserMessage()
	{
		messageImageSpan = document.getElementById("titlebar_error_image");
		message = document.getElementById("titlebar_error");
		messageImageSpan.innerHTML = "";
		message.innerHTML = "";
		message.innerText = "";
	}

	function intervalHandler(target, func)
	{
		eval(target+"."+func+"()")
	}

	function timeoutHandler(target, func)
	{
		eval(target+"."+func+"()")
	}
	
	
	function showFieldHelp(fieldHelpInnerId)
	{
	  	var popup = window.createPopup();
	  	var popupBody = popup.document.body;
		popupBody.style.border="1px solid #000000";
		inner = parent.document.getElementById(fieldHelpInnerId);
	  	popupBody.insertAdjacentElement('beforeEnd', inner);
	  	popup.show(menuX, menuY, 200, 50, document.body);
	}

	function setfocusField(el)
	{
		if(focusField==el)
			return;
		sf = el.setsfocus;
		ch = el.changed;
		elId = el.id;
		if(elId)
		{
			len = elId.length;
			if(elId.indexOf("detail")==len-6)
				el = getPart(getControl(el), "textbox");
		}
		if((!undef(ch) && ch==true) || el.readOnly==true || (!undef(sf) && sf=="false"))
			return;
		
		lastFocusField=focusField;
		focusField=el;
		cfd = document.getElementById("commframe");
		hiddenForm=null;
		if(cfd)
		{
			commframedoc = document.getElementById("commframe").contentWindow.document;
			hiddenForm = commframedoc.getElementById("hiddenform");
		}
		
		if(undef(hiddenForm))
		{
			return;
		}	
		if(el)
		{
			ctrl=getControl(el);
			if(ctrl)
				ctrlId=ctrl.id;
			if(ctrl && ctrl.ontable)
				ctrlId = ctrl.controlid
		}
		if(undef(ctrlId))
			ctrlId="";
		inputs = hiddenForm.elements;
		last = inputs.namedItem("lastfocus");
		current = inputs.namedItem("currentfocus");
		currentControl = inputs.namedItem("currentcontrol");
		last.value=current.value;
		current.value=el.id;
		currentControl.value=ctrlId;
	}

	function setDefaultFocus(last)
	{
		useLast=last;
		if(undef(useLast))
			useLast=false;
		if(stopFocus==true)
		{
			stopFocus=false;
			return;
		}
	
		container=focusContainer;
		

		if(container==null)
			return;
		
		commframedoc = document.getElementById("commframe").contentWindow.document;
		hiddenForm = commframedoc.getElementById("hiddenform");
		inputs = hiddenForm.elements;
		fc= inputs.namedItem("focuscontainer");
		fc.value=container.id;
		objects = container.all;
		found=false;
		if(objects==null)
			return;

		if(!found && useLast==true)
		{
			images=objects.tags("IMG");
			if(images==null)
			{
				return;
			}
			len = images.length;
			element = images[len-1];
			try
			{
				if(element.tabIndex!="-1")
				{
					element.setActive();
					found=true;
				}
			}
			catch(error)
			{
			
			}
		}

		if(!found)
		{
			inputs=objects.tags("INPUT");
			if(inputs==null)
			{
				return;
			}
			len = inputs.length;
			found = false;
			i=0;
			if(useLast==true)
			{
				i=len-1;
			}
			for(;i<len;i++)
			{
				element = inputs[i];
				allowro = (READ_ONLY_DEFAULT_FOCUS=="true" && READ_ONLY_TAB_INDEX == "0") ?true:false;
				if(canFocus(element, allowro))
				{
					try
					{
						element.focus();
						element.setActive();
						found=true;
					}
					catch(error)
					{
					
					}
					if(found)
						break;
				}
			}
		}		
		if(!found)
		{
			inputs=objects.tags("TEXTAREA");
			if(inputs==null)
			{
				return;
			}
				
			len = inputs.length;
			found = false;
			i=0;
			if(useLast==true)
			{
				i=len-1;
			}
			for(;i<len;i++)
			{
				element = inputs[i];
				if(canFocus(element, false))
				{
					try
					{
						element.focus();
						element.setActive();
						element.click();
						found=true;
					}
					catch(error)
					{
					
					}
					if(found)
						break;
				}
			}
		}
		if(!found)
		{
			defId = container.defaultbutton;
			if(defId && defId!="")
			{
				def = document.getElementById(defId);
				if(def)
				{
					buttontable=getPart(def, "table");
					buttontable.focus();
					buttontable.setActive();
				}
			}
			else
			{
				try 
				{
					if (!undef(container))
						container.focus();
					else
						return;
				}
				catch (error) 
				{
					return;
				}
			}
		}
	}

	function setFieldFocusbyId(elementId)
	{
		var focusElement = parent.document.getElementById(elementId);
		if(!undef(focusElement))
		{
			if(focusElement.tagName!="INPUT")
			{
				var childNodes = focusElement.all.tags("INPUT");
				if(childNodes.length>0)
				{
					focusElement = childNodes[0];
				}
			}
			
			if(!undef(focusElement))
			{
				focusField = focusElement;
				setFieldFocus(focusElement);
			}
		}	
	}
	
	function setFieldFocus(element)
	{
		if(stopFocus==true)
		{
			stopFocus=false;
			return;
		}
		try
		{
			if(canFocus(element, true))
			{
				element.fireEvent("ondeactivate");
				element.fireEvent("onactivate");
		
				element.focus();

				element.setActive();
				element.select();
			}
		}
		catch(exception)
		{
			
		}
	}	

	function canFocus(fld, ro)
	{
		returnVal = true;
		field = fld;
		allowreadonly = ro;
		if(allowreadonly==null)
			allowreadonly = false;
			
		if(field==null)
			return false;
			
		if(returnVal==true && field.readOnly==true)
		{
			if(!allowreadonly)
			{
				returnVal=false;
			}
		}
		return returnVal;
	}

	function actionkeys()
	{
		if(event.keyCode>=16 && event.keyCode <=18)
			return;
		//check to see if an action key was pressed...
	
		var key, keyPressed = -1, RUNACTION = "";
		var SHIFT = true, CTRL = true, ALT = true;
		
		if(undef(ACTIONKEYS))
			return;

		for(key in ACTIONKEYS)
		{
			actionKey = ACTIONKEYS[key].toUpperCase();
			keyPart1 = actionKey.substr(0, actionKey.indexOf("|"))
			lastplus = actionKey.lastIndexOf("+") + 1;
	
			actionkeycode = actionKey.substr(lastplus);
			if(actionKey.charCodeAt(actionKey.length-1)==event.keyCode || keyPart1.charCodeAt(keyPart1.length-1)==event.keyCode || actionkeycode == event.keyCode)
			{
				if(actionKey.length>4)
				{
					if(actionKey.search("CTRL") > -1 && event.ctrlKey == false)
					{
						CTRL = false;
					}
					if(actionKey.search("ALT") > -1 && event.altKey == false)
					{
						ALT = false;
					}
					if(actionKey.search("SHIFT") > -1 && event.shiftKey == false)
					{
						SHIFT = false;
					}
				}
				if(SHIFT == true && ALT == true && CTRL == true)
				{
					RUNACTION = ACTIONLIST[key];
				}
				break;
			}
		}
		if(RUNACTION != "")
		{
			itemtoclick = document.getElementById(RUNACTION);
			if(itemtoclick)
			{
				event.cancelBubble=true;
				itemtoclick.focus();
				itemtoclick.setActive();

				sendFrontEndEvent("clickHotKey", RUNACTION);
				return false;
			}
		}
	}

	function clickHotKey(itemId)
	{
		itemtoclick = document.getElementById(itemId);
		if(itemtoclick)
		{
			if(event)
			{
				event.returnValue=false;
				event.cancelBubble=true;
			}
			toolbarbutton_autoClick(itemtoclick);
		}
	}

	function sendFrontEndEvent(methodName, param)
	{
		if(!stopevents)
		{
			cEvent = new clientEvent("clientonly", methodName, param);
			if(working)
				clientEventQueue[clientEventQueue.length]=cEvent;
			else
				processFrontEndEvent(cEvent);
		}
	}

	function clickFileButton(id)
	{
		iFrameEl = document.getElementById("upload_iframe");
		ifButton = iFrameEl.contentWindow.document.getElementById(id);
		if(!undef(ifButton))
		{
			ifButton.click();
		}
		enableDoc();
	}

	function processFrontEndEvent(clientEvent)
	{
		eval(clientEvent.targetid+"('"+clientEvent.value+"')");
	}

	function showDialog(dialogId, tempDialogObj, openPageCount)
	{
		if(dialogId=="msgbox")
			unLockWait();
		openPages=openPageCount;
		hidePopup();
		hideObjs();
		
		var dialogObj = window.document.getElementById(tempDialogObj.id);
		if (dialogObj != null)
		{
			// 	If it's already there, delete it.
			//	This should not happen!
			removeDialog(dialogObj.id,openPages-1);
		}
		
		if (tempDialogObj != null)
		{
			var newDialogObj;
			if (designmode)
			{
				document.body.insertAdjacentHTML('beforeEnd', tempDialogObj.outerHTML);
				newDialogObj = document.getElementById(tempDialogObj.id);
			}
			else
			{
			    parent.document.body.insertAdjacentHTML('beforeEnd', tempDialogObj.outerHTML);
				newDialogObj = parent.document.getElementById(tempDialogObj.id);
			}

			updateScrollList(newDialogObj)
			
			positionDialog(newDialogObj);
	
			if (!designmode)
			    showWait(true, newDialogObj.id);

			openDialogs.push(newDialogObj);
		}
	    if(newDialogObj.scrollList)
	    {
		    scrollList=newDialogObj.scrollList.split(",");
			for(scrollItem=0;scrollItem<scrollList.length;scrollItem++)
			{
				scrll=document.getElementById(scrollList[scrollItem]);
				if(scrll)
					scrll.style.overflowX="auto";
			}
		}
		document.close();
		focusContainer = newDialogObj;
	}

	function updateScrollList(domObj)
	{
		coll = domObj.getElementsByTagName("DIV");
		if(!coll)
		{
			return;
		}
		scrollList = new Array;
		oldList = domObj.scrollList;
		if(!undef(oldList))
			scrollList = oldList.split(",");

		for(x=0;x<coll.length;x++)
		{
			objId = coll[x].id;
			overFlow = coll[x].style.overflowX;
			cName = coll[x].className;
			if(overFlow=="auto" || overFlow=="hidden" || cName=="dialog_contents_scrollable")
			{
				if(!inArray(scrollList, objId))
					scrollList[scrollList.length]=objId;
			}
		}
		sl=scrollList.join(",");
		domObj.scrollList=sl;

	}

	function inArray(arrayObj, val)
	{
		for(i=0;i<arrayObj.length;i++)
		{
			if(arrayObj[i]==val)
				return true;
		}
		return false;
	}

	function positionDialog(newDialogObj)
	{
		// get height, width of total client area and dialog
		var cHeight = document.body.offsetHeight;
		var cWidth = document.body.offsetWidth;

		// scroll offset makes sure popup still appears in middle of visible area if page is scrolled
		var scrolloffset = window.document.body.scrollTop;
		dHeight = (dHeight=="")? 200: dHeight;
		dWidth = (dWidth=="")? 500: dWidth;
	
		var dHeight = newDialogObj.clientHeight;
		var dWidth = newDialogObj.clientWidth;
		
		var left = (cWidth - dWidth) / 2;
		var top = (cHeight - dHeight) / 4 + scrolloffset;
		if(top<0)
			top=0;
		if(left<0)
			left=0;
		newDialogObj.style.left = left;
		newDialogObj.style.top = top;
		//newDialogObj.style.height = dHeight;
		if(dWidth>document.body.clientWidth)
			dWidth=document.body.clientWidth;
		newDialogObj.style.width = dWidth;
		moveableTopZ=moveableTopZ+2;
		newDialogObj.style.zIndex=moveableTopZ;
	}
	
	function showMoveableWindow(dialogId, tempDialogObj)
	{
		hideObjs();
				
		var dialogObj = window.document.getElementById(tempDialogObj.id);
		if (dialogObj != null)
		{
			// if it's already there, delete it.
			dialogObj.removeNode(true);			
		}
		
		coll = tempDialogObj.getElementsByTagName("DIV");
		list = "";
		for(x=0;x<coll.length;x++)
		{
			if(coll[x].style.overflowX=="auto")
			{
				list+=","+coll[x].id;
			}
		}
		if (tempDialogObj != null)
		{
			document.body.insertAdjacentHTML('beforeEnd', tempDialogObj.outerHTML);
			var newdialog = document.getElementById(tempDialogObj.id);
			var cHeight = document.body.offsetHeight;
			var cWidth = document.body.offsetWidth;
			var dHeight = newdialog.clientHeight;
			var dWidth = newdialog.clientWidth;
		
			// scroll offset makes sure popup still appears in middle of visible area if page is scrolled
			var scrolloffset = window.document.body.scrollTop;
			dHeight = (dHeight=="")? 200: dHeight;
			dWidth = (dWidth=="")? 500: dWidth;

			var left = null;
			var top = null;
			var pos = getWindowPositionObject(dialogId);
			if (pos == null)
			{
				left = (cWidth - dWidth) / 2;
				top = (cHeight - dHeight) / 4 + scrolloffset;
				saveWindowPosition(dialogId, top, left);
			}
			else
			{
				left = pos.left;
				top = pos.top;
			}
			newdialog.scrollList=list.substring(1);
			newdialog.style.left = left;
			newdialog.style.top = top;
			moveableTopZ++;
			newdialog.style.zIndex=moveableTopZ;
		}
		document.close();
		focusContainer = newdialog;
	}


	function removeDialog(dialogId, openPageCount)
	{
		openPages=openPageCount;
		var newDialogs = new Array();
		for(i=0;i<openDialogs.length;i++)
		{
			if(openDialogs[i].id==dialogId)
				dialog = openDialogs[i];
			else
				newDialogs[newDialogs.length]=openDialogs[i];
		}
		if(dialog)
		{
			openDialogs=newDialogs;
			dialog.removeNode(true);
		}
		hideWait(dialogId);
		showObjs();
		if(openPages==1 && moveableTopZ>500)
		{
			moveableTopZ=120;
		}
		document.close();
	}
		
	function showWindow(dialogId)
	{
		var dialogObj = window.document.getElementById(dialogId);
	
		if (dialogObj)
		{
			// get height, width of total client area and dialog
			var cHeight = document.body.offsetHeight;
			var cWidth = document.body.offsetWidth;
			var dHeight = dialogObj.clientHeight;
			var dWidth = dialogObj.clientWidth;
		
			// scroll offset makes sure popup still appears in middle of visible area if page is scrolled
			var scrolloffset = window.document.body.scrollTop;
			dHeight = (dHeight=="")? 200: dHeight;
			dWidth = (dWidth=="")? 500: dWidth;
					
			var left = (cWidth - dWidth) / 2;
			var top = (cHeight - dHeight) / 4 + scrolloffset;
			
			dialogObj.style.left = left;
			dialogObj.style.top = top;
			dialogObj.style.height = dHeight;
			dialogObj.style.width = dWidth;
	
			dialogObj.style.display = "inline";
		}
		document.close();
	}
		
	function hideWindow(dialogId)
	{
		var dialogObj = window.document.getElementById(dialogId);
		if(dialogObj)
			dialogObj.style.display = "none";
		document.close();
	}

	function removeMoveableWindow(dialogId)
	{
		var dialog = window.document.getElementById(dialogId);
		if(dialog)
			dialog.removeNode(true);
		showObjs();
		document.close();
	}
	
	function WindowPosition(i, t, l)
	{
		this.id = i;
		this.top = t;
		this.left = l;
	}
	
	function saveWindowPosition(id, top, left)
	{
	    // if we're dealing with a properties window, we want them all the same
	    if (id.indexOf("mxdproperties_") == 0)
		    id = "mxdproperties_";

		var pos = getWindowPositionObject(id);

		// if we don't find one, add it.  otherwise reset the one we found
		if (pos == null)
		{
			pos = new WindowPosition(id, top, left);
			addWindowPositionObject(pos);
		}
		else
		{
			pos.top = top;
			pos.left = left;
		}
	}
	
	function getWindowPositionObject(id)
	{
	    // if we're dealing with a properties window, we want them all the same
		if (id.indexOf("mxdproperties_") == 0)
		    id = "mxdproperties_";
		    
		var pos = null;
		// look in windowPositions array to see if it's there.  if it isn't, return null
		for (i = 0; i < windowPositions.length; i ++)
		{
			if (windowPositions[i].id == id)
			{
				pos = windowPositions[i];
				break;
			}
		}
		return pos;		
	}

	function addWindowPositionObject(position)
	{
		windowPositions[windowPositions.length] = position;
	}

	function hideObjs()
	{
		if(openDialogs.length>=1 || objsHidden)
			return;

		objs = document.all.tags("OBJECT");
		len=objs.length;
		for(i=0;i<len;i++)
		{
			obj = objs[i];
			ch = obj.clientHeight;
			if(ch>0)
			{
				if (obj.height.indexOf("%") > -1)
					obj.dimensionHeight = obj.height;
				else
					obj.dimensionHeight = ch;

				if (obj.width.indexOf("%") > -1)
					obj.dimensionWidth = obj.width;
				else
					obj.dimensionWidth = obj.clientWidth;

				obj.style.height="1px";
				obj.style.width="1px";
				back = document.getElementById(obj.id+"_back");
				if(back)
					back.style.display="inline";
				objsHidden = true;
			}
		}
	}

	function showObjs()
	{
		if(openDialogs.length>=1 || objsHidden==false)
			return;

		objsHidden = false;
		objs = document.all.tags("OBJECT");
		len=objs.length;
		for(walkobjs=0;walkobjs<len;walkobjs++)
		{
			obj = objs[walkobjs];
			back = document.getElementById(obj.id+"_back");
			if(back)
				back.style.display="none";

			obj.style.height=obj.dimensionHeight;
			obj.style.width=obj.dimensionWidth;
			obj.height=obj.dimensionHeight;
			obj.width=obj.dimensionWidth;
		}
	}

	function updateDetailMenu(imageid, imgsrc, detailtype, mxevent)
	{
		var image = document.getElementById(imageid);
		if (image != null)
		{
			image.src = imgsrc;
			image.detailtype=detailtype;
			image.mxevent=mxevent;
		}
	}
	
	function showFieldHelp()
	{
		if(event.ctrlKey!=true && event.altKey==true && (event.keyCode == 73 || event.keyCode == 112)) 
		{
			el = event.srcElement;
			control=getControl(el);
			
			if (event.keyCode != 112 && event.keyCode!=73)
				shared_handleChange(el);
			
			var showhelp = "fieldhelp";
			if (event.keyCode == 73)
				showhelp = "internalhelp";

			sendEvent(showhelp, control.id, null, el.dataattribute);
			event.cancelBubble=true;
			event.returnValue=false;
			return false;
		}
	}	
	
	function clearFiring()
	{
		firingControl=null;
		usefiringcontrol = false;
	}

	function swapImages(image)
	{
		if (undef(image))
			return;
		var alt = null;
		var altsrc = null;
		if (image != null)
		{
			if (image.altsrc != null)
			{
				altsrc = image.src;
				image.src = image.altsrc;
				image.altsrc = altsrc;
			}
			if (image.flipalt != null)
			{
				alt = image.alt;
				image.alt = image.flipalt;
				image.flipalt = alt;
			}
		}
	}

	//Used for logging/testing
	function log(stringVal, stamp)
	{
		if(logging==false)
			return;
		timestamp = stamp;
		var fso = new ActiveXObject("Scripting.FileSystemObject");
		var a = fso.OpenTextFile(logfile, 8, true);
		if(timestamp!=null && timestamp==true)
			a.WriteLine(new Date + " : " + stringVal);
		else
			a.WriteLine(stringVal);
		a.Close();
	}

	// method to open a new window to display an attached document
	function openURL(url)
	{
		while(url.search("#")>-1)
		{
			url=url.replace("#", "%23");
		}
		stopFocus=true;
		var newWindow = window.open(url,'newWindow','left=100,top=100,height=500,width=800,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes');
		newWindow.focus();
	}

	function clickDefaultButton(id)
	{
		clickedDefault = false;
		try
		{
			el = document.getElementById(id);
			if(undef(el))
				return true;

			defId = el.defaultbutton;
			if(defId && defId!="")
			{
				def = document.getElementById(defId);
				if(def)
				{
					pushbutton_clickButton(def);
					clickedDefault=true;
					event.cancelBubble=true;
					event.returnValue=false;
				}
			}
		}
		catch(error)
		{
		}
		return clickedDefault;
	}
	
	function library_showElement(ctrlInst, id)
	{
		var success = true;
		var eventElement = ctrlInst.document.getElementById(id);
		if(!undef(eventElement))
		{
			if(eventElement.style.display=="")
			{
				success = false;
			}
			eventElement.style.display = "";
		}
		return success;
	}
	
	function library_hideElement(ctrlInst, id)
	{
		var success = true;
		var eventElement = ctrlInst.document.getElementById(id);
		if(!undef(eventElement)){
			if(eventElement.style.display == "none")
			{
				success = false;
			}
			eventElement.style.display = "none";
		}	
		return success;
	}

	function library_cancelEventBubbling()
	{
		event.cancelBubble = true;
		event.returnValue = false;
	}

	function library_getMxEvents(ctrlInst, eventElement)
	{
		eventElement = library_getElementHavingEvent(ctrlInst, eventElement);
		var mxeventColl = eventElement.getAttribute("mxevent");
		if(mxeventColl==null)
		{
			mxeventColl = "";
		}
		mxeventColl = mxeventColl.split(",");
		return mxeventColl;
	}
		
	function library_getElementHavingEvent(ctrlInst, eventElement)
	{

		var startElement = eventElement;
		var mxeventColl = startElement.getAttribute("mxevent");
		while(undef(mxeventColl))
		{
			eventElement = eventElement.parentElement;
			if( (eventElement==ctrlInst) || (eventElement==null) )
			{
				break;
			}
			mxeventColl = eventElement.getAttribute("mxevent");
		}
		if(eventElement==null)
		{
			eventElement = startElement;
		}

		return eventElement;
	}

	function library_getControl(startElement)
	{
		var ctrlInst = null;
		var attrValue = "";
		if(!undef(startElement))
		{
			attrValue = startElement.getAttribute("control");
			while(attrValue != "true")
			{
				startElement = startElement.parentElement;
				attrValue = startElement.getAttribute("control");
			}
			ctrlInst = startElement;
		}	
		return ctrlInst;
	}
	
	function library_getControlByType(startElement, controlType)
	{
		var ctrlInst = null;
		var attrValue = "";
		var attrCtrlType = "";
		if(!undef(startElement))
		{
			attrValue = startElement.getAttribute("control");
			attrCtrlType = startElement.getAttribute("controltype");
			while( (attrValue!="true") || (attrCtrlType!=controlType))
			{
				startElement = startElement.parentElement;
				if(!undef(startElement))
				{
					attrValue = startElement.getAttribute("control");
					attrCtrlType = startElement.getAttribute("controltype");
				}
				else
				{
				    break;
				}
			}
			ctrlInst = startElement;
		}	
		return ctrlInst;
	}
	
	function webColor(hex, red, green, blue)
	{
		this.red=red;
		this.green=green;
		this.blue=blue;
		if(hex && hex.substring(0,1)!="#")
			hex="#"+hex;
		this.hex = hex;
		if(this.hex && this.hex!="")
		{
			this.red = getRed();
			this.green = getGreen();
			this.blue = getBlue();
		}
		else
		{
			this.hex = "#"+getHex();
		}

		function getHex()
		{
			if(!this.hex || this.hex=="")
			{
				var newHex = "";
				tmp = parseInt(red).toString(16);
				if (tmp.length < 2)
					tmp = "0" + tmp;
				newHex+=tmp;
				tmp = parseInt(green).toString(16);
				if (tmp.length < 2)
					tmp = "0" + tmp;
				newHex+=tmp;
				tmp = parseInt(blue).toString(16);
				if (tmp.length < 2)
					tmp = "0" + tmp;
				newHex+=tmp;
				hex = newHex.toUpperCase();
			}
			return hex;
		}

		function getRed()
		{
			if(!this.red || this.red=="")
			{
				a = MakeNum(hex.substr(1,1));
				b = MakeNum(hex.substr(2,1));
				red = (a*16)+(b*1);

			}
			return red;
		}

		function getGreen()
		{
			if(!this.green || this.green=="")
			{
				a = MakeNum(hex.substr(3,1));
				b = MakeNum(hex.substr(4,1));
				green = (a*16)+(b*1);
			}
			return green;
		}

		function getBlue()
		{
			if(!this.blue || this.blue=="")
			{
				a = MakeNum(hex.substr(5,1));
				b = MakeNum(hex.substr(6,1));
				blue = (a*16)+(b*1);

			}
			return blue;
		}

		function MakeNum(str)
		{
			if((str >= 0) && (str <= 9))
				return str;

			switch(str.toUpperCase()) 
			{
				case "A": return 10;
				case "B": return 11;
				case "C": return 12;
				case "D": return 13;
				case "E": return 14;
				case "F": return 15;
		   }
		}
	}
	
	function webBorder(width, style, color)
	{
		this.color = color;
		this.style=style;
		this.width=width;
		this.toString=toString;
		
		function toString()
		{
			return width + " " + style + " " + color.hex; 
		}
		
	}
