// js\WxCore.js
// (c) 1993 - 2009 EMC
//
// The WxCore.js file contains the core javascript library required by ApplicationXtender Web Access

//global flag that tells us if the form was submitted.
var g_bFormSubmitted = false;

var thisForm = null;


function HookSubmit()
{
   thisForm = document.forms[0];

   //Create a new pointer to the intrinsic submit method
   thisForm.__submit = thisForm.submit;
   
   //replace the intrinsic submit method point with a pointer to
   //our own version of this method.
   thisForm.submit = __submitForm;
}

//Our replacement submit method
function __submitForm()
{
   //Fire the event that triggers onsubmit event.
   if (IsExplorer())
      thisForm.fireEvent("onsubmit");
   else
      thisForm.onsubmit();
      
   //call the original submit method.
   thisForm.__submit();
}

//This is the default hanlder for the onsubmit event.
function SetFormSubmitted()
{
   g_bFormSubmitted = true;
}

//This method is called from the unload event which checks to see if we should autologout.
function CheckAutoLogout()
{
   var oQuery = new QueryString(document)
   var enableAutoLogout = document.forms[0].elements["AutoLogout"].value;
   if (g_bFormSubmitted == false && enableAutoLogout == "True")
      window.open("AutoLogout.aspx", "AutoLogout", "height=1,width=1,toolbar=no,menubar=no,status=no");         
}

function NormalizePageLayout()
{
   var screenWidth;
   var screenHeight;
   
   if (window.innerWidth == null) 
      screenWidth = document.body.clientWidth - 5;
   else 
      screenWidth = window.innerWidth - 5;

   if (window.innerHeight == null) 
      screenHeight = document.body.clientHeight - 5;
   else 
      screenHeight = window.innerHeight - 5;

   // PAGE LAYOUT WIDTH and HEIGHT ADJUST
   var oPL = document.getElementById("PageLayout");
   if (oPL != null)
   {
      oPL.style.height = screenHeight.toString() + "px";
      oPL.style.width = screenWidth.toString() + "px";
   }

   // MENU ROW HEIGHT ADJUST
   var oMenuRow = document.getElementById("PageLayout_PageLayoutMenuRow");
   if (oMenuRow != null && oMenuRow.style.display != "none")
   {
      if ( oMenuRow.style.pixelHeight == null || oMenuRow.style.pixelHeight == 0 )
         screenHeight = screenHeight - oMenuRow.clientHeight; 
      else
         screenHeight = screenHeight - oMenuRow.style.pixelHeight; 
   }

   // TOOLBAR ROW HEIGHT ADJUST
   var oToolbarRow = document.getElementById("PageLayout_PageLayoutToolbarRow");
   if (oToolbarRow != null && oToolbarRow.style.display != "none")
   {
      if ( oToolbarRow.style.pixelHeight == null || oToolbarRow.style.pixelHeight == 0 )
         screenHeight = screenHeight - oToolbarRow.clientHeight;
      else
         screenHeight = screenHeight - oToolbarRow.style.pixelHeight; 
   }
    
   // THUMBNAIL PANE WIDTH ADJUST
   var oThumbnailPane = document.getElementById("PageLayout_ThumbnailContainer");
   if (oThumbnailPane != null && oThumbnailPane.style.display != "none")
   {
      oThumbnailPane.style.height = screenHeight.toString() + "px";
      oThumbnailPane.style.width = "125 px";
    
      if ( oThumbnailPane.style.pixelWidth == null || oThumbnailPane.style.pixelWidth == 0 )
         screenWidth = screenWidth - oThumbnailPane.clientWidth;
      else
         screenWidth = screenWidth - oThumbnailPane.style.pixelWidth;  

      // adjust thumbnail DIV
      var oThumbnailPanel = document.getElementById("PageLayout_PageLayoutThumbnailContainerPanel");
      if (oThumbnailPanel != null)
         oThumbnailPanel.style.height = screenHeight.toString() + "px";
   }
      
   // INDEX PANE WIDTH ADJUST
   var oIndexingPane = document.getElementById("PageLayout_IndexingContainer");
   if (oIndexingPane != null && oIndexingPane.style.display != "none")
   {
      oIndexingPane.style.height = screenHeight.toString() + "px";

      if ( oIndexingPane.style.pixelWidth == null || oIndexingPane.style.pixelWidth == 0 )
         screenWidth = screenWidth - oIndexingPane.clientWidth;
      else
         screenWidth = screenWidth - oIndexingPane.style.pixelWidth;
      
      var oIndexingPanel = document.getElementById("PageLayout_IndexPanel");
      if (oIndexingPanel != null && oIndexingPanel.style.display != "none")
         oIndexingPanel.style.height = screenHeight.toString() + "px";
   }

   // GRIP PANE WIDTH ADJUST
   var oGripPane = document.getElementById("PageLayout_IndexGripSeperator");
   if (oGripPane != null && oGripPane.style.display != "none")
   {
      if ( oGripPane.style.pixelWidth == null || oGripPane.style.pixelWidth == 0 )
         screenWidth = screenWidth - oGripPane.clientWidth; 
      else
         screenWidth = screenWidth - oGripPane.style.pixelWidth;
   }

   // CONTENT PANE ADJUST
   var oConentPane = document.getElementById("PageLayout_ContentContainer");
   if (oConentPane != null)
   {
      if (oConentPane.parentNode.style.paddingTop != "")
      {
         screenWidth = screenWidth - 10;
         screenHeight = screenHeight - 10;
      }
      if (screenWidth < 0)
         screenWidth = 0;
      if (screenHeight < 0)
         screenHeight = 0;
    
      // CONTENT PANE WIDTH AND HEIGHT ADJUST
      oConentPane.style.width = screenWidth.toString() + "px";
      oConentPane.style.height = screenHeight.toString() + "px";

      // PAGEVIEW TOOLBAR ROW HEIGHT ADJUST
      var oEmbeddedToolbarRow = document.getElementById("PageLayout_PageView_PageLayout_PageLayoutToolbarRow");
      if (oEmbeddedToolbarRow != null && oEmbeddedToolbarRow.style.display != "none")
      {
         if ( oEmbeddedToolbarRow.style.pixelHeight == null || oEmbeddedToolbarRow.style.pixelHeight == 0 )
            screenHeight = screenHeight - oEmbeddedToolbarRow.clientHeight;
         else
            screenHeight = screenHeight - oEmbeddedToolbarRow.style.pixelHeight; 
      }

      // PAGEVIEW CONTENT WIDTH and HEIGHT ADJUST
      var oEmbeddedPageView = document.getElementById("PageLayout_PageView_PageLayout_ContentContainer");
      if (oEmbeddedPageView != null)
      {
         oEmbeddedPageView.style.height = (screenHeight - 5).toString() + "px";
         oEmbeddedPageView.style.width = (screenWidth - 5).toString() + "px";
      }
   }
   
   var oSelectedControlID = document.forms[0].elements["SelectedControl"];
   if (oSelectedControlID != null)
   {
      var selectedControlId = oSelectedControlID.value;
      if (selectedControlId != null && selectedControlId.length > 0)
      {
         var oSelectedControl = document.getElementById(selectedControlId);
         if (oSelectedControl != null)
         {
            oSelectedControl.select();
            oSelectedControl.focus();
         }
      }
   }
}





/////////////////////////////////////////////////////////////////////////////////////
// Browser Info Library
/////////////////////////////////////////////////////////////////////////////////////
////////
//////
////
//

//	IsVersionMin(nVersion)
//
// This method returns true if the current browser	version is version 4.0 or greater.
function IsVersionMin(nVersion)
{
   return (parseInt(navigator.appVersion.charAt(0)) >= nVersion)
}
	 
	 
//
//	IsNav()
//
//	This method	returns true if the current browser	is	Netscape	naviagtor version	
//	4.0 or greater, note Firefox and Safari report Netscape as appName		
function IsNav()
{
   return IsVersionMin(4) && (navigator.appName == "Netscape");
}
		  
//
//	IsExplorer()
//
//	This method	returns true if the current browser	is	Microsoft IE version	
//	4.0 or greater		
function IsExplorer()
{
   return IsVersionMin(4) && (navigator.appVersion.indexOf("MSIE") != -1)
}
   
//
//	IsSafari()
//
//	This method	returns true if the current browser	is	Safari version 5 or better
function IsSafari()
{
   return IsVersionMin(5) && (navigator.appVersion.indexOf("Safari") != -1);
}

//
//	IsExplorerMinVer()
//
//	This method	returns true if the current browser	is	Microsoft IE version	
//	nVer or higher
//function IsExplorerMinVer(nVer)
//{
//   return IsVersionMin(nVer) && (navigator.appVersion.indexOf("MSIE") != -1)
//}
   
	 
//	Trim(gValue)
//
//	This function trims the	leading and	trailing	white	space	from the	
//	input	string gValue
function Trim(gValue)
{
   //Trim leading white space
   while (gValue.charAt(0) == " ")
      gValue =	gValue.substring(1,gValue.length);
   	 
   //Trim trailing whie space
   var cChar = gValue.charAt(gValue.length-1);
   while (cChar == " ")
   {
      gValue = gValue.substring(0,gValue.length - 1);
      cChar = gValue.charAt(gValue.length -1);
   }
   	 
   return gValue;
}
	 
function _debugInspect(obj)
{
   var dbgWnd = window.open("","inspect","HEIGHT=600,WIDTH=600,scrollbars=yes,resizable=yes")
   var wintxt = "<HTML><HEAD><TITLE>ApplicationXtender Web Access .NET</TITLE></HEAD><BODY>"
   wintxt += "<TABLE cellpadding='2' cellspacing='2' border='0' width='100%'>";
   wintxt += "<TR><TD width='30%'><B>Property</B></TD><TD width='70%'><B>Value</B></TD></TR>";
   for (prop in obj)
   {
      if (typeof obj[prop] != "function" && typeof obj[prop] != "unknown")
         wintxt += "<TR><TD nowrap>" + prop + "</TD><TD nowrap>" + obj[prop] + "</TD></TR>";
   }
   wintxt += "</TABLE>";
   
   
   wintxt += "<INPUT TYPE=button VALUE='Close' onClick='self.close()' id=button1 name=button1>"
   wintxt += "</FORM></BODY></HTML>"
   dbgWnd.document.write(wintxt)
   dbgWnd.document.close()
   return true
}      
   
   
   
   
   
   
/////////////////////////////////////////////////////////////////////////////////////
// QueryString Object 
/////////////////////////////////////////////////////////////////////////////////////
// To use the QueryString object you'll need create an instance of this
// object using the following syntax
//
// var oQuery = new QueryString(document)
//
// The constructor takes only one arguement and that is the current pages document object.
// This method gets the query string from the document object and parses it.  It then creates
// a named collection of the query string items.  For example to to find out the value of 
// the name attribute in the following query string:
//    MyPage.htm?Name=Rudy&Title=Engineer
// you would used the following syntax:
//    oQuery["Name"]
//
// This object has two additional property count and value.  Count returns the number of items
// in the collection and value return the query string parameters unparsed (excluding the leading
// question mark).
//////////////////////////////////////////////////////////////////////////////////////
////////
//////
////
//	 
function QueryString(document)
{
   var _instance = this;
	var szHref = document.location.search
   // First, get a list of all cookies that pertain to this document.
   // We do this by reading the magic Document.cookie property.
   if (szHref == null || szHref == "") 
   {
      _instance.length = 0
      return true;
   }

   //The first character is always a '?' so we need to trim that off   
   szHref =	szHref.substring(1,szHref.length);      
   
   return QueryStringEx(szHref,_instance);
}
   

function QueryStringEx(szHref)
{
   var _instance;
   if (QueryStringEx.arguments.length == 2)
      _instance = QueryStringEx.arguments[1];
   else
      _instance = this;
   
   if (szHref == null || szHref == "") 
   {
      _instance.length = 0
      return true;
   }

   var a = szHref.split("&");  // break it into array of name/value pairs
   
   for(var i=0; i < a.length; i++)  // break each pair into an array
      a[i] = a[i].split("=");
       
   // Now that we've parsed the query string value, set all the names and values
   // of the state variables in this QueryString object. Note that we unescape()
   // the property value.
   for(var i = 0; i < a.length; i++)
   {
      _instance[a[i][0]] = decodeURL(a[i][1]);
   }
   
   return QueryBuilder(_instance);
}
   
function QueryBuilder()
{
   var _instance;
   if (QueryStringEx.arguments != null)
      _instance = QueryStringEx.arguments[0];
   else
      _instance = this;
      
   _instance.$Target = "";
   _instance.toString = _getQueryString;
   _instance.setTarget = _setTarget;
   _instance = null;
   return true;

}   
   
function _setTarget(szValue)
{
   this.$Target = szValue;
}   
   
   
function _getQueryString()
{   
   var szQueryString = ""
   
   if (this.$Target.length > 0)
      szQueryString = this.$Target + "?";
      
   for(var prop in this)
   {
      // Ignore properties with names that begin with '$' and also methods.
      if (prop.charAt(0) == "$" || (typeof this[prop]) == "function") 
         continue;
         
      if (szQueryString.charAt(szQueryString.length -1) != "?") 
         szQueryString += "&";
         
      szQueryString += encodeURL(prop) + "=" + encodeURL(this[prop].toString());
   }

   return szQueryString
}
   
function encodeURL(szValue)
{
   if (typeof szValue == "undefined")
      return szValue;
      
   szValue = szValue.toString();
   var szRet = encodeURI(szValue);  
   
   while(szRet.indexOf('#') != -1)
      szRet = szRet.replace('#','%23');
   while(szRet.indexOf('&') != -1)
      szRet = szRet.replace('&','%26');
   while(szRet.indexOf('+') != -1)
      szRet = szRet.replace('+','%2b'); 
   while(szRet.indexOf('=') != -1)
      szRet = szRet.replace('=','%3d'); 
   
   return szRet;
}
   
function encodeDelimiter(szValue)
{
    if (typeof szValue == "undefined")
      return szValue;
      
   var szRet = szValue.toString();
   
   while(szRet.indexOf(',') != -1)
      szRet = szRet.replace(',','%2c');
   
   return szRet;
}

function decodeDelimiter(szValue)
{
   if (typeof szValue == "undefined")
      return szValue;
      
   if (szValue == null)
      return "";
      
   while(szValue.indexOf('%2c') != -1)
      szValue = szValue.replace('%2c',',');   
   return szValue;
   
}
   
// This is a helper method used to extract the cookie values that are set by the
// server during an image request.  The cookie contains status information about
// the image.
function CookieExtract(strCookie, strCookieName, strKey)
{
   // First, get a list of all cookies that pertain to this document.
   // We do this by reading the magic Document.cookie property.
   
   strValue = "";
   
   var allcookies = decodeURL(strCookie);
   if (allcookies == "") 
      return "";
      
   var start = allcookies.indexOf(strCookieName + "=");
   if (start == -1) 
      return "";   // cookie not defined for this page.
      
   // Now extract just the named cookie from that list
      
   start += strCookieName.length + 1;  // skip name and equals sign.
   
   var end = allcookies.indexOf(";", start);
   if (end == -1) 
      end = allcookies.length;
      
   var cookieval = allcookies.substring(start, end);
   
   // Now that we've extracted the value of the named cookie, we've
   // got to break that value down into individual state variable 
   // names and values. The name/value pairs are separated from each
   // other with ampersands, and the individual names and values are
   // separated from each other with colons. We use the split method
   // to parse everything.
   
   var a = cookieval.split("&");  // break it into array of name/value pairs
   
   for (var i=0; i < a.length; i++)  // break each pair into an array
      a[i] = a[i].split("=");
       
   // Now that we've parsed the cookie value, set all the names and values
   // of the state variables in this Cookie object. 
   for (var i = 0; i < a.length; i++)
   {
      if (decodeURL(a[i][0]) == strKey)
      {
         return decodeURL(a[i][1]);
      }
   }
      
   // We're done, so return the success code.
   return "";
}
   
function decodeURL(szValue)
{
   if (typeof szValue == "undefined")
      return szValue;
      
   if (szValue == null)
      return "";
      
   //Replace plus signs with ' '.  WHen you store a cookie value on the server side, the 
   //Response object automatically escapes values.  however, it places '+' for ' ' instead
   //of %20.  
   while(szValue.indexOf('+') != -1)
      szValue = szValue.replace('+',' ');  
   
   while(szValue.indexOf('%23') != -1)
      szValue = szValue.replace('%23','#');   
   while(szValue.indexOf('%26') != -1)
      szValue = szValue.replace('%26','&');
   while(szValue.indexOf('%2b') != -1)
      szValue = szValue.replace('%2b','+');
   while(szValue.indexOf('%3d') != -1)
      szValue = szValue.replace('%3d','=');

	try
	{      
		return decodeURI(szValue);
   }
   catch(e)
   {
		return szValue;
   }
} 

/////////////////////////////////////////////////////////////////////////////////////
// Miscellaneous Functions
/////////////////////////////////////////////////////////////////////////////////////
////////
//////
////
//

function OnMonitor(oItem)
{
   var oQuery = new QueryBuilder();
   oQuery.setTarget("WmiMonitor.aspx");
   oQuery["DataSource"] = document.forms[0].elements["DataSource"].value;
   oQuery["OType"] = oItem;
   window.open(oQuery.toString(), "Monitor", "width=550,height=475,resizable=yes,scrollbars=yes,status=no,titlebar=no,menubar=no,toolbar=no", true);
}

function OnAdmin()
{
   var oQuery = new QueryBuilder();
   oQuery.setTarget("Admin.aspx");
   oQuery["DataSource"] = document.forms[0].elements["DataSource"].value;
   window.open(oQuery.toString(), "Admin","resizable=yes,scrollbars=yes,status=yes,titlebar=no,menubar=no,toolbar=no", true);
}

//This is an event handler used to open the settings.asp page as a popup.
function OnConfig()
{
   var oQuery = new QueryBuilder();
   oQuery.setTarget("Settings.aspx");
   oQuery["DataSource"] = document.forms[0].elements["DataSource"].value;
   window.open(oQuery.toString(), "Settings", "left=100,top=100,width=785,height=565,resizable=yes,scrollbars=yes,status=no,titlebar=no,menubar=no,toolbar=no", true);
}

function OnComponentCheck()
{
   var urlBld = new QueryBuilder();
   urlBld.setTarget("ComponentCheck.aspx");
   window.open(urlBld.toString(), "Check_Installed_Components", "width=550,height=480,resizable=yes,scrollbars=yes,status=no,titlebar=no,menubar=no,toolbar=no", true);
}

function OnHelp()
{
   helpURL = document.forms[0].elements["HelpTopic"].value;
   window.open(helpURL, "WxHelp", "width=750,height=550,resizable=yes,scrollbars=yes,status=no,titlebar=no,menubar=no,toolbar=no", true);
}

function OnAbout()
{
   var urlBld = new QueryBuilder();
   urlBld.setTarget("About.aspx");
   window.open(urlBld.toString(), "About_WebXtender", "width=610, height=540,resizable=yes,scrollbars=yes,status=no,titlebar=no,menubar=no,toolbar=no", true);
}

/////////////////////////////////////////////////////////////////////////////////////
// Context Menu Functions
/////////////////////////////////////////////////////////////////////////////////////
////////
//////
////
//
function CancelContextMenu(event)
{
	var oContextMenu = document.getElementById("oContextMenu");
	if(typeof oContextMenu != "undefined" && oContextMenu != null)
	{
	   if(oContextMenu.getAttribute("status") == "true")
		{
		   // Reset the context menu, release mouse capture, and hide it.	
		   oContextMenu.style.display="none";
		   oContextMenu.setAttribute("status","false");
		   ClearTableRows(oContextMenu);
		   if(event != null)
   		   event.returnValue = false;
		}
   }
   
   CancelWfxContextSubMenu();
   
   if (bSkipCloseFieldIndexPopup == true)
   {
      bSkipCloseFieldIndexPopup = false;
   }
   else
   {
      CloseFieldIndexPopup();
   }
}

function CancelWfxContextSubMenu(event)
{
   var oWorkflowContextMenu = document.getElementById("oWorkflowContextMenu");
   if(typeof oWorkflowContextMenu != "undefined" && oWorkflowContextMenu != null)
   {
      if(oWorkflowContextMenu.getAttribute("status") == "true")
      {
         // Reset the context menu, release mouse capture, and hide it.	
         oWorkflowContextMenu.style.display="none";
         oWorkflowContextMenu.setAttribute("status","false");
         ClearTableRows(oWorkflowContextMenu);
         if(event != null)
            event.returnValue = false;
      }
  }

  CancelWfxContextSubSubMenu(event);
}

function CancelWfxContextSubSubMenu(event) {
    var oWIMContextMenu = document.getElementById("oWIMContextMenu");
    if (typeof oWIMContextMenu != "undefined" && oWIMContextMenu != null) {
        if (oWIMContextMenu.getAttribute("status") == "true") {
            // Reset the context menu, release mouse capture, and hide it.
            oWIMContextMenu.style.display = "none";
            oWIMContextMenu.setAttribute("status", "false");
            ClearTableRows(oWIMContextMenu);
            if (event != null)
                event.returnValue = false;
        }
    }

    var oWfxContextMenu = document.getElementById("oWfxContextMenu");
    if (typeof oWfxContextMenu != "undefined" && oWfxContextMenu != null) {
        if (oWfxContextMenu.getAttribute("status") == "true") {
            // Reset the context menu, release mouse capture, and hide it.
            oWfxContextMenu.style.display = "none";
            oWfxContextMenu.setAttribute("status", "false");
            ClearTableRows(oWfxContextMenu);
            if (event != null)
                event.returnValue = false;
        }
    }
}

function ClearTableRows(oTable)
{
   if (oTable == null)
      return;
   var rowCount = oTable.rows.length;
   var i;
   for(i = 0; i < rowCount ; i++)
      oTable.deleteRow(0);
}   

function DoPopup(event)
{
   //set to false to indicate that we don't wish to bubble this event to the parent.
	event.returnValue = false;
	if(event.stopPropagation)
	   event.stopPropagation();

   //Kill the browser's default action for this event (displaying its own context menu)
   if (event.preventDefault)
      event.preventDefault();
   
   var oContextMenu = document.getElementById("oContextMenu");
   
   var nBodyHeight = 0;
   var nBodyWidth = 0;
   var nScrollTop = 0;
   var nScrollLeft = 0;
   var offsetTop = 0;
 
   // Relocate the menu to an offset from the mouse position
   if(typeof oContextMenu.style.pixelTop == "undefined")
   {
      // Make the menu visible.
      oContextMenu.style.display = "block";
      // Set its STATUS to true
      oContextMenu.setAttribute("status", "true");
       
      // Netscape 7.0, Firefox
      nScrollTop = document.body.scrollTop;
      nScrollLeft = document.body.scrollLeft;
      nBodyHeight = document.body.offsetHeight;
      nBodyWidth = document.body.offsetWidth;
      
      var menuTop =  nScrollTop + event.clientY - 5;
      var menuLeft = nScrollLeft + event.clientX;
      
      var menuHeight = oContextMenu.offsetHeight;
      var menuWidth = oContextMenu.offsetWidth;
      
      // The viewport (nBodyHeight) is the area of the WX screen not including the toolbar at the top.
      //
      // If there is enough room to fit the context menu in the viewport,
      // and if the y coordinate of the mouse is such that the menu would be cut off by the
      // bottom of the viewport, then move the top of the menu high enough so the bottom edge
      // of the menu will coincide with the bottom of the viewport.      
      if ( (nBodyHeight >= menuHeight) && ((menuTop + menuHeight) > (nBodyHeight + offsetTop)))
      {
         menuTop = nBodyHeight - menuHeight + offsetTop;
      }
      
      if ( (nBodyWidth >= menuWidth) && ((menuLeft + menuWidth) > nBodyWidth))
      {
	     menuLeft = nBodyWidth - menuWidth;
      }
      
      oContextMenu.style.top =  menuTop;
      oContextMenu.style.left = menuLeft;
   }
   else
   {
       // Make the menu visible.
      oContextMenu.style.display = "block";
      // Set its STATUS to true
      oContextMenu.setAttribute("status", "true");
   
      // IE, AppleMAC-Safari
      var container = document.getElementById("PageLayout_ContentContainer");
      nScrollTop = container.scrollTop;
      nScrollLeft = container.scrollLeft;
      nBodyHeight = container.offsetHeight;
      nBodyWidth = container.offsetWidth;
      offsetTop = container.offsetParent.offsetTop;

      var elem = event.srcElement;

      var menuTop; 
      var menuLeft;
      var menuHeight = oContextMenu.clientHeight;
      var menuWidth = oContextMenu.clientWidth;

      if ( IsExplorer() )
      {
         menuTop = getClientTop(elem) + event.offsetY;
         menuLeft = getClientLeft(elem) + event.offsetX;
      }
      else
      {
         menuTop = getClientTop(elem) - nScrollTop + event.offsetY;
         menuLeft = getClientLeft(elem) - nScrollLeft + event.offsetX;
      }
      
      // The viewport (nBodyHeight) is the area of the WX screen not
      // including the toolbar at the top.
      
      // if the menu can not be fully displayed from click position
      if (menuTop + menuHeight > nBodyHeight + offsetTop)
      {
          // move the menu up for menuHeight
          menuTop -= menuHeight;
      	
          // if the menu is too up to be fully displayed
          if (menuTop < offsetTop)
          {
              // set menuTop to offsetTop
              menuTop = offsetTop;
      	    
              // if there is enough room to display the menu
              // move the menu a little down
              if (nBodyHeight > menuHeight)
                  menuTop += (nBodyHeight - menuHeight) / 2;
          }
      }
      if (menuLeft + menuWidth > nBodyWidth)
      {
          menuLeft -= menuWidth;
      	
          if (menuLeft < 0)
          {
              menuLeft = 0;
      	    
              if (nBodyWidth > menuWidth)
                  menuLeft += (nBodyWidth - menuWidth) / 2;
          }
      }

      oContextMenu.style.pixelTop = menuTop;
      oContextMenu.style.pixelLeft = menuLeft;
   }
}

   
//This is a generic method used by grid controls that are derived from NavBaseGrid.  This method
//is called when the mouse moves over or out of a single row's area within the grid   
function OnMouseHover(oElement,bOverRow,bEnter)
{
   //_debugInspect(oElement.attributes);
   if (top.IsNav())
   {
      var oAttr = oElement.attributes.getNamedItem("isSelected");
      if (oAttr != null)
         oElement.isSelected = oAttr.nodeValue;
   }
      
   if (bOverRow)
   {
      if (bEnter)
      {
         if (oElement.style.backgroundColor == "#e0e0e0")
            oElement.isSelected = "0";
            
         oElement.style.backgroundColor  = "#ffff99"
         oElement.style.cursor='pointer'         
      }
      else
      {
         if (oElement.isSelected == "1")
            oElement.style.backgroundColor = "#6699cc"
         else
            oElement.style.backgroundColor = "#e0e0e0"
      }
   }
   else
   {
      if (bEnter)
      {
         oElement.style.backgroundColor = "#6699cc"
         oElement.style.cursor='pointer'         
      }
      else
      {
         if (oElement.innerText != "")
            oElement.style.backgroundColor = "#2e4a79"
      }
   }            
}            

function OnCheckRow(Evt,oElement)
{
   if (typeof oElement.style == "undefined" || typeof oElement.style == null)
      return;

   var isChecked = oElement.checked;
        
   if (isChecked == false)
   {
      window.document.forms[0].elements['CheckAll'].checked = false;
   }
   
   Evt.cancelBubble = true;
}      
   
function GetLocalizedText(stringId)
{
   return window.document.forms[0].elements[stringId].value;
}  


// Helper returns element regardless of browser type.
function getElement(id) 
{
   return document.getElementById ? document.getElementById(id) :document.all ? document.all(id) : null;
}


//
// Calender Support
// ==========================================================================
var bSkipCloseFieldIndexPopup = false;
var currentFieldIndexField = null;
function OnCalender(event, dateControlId, FieldName)
{
   if (CloseFieldIndexPopup())
   {
      bSkipCloseFieldIndexPopup = false;
      return;
   }
   
   currentFieldIndexField = getElement(dateControlId);
   var oQuery = new top.QueryBuilder();
   oQuery.setTarget("CalenderPopup.aspx");
   if (document.forms[0].elements["DataSource"] !=  null)
      oQuery["DataSource"] = document.forms[0].elements["DataSource"].value;
   else
   {
      var queryString = new QueryString(document);
      oQuery["DataSource"] = queryString["DataSource"];
   }
   if (document.forms[0].elements["AppName"] != null)
      oQuery["AppName"] = document.forms[0].elements["AppName"].value;
   else
   {
      if (document.forms[0].elements["AppId"] != null)
         oQuery["AppId"] = document.forms[0].elements["AppId"].value;
   }
   oQuery["FieldName"] = FieldName;
   oQuery["BoundControl"] = decodeURI(dateControlId);
   oQuery["CurrentDate"] = currentFieldIndexField.value;
   //window.open(oQuery.toString(),"Calender","width=212,height=188,resizable=no,scrollbars=no,titlebar=no,top=300,left=300",true)
   
   var sContents = "<IFRAME SRC='" + oQuery.toString() + "' width=212 height=184  name=calframe id=calframe>";
   var newIframe = document.createElement(sContents);
   
   //set to false to indicate that we don't wish to bubble this event to the parent.
	event.returnValue = false;
	if(event.stopPropagation)
	   event.stopPropagation();

   //Kill the browser's default action for this event (displaying its own context menu)
   if (event.preventDefault)
      event.preventDefault();
      
   var spanElem = getElement("fieldIdxGridPopup");
   
   var elem = event.srcElement;
   currentFieldIndexField.offsetParent.appendChild(spanElem);
   spanElem.style.display = "";
   elem.offsetParent.vAlign = "top";
   
   if ( typeof currentFieldIndexField.style.pixelWidth != "undefined" )
      currentFieldIndexField.style.pixelWidth = currentFieldIndexField.style.pixelWidth - 205 <= 0 ? 0 : currentFieldIndexField.style.pixelWidth - 205;
   
   currentFieldIndexField.style.backgroundColor = "LightSteelBlue";
   currentFieldIndexField.style.borderColor = "#dbd7d0";
   spanElem.style.pixelHeight = 184;
   spanElem.appendChild(newIframe);
   
   bSkipCloseFieldIndexPopup = true;
}


function getClientLeft(elem)
{
   var left = elem.offsetLeft;
   while (elem.offsetParent != null)
   {
      elem = elem.offsetParent;
      left = left + elem.offsetLeft - elem.scrollLeft;
   }
   return left;
}

function getClientTop(elem)
{
   var top = elem.offsetTop;
   while (elem.offsetParent != null)
   {
      elem = elem.offsetParent;
      top = top + elem.offsetTop - elem.scrollTop;
   }
   return top;
}

function setFieldDate()
{
   while (document.readyState != "complete")
   {
      setTimeout("setFieldDate()",50);
      return;
   }
   
   var elemId = document.forms[0].elements["BoundControl"].value;
   var fieldValue = document.forms[0].elements["DateString"].value
   while (elemId.indexOf(' ') != -1)
      elemId = elemId.replace(' ','+');
   elemId = encodeURI(elemId);
   var elem = window.top.getElement(elemId);
   elem.value = fieldValue;
   
   window.top.CloseFieldIndexPopup();
   bSkipCloseFieldIndexPopup = false;
   return;
}   
   


function CloseFieldIndexPopup()
{
   if (IsExplorer())
   {
      var spanElem = getElement("fieldIdxGridPopup");
      if (spanElem != null)
      {
         if (spanElem.children.length > 0)
         {
            var oCalender = spanElem.children(0);
            spanElem.removeChild(oCalender);
            spanElem.style.display = "none";
            if (currentFieldIndexField != null)
            {
               currentFieldIndexField.style.width = "100%";
               currentFieldIndexField.style.backgroundColor = "";
               currentFieldIndexField.style.borderColor = "";
            }
            return true;
         }
      }
    }
      
    return false;
}



//
// Index Pane Resize Support
// ==========================================================================
var g_beginResizeIndexPane = false;
var g_originalScreenX = 0;
var g_orginalWidth;
var g_oIndexPane = null;



function bodyMouseUp()
{
   if (g_beginResizeIndexPane)
   {
      g_beginResizeIndexPane = false
      window.document.releaseCapture();
   }
}



function SetMenuItemOverStyle()
{
   this.className = 'ContextMenuItemOver';
}

function SetMenuItemOutStyle()
{
   this.className = 'ContextMenuItem';
}	


function NavigateTo(url)
{
   window.location.replace(url);
}

function ___doPostBack(eventTarget,eventArgument)
{
   document.forms[0].onsubmit();
   __doPostBack(eventTarget, eventArgument) 
}

function DownloadFile(filePath)
{
   window.open(filePath,null,"width=1,height=1,resizable=yes,toolbar=no,menubar=no,status=no,top=0,left=0",true);
}


///////////////////////////////////////////////////////////////////////////////////
// INDEX PANE RESIZE LOGIC
///////////////////////////////////////////////////////////////////////////////////


var theobject = null; //This gets a value as soon as a resize start

function resizeObject() {
	this.el     = null; //pointer to the object
	this.elCP   = null; //pointer to the content object
	this.elIG   = null;
	this.dir    = "";      //type of current resize (n, s, e, w, ne, nw, se, sw)
	this.grabx = null;     //Some useful values
	this.graby = null;
	this.width = null;
	this.widthCP = null;
	this.height = null;
	this.left = null;
	this.top = null;
	this.isie = true;
}

function gripMouseDown(evt)
{
   doDown(evt);
}

//Find out what kind of resize! Return a string inlcluding the directions
function getDirection(evt, el) 
{
	var xPos, yPos, offset, dir;
	dir = "";

   if ( evt.offsetX == null )
   {
      yPos = document.body.scrollTop + evt.clientY;
      xPos = document.body.scrollLeft + evt.clientX;
   }
   else
   {
      xPos = evt.offsetX; // window.event.offsetX;
	   yPos = evt.offsetY; // window.event.offsetY;
	}
	
	offset = 8; //The distance from the edge in pixels

	if (yPos<offset) dir += "n";
	else if (yPos > el.offsetHeight-offset) dir += "s";
	if (xPos<offset) dir += "e";
	else if (xPos > el.offsetWidth-offset) dir += "w";

	return dir;
}

function doDown(evt) 
{
	var el = document.getElementById("PageLayout_IndexPanel");
	if (el == null) 
	{
		theobject = null;
		return;
	}		

   var elCP = document.getElementById("PageLayout_ContentContainer");
   var elIG = document.getElementById("PageLayout_IndexGripSeperator");

	dir = getDirection(evt, el);
	if (dir == "") return;

	theobject = new resizeObject();

	theobject.isie = IsExplorer()? true : false;
		
	theobject.el = el;
	theobject.elCP = elCP;
	theobject.elIG = elIG;
	theobject.dir = dir;
	theobject.grabx = evt.clientX; // window.event.clientX;
	theobject.graby = evt.clientY; // window.event.clientY;
	theobject.width = el.offsetWidth;
   if ( elCP == null )
      theobject.widthCP = 0;
   else 
      theobject.widthCP = elCP.offsetWidth;
	theobject.height = el.offsetHeight;
	theobject.left = el.offsetLeft;
	theobject.top = el.offsetTop;

   evt.returnValue = false; // window.event.returnValue = false;
	evt.cancelBubble = true; // window.event.cancelBubble = true;
}

function doUp() 
{
	if (theobject != null) 
	{
		//Post back to the server so that we can save the new width within the
      //user profile.
      hiddenField = document.getElementById("IndexPaneWidth"); 
      if ( theobject.el.style.pixelWidth == null )
         hiddenField.value = theobject.el.clientWidth;
      else
         hiddenField.value = theobject.el.style.pixelWidth;
      document.body.style.cursor = "";
      document.forms[0].submit();
      theobject = null;
	}
}

function doMove(evt) 
{
	var xMin, yMin;
	xMin = 8; //The smallest width possible
	yMin = 8; //             height

	
//Dragging starts here
	if(theobject != null) 
	{
	   if ( evt == null )
	      evt = window.event;
	      
      if ( theobject.isie )
      {
		   var ipwidth;

			ipwidth = Math.max(xMin, theobject.width + evt.clientX - theobject.grabx);
			theobject.el.parentNode.style.width = ipwidth;
			theobject.el.style.width = ipwidth;

         if ( theobject.widthCP > 0 )
         {
            var ipwidthCP;
            ipwidthCP = Math.max(xMin, theobject.widthCP - (evt.clientX - theobject.grabx));
   			theobject.elCP.parentNode.style.width = ipwidthCP;
			   theobject.elCP.style.width = ipwidthCP;
			}
      }
      else
      {
		   var beforeLeft = 0;
		   var afterLeft = 1;
		   if ( theobject.elIG != null )
		      beforeLeft = theobject.elIG.offsetLeft;
			var oldwidthP = theobject.el.parentNode.style.width;
			var oldwidth = theobject.el.style.width;
			var ipwidth = Math.max(xMin, theobject.width + evt.clientX - theobject.grabx);
			theobject.el.parentNode.style.width = ipwidth;
  			theobject.el.style.width = ipwidth;
		   if ( theobject.elIG != null )
		      afterLeft = theobject.elIG.offsetLeft;
         if ( afterLeft != beforeLeft )
         {
            if ( theobject.widthCP > 0 )
            {
               ipwidthCP = Math.max(xMin, theobject.widthCP - (evt.clientX - theobject.grabx));
   			   theobject.elCP.parentNode.style.width = ipwidthCP;
   		      theobject.elCP.style.width = ipwidthCP;
   		   }
         }
         else
         {
			   theobject.el.parentNode.style.width = oldwidthP;
            theobject.el.style.width = oldwidth;
         }
      }
	
		if (dir.indexOf("s") != -1)
			theobject.el.style.height = Math.max(yMin, theobject.height + evt.clientY - theobject.graby);		

		if (dir.indexOf("n") != -1) 
		{
			theobject.el.style.top = Math.min(theobject.top + evt.clientY - theobject.graby, theobject.top + theobject.height - yMin);
			theobject.el.style.height = Math.max(yMin, theobject.height - evt.clientY + theobject.graby);
		}
		
		evt.returnValue = false;
		evt.cancelBubble = true;
	} 
}


function getReal(el, type, value) 
{
	temp = el;
	while ((temp != null) && (temp.tagName != "BODY")) 
	{
		if (eval("temp." + type) == value) 
		{
			el = temp;
			return el;
		}
		temp = temp.parentElement;
	}
	return el;
}

function onSilverlightError(sender, args) 
{
    var appSource = "";
    if (sender != null && sender != 0) {
        appSource = sender.getHost().Source;
    }
    var errorType = args.ErrorType;
    var iErrorCode = args.ErrorCode;

    var errMsg = "Unhandled Error in Silverlight 2 Application " + appSource + "\n";

    errMsg += "Code: " + iErrorCode + "    \n";
    errMsg += "Category: " + errorType + "       \n";
    errMsg += "Message: " + args.ErrorMessage + "     \n";

    if (errorType == "ParserError") {
        errMsg += "File: " + args.xamlFile + "     \n";
        errMsg += "Line: " + args.lineNumber + "     \n";
        errMsg += "Position: " + args.charPosition + "     \n";
    }
    else if (errorType == "RuntimeError") {
        if (args.lineNumber != 0) {
            errMsg += "Line: " + args.lineNumber + "     \n";
            errMsg += "Position: " + args.charPosition + "     \n";
        }
        errMsg += "MethodName: " + args.methodName + "     \n";
    }

    throw new Error(errMsg);
}

document.onmouseup   = doUp;
document.onmousemove = doMove;

// Bring the window to foreground
window.focus();