﻿//-----------------------------------------------------------------------------
// XUI
//
// Copyright 2005-2010 - Xcential Group LLC.
//
//-----------------------------------------------------------------------------

//=============================================================================
// Constructor

function XUI(
   elementOrId,
   create
)
{
   elementOrId = (elementOrId == null) ? null : elementOrId;
   create = (create == null) ? true : false;

   if (create)
      return new XUI(elementOrId, false);

   //--------------------------------------------------------------------------
   // Private Interface

   //--------------------------------------------------------------------------
   // Privileged Interface

   this.valueOf = function()
   {

      return oElement;
   }

   //--------------------------------------------------------------------------

   this.setObjectValue = function(
      elementOrId
   )
   {
      elementOrId = (elementOrId == null) ? null : elementOrId;

      var oElement = XUI.getElementFrom(elementOrId);

      return oElement;
   }

   //--------------------------------------------------------------------------
   // Initialization

   var oElement = this.setObjectValue(elementOrId);

}

XUI.ClassName = "XUI";

//=============================================================================
// Static Interface

XUI.NAMESPACE_URI = "http://www.xcential.com/schemas/2006/xui";
XUI.PREFERRED_PREFIX = "xui";

XUI.KEY_BACKSPACE = 8;
XUI.KEY_ENTER     = 13;
XUI.KEY_ESC       = 27
XUI.KEY_Y         = 89;

XUI.INLINE_BLOCK_DISPLAY = "inline-block";
XUI.BLOCK_DISPLAY        = (!XApp.isBrowser("MSIE"))   ? "block"           : "block";
XUI.TABLE_DISPLAY        = (!XApp.isBrowser("MSIE"))   ? "table"           : "block";
XUI.TABLE_ROW_DISPLAY    = (!XApp.isBrowser("MSIE"))   ? "table-row"       : "block";
XUI.TABLE_CELL_DISPLAY   = (!XApp.isBrowser("MSIE"))   ? "table-cell"      : "block";
XUI.HIDDEN_DISPLAY       = "none";

XUI.FORCE = true;
XUI.SET_FOCUS = true;
XUI.PROMPT = true;
XUI.IF_DIFFERENT = true;
XUI.EXPAND = true;

XUI.TRAVERSE_FRAMES = true;

XUI.SHOW = "show";
XUI.HIDE = "hide";

//-----------------------------------------------------------------------------

// Note: By attaching a function to this, it is possible to track when items
//       are opened or closed.

XUI.recordChanges = null;

//-----------------------------------------------------------------------------
// Event Handlers

XUI.onHighlight     = null;
XUI.onUnhighlight   = null;
XUI.onBrowse        = null;
XUI.onShowContent   = null;
XUI.onHideContent   = null;
XUI.onToggleContent = null;
XUI.onToggleHelp    = null;
XUI.onKeyDown       = null;
XUI.onLinkTo        = null;
XUI.onGrabPermalink = null;
XUI.onShowPopup     = null;
XUI.onHidePopup     = null;
XUI.onCancelEvent   = null;

//-----------------------------------------------------------------------------

XUI.isArray = function(
   element
)
{

   try
   {
      if (element.length > 1)
         return true;
   }
   catch (error)
   {
      // Do not report error
   }

   return false;
}

//-----------------------------------------------------------------------------

XUI.getElementFrom = function(
   elementOrId
)
{

   // Note: Be careful, a single option input will appear as as array - hence
   //       the check for id in addition to the isArray test.

   var element = null;

   if (elementOrId == null)
      return null;
   else if (typeof(elementOrId) == "string")
   {
      var id = elementOrId;
      var context = document;
      if ((/\//).test(id))
      {
         while (XMatch(id, /\//))
         {
            var contextId = XMatch.leftContext;
            context = context.getElementById(contextId);
            if (!context)
               return null;
            id = XMatch.rightContext;
         }
      }
      element = context.getElementById(id);
      if (element && element.id == null && element.length > 0 && XUI.isArray(element))
         element = element[0];
   }
   else
      element = elementOrId;

   return element;
}

//-----------------------------------------------------------------------------

XUI.elementExists = function(
   id
)
{

   try
   {
      var element = $(id);
   }
   catch (error)
   {
      element = null;
   }

   return (element != null) ? true : false;
}

//-----------------------------------------------------------------------------

XUI.createOptionSetting = function(
   text,
   value,
   className
)
{
   value = (value == null) ? text : value;
   className = (className == null) ? null : className;

   var optionSetting = new Array();
   optionSetting.text = text;
   optionSetting.value = value;
   optionSetting.className = className;

   return optionSetting;
}

//-----------------------------------------------------------------------------

XUI.getContentEditor = function(
   event
)
{

   var contentEditor = event.srcElement;
   if (contentEditor == null || (contentEditor.localName && contentEditor.localName.toLowerCase() == "body"))
   {
      contentEditor = event.currentTarget;
      if (!contentEditor.tagName)
      {
         var contentWindow = event.currentTarget;
         if (contentWindow && XMatch(contentWindow.location.toString(), /[\&\?]id=([^\&]*)/))
            contentEditor = $(XMatch.matches[1] + ".editor");
      }
   }
   else if (contentEditor.frameElement)
   {
      contentEditor = contentEditor.frameElement;
   }
   else if (contentEditor.nodeType == XNode.NODE_DOCUMENT)
   {
      contentEditor = contentEditor.defaultView.frameElement;
   }

   if (XString(contentEditor.getAttribute("id")).isNothing())
       contentEditor = null;

   return XUI(contentEditor);
}

//-----------------------------------------------------------------------------

XUI.getAbsoluteTop = function(
   elementOrId,
   traverseFrames,
   castAs
)
{
   castAs = (castAs == null) ? null : castAs;
   traverseFrames = (traverseFrames == null) ? false : traverseFrames;

   if (elementOrId == null)
      return 0;

   var element = (typeof(elementOrId) == "string") ? $(elementOrId) : elementOrId;

   var absoluteTop = null;
   if (element)
   {
      absoluteTop = (element.offsetTop) ? element.offsetTop : 0;
      var offsetParent = (element.offsetParent) ? element.offsetParent : (traverseFrames && element.frameElement) ? element.frameElement : null;
      while (offsetParent)
      {
         absoluteTop += (offsetParent.offsetTop) ? offsetParent.offsetTop : 0;
         var ownerDocument = offsetParent.ownerDocument;
         offsetParent = offsetParent.offsetParent;
         if (!offsetParent && traverseFrames)
         {
            var parentWindow = (XApp.isBrowser("MSIE")) ?  ownerDocument.parentWindow : ownerDocument.defaultView;
            if (parentWindow.frameElement)
            {
               offsetParent = parentWindow.frameElement;
               var scrollTop = (XApp.isBrowser("MSIE")) ? ownerDocument.documentElement.scrollTop : parentWindow.pageYOffset;
               absoluteTop = absoluteTop - scrollTop;
            }
         }
      }
   }

   return (absoluteTop == null) ? null : (castAs == null) ? absoluteTop : castAs(absoluteTop);
}

//-----------------------------------------------------------------------------

XUI.getAbsoluteLeft = function(
   elementOrId,
   traverseFrames,
   castAs
)
{
   castAs = (castAs == null) ? null : castAs;
   traverseFrames = (traverseFrames == null) ? false : traverseFrames;

   if (elementOrId == null)
      return 0;

   var element = (typeof(elementOrId) == "string") ? $(elementOrId) : elementOrId;

   var absoluteLeft = null;
   if (element)
   {
      absoluteLeft = (element.offsetLeft) ? element.offsetLeft : 0;
      var offsetParent = (element.offsetParent) ? element.offsetParent : (traverseFrames && element.frameElement) ? element.frameElement : null;
      while (offsetParent)
      {
         absoluteLeft += (offsetParent.offsetLeft) ? offsetParent.offsetLeft : 0;
         var ownerDocument = offsetParent.ownerDocument;
         offsetParent = offsetParent.offsetParent;
         if (!offsetParent && traverseFrames)
         {
            var parentWindow = (XApp.isBrowser("MSIE")) ?  ownerDocument.parentWindow : ownerDocument.defaultView;
            if (parentWindow.frameElement)
            {
               offsetParent = parentWindow.frameElement;
               var scrollLeft = (XApp.isBrowser("MSIE")) ? ownerDocument.documentElement.scrollLeft : parentWindow.pageXOffset;
               absoluteLeft = absoluteLeft - scrollLeft;
            }
         }
      }
   }

   return (absoluteLeft == null) ? null : (castAs == null) ? absoluteLeft : castAs(absoluteLeft);
}

//-----------------------------------------------------------------------------

XUI.getWidth = function(
   elementOrId,
   castAs
)
{
   castAs = (castAs == null) ? null : castAs;

   if (elementOrId == null)
      return 0;

   var element = (typeof(elementOrId) == "string") ? $(elementOrId) : elementOrId;

   var width = null;
   if (element)
   {
      width = element.offsetWidth;
   }

   return (width == null) ? null : (castAs == null) ? width : castAs(width);
}

//-----------------------------------------------------------------------------

XUI.getHeight = function(
   elementOrId,
   castAs
)
{
   castAs = (castAs == null) ? null : castAs;

   if (elementOrId == null)
      return 0;

   var element = (typeof(elementOrId) == "string") ? $(elementOrId) : elementOrId;

   var height = null;
   if (element)
   {
      height = element.offsetHeight;
   }

   return (height == null) ? null : (castAs == null) ? height : castAs(height);
}

//-----------------------------------------------------------------------------

XUI.browse = function(
   ref,
   gotoId,
   highlightWordsText
)
{
   ref = (ref == null) ? null : ref.toString();
   gotoId = (gotoId == null) ? null : gotoId;
   highlightWordsText = (highlightWordsText == null) ? null : highlightWordsText;


   if (ref)
   {
      if (window.parent && window.parent.browse)
         window.parent.browse(ref, gotoId, highlightWordsText);
      else
      {
         var showBanner = XClient.getArg("showBanner", true);

         var xRef = XRef(ref);
         var url = "/app/pkgs/" + xRef.getModel() + "/Retrieve.asp?ref=" + encodeURIComponent(xRef.setFormat("html")) +
            "&resolveIncludes=yes" +
            "&showBanner=" + ((showBanner) ? "yes" : "no");
         window.location = url;
      }
   }

}

//-----------------------------------------------------------------------------

XUI.showVideo = function(
   ref,
   newWindow
)
{
   newWindow = (newWindow == null) ? null : newWindow;

   var width = 500;
   var height = (width * 0.75) + ((window.navigator.platform == "Win32") ? 50 : 18);


   var videoPlayerRef = "/app/pkgs/xfw/video/ShowVideo.asp";
   videoPlayerRef += "?videoRef=" + encodeURIComponent(ref);
   videoPlayerRef += XChar.AMP + "width=" + width;
   videoPlayerRef += XChar.AMP + "height=" + height;

   var params = "";
   params += "width=" + width + ",";
   params += "height=" + height + ",";
   params += "toolbar=no,";
   params += "menubar=no,";
   params += "scrollbars=no,";
   params += "titlebar=no,";
   params += "status=no,";
   params += "resizable=no";
   XUI.openWindow(videoPlayerRef, "_blank", params);

}

//-----------------------------------------------------------------------------

XUI.grabPermalink = function(
   source,
   linkingTool
)
{
   linkingTool = (linkingTool == null) ? "linking tool" : linkingTool;

   var sourceRef = (typeof(source) == "string") ? source : source.getSrc();

   if (!(/^http:/).test(sourceRef) && !(/^urn:/).test(sourceRef))
      sourceRef = XApp.getDomainURL() + sourceRef;

   // Attach the memberId and memberCode if the reference is within this domain
   if ((RegExp(XApp.getDomainURL())).test(sourceRef))
   {
      var sourceXRef = XRef(sourceRef);
      var memberId = sourceXRef.getArg("memberId");
      var memberCode = sourceXRef.getArg("memberCode");
      if (XString(memberId).isNothing() || XString(memberCode).isNothing())
      {
         var memberInfo = XClient.getCookie("memberInfo");
         if (memberInfo && memberInfo.length > 0)
         {
            var currentMemberId = null;
            var currentMemberCode = null;
            for (var i=0; i<memberInfo.length; i++)
            {
               switch (memberInfo[i][0])
               {
                  case "memberId":
                     currentMemberId = memberInfo[i][1];
                     break;
                  case "memberCode":
                     currentMemberCode = memberInfo[i][1];
                     break;
               }
               if (currentMemberId && currentMemberCode)
               {
                  if (XString(memberId).isNothing() || memberId == currentMemberId)
                  {
                     var format = sourceXRef.getArg("format"); // Keep format at the end of the arg list
                     sourceXRef.delArg("format");
                     sourceXRef.setArg("memberId", currentMemberId);
                     sourceXRef.setArg("memberCode", currentMemberCode);
                     if (format)
                        sourceXRef.setArg("format", format);
                  }
                  break;
               }
            }
         }
      }
      sourceRef = sourceXRef.toString();
   }

   var clipboardUsed = false;
   switch (XApp.browserName)
   {
      case "MSIE":
         window.clipboardData.clearData();
         window.clipboardData.setData("Text", sourceRef);
         clipboardUsed = true;
         break;
      case "Firefox":
         try
         {
            window.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
            clipboardHelper.copyString(sourceRef);
            clipboardUsed = true;
         }
         catch (error)
         {
            window.prompt("Copy and paste the link shown below:", sourceRef);
         }
         break;
      case "Safari":
      case "Chrome":
      default:
         window.prompt("Copy and paste the link shown below:", sourceRef);
         break;
   }
   if (clipboardUsed)
      window.alert("A permalink (URL) to this document has been placed in your clipboard. Paste it into your " + linkingTool + ".");

}

//-----------------------------------------------------------------------------

XUI.openWindow = function(
   url,
   target,
   params
)
{
   target = (target == null) ? null : target;
   params = (params == null) ? null : params;

   var win = window.open(url, target, params);

   if (win === null)
   {
      window.alert("A popup window was blocked. Please check your popup blocker.");
   }
   else if (typeof(win) == "undefined")
   {
      window.alert("A popup window was blocked. Please check your popup blocker.");
   }
   else if (win && win.closed)
   {
      window.alert("A popup window may have been blocked. Please check your popup blocker.");
   }

   return win;
}

//=============================================================================
// Event Handlers

XUI.doHighlight = function(
   event,
   id
)
{
   event = (event == null) ? window.event : event;

   var items = $(id);
   if (items != null)
   {
      items = (items.length == null) ? [items] : items;
      for (var i = 0; i<items.length; i++)
      {
         var item = items[i];
         switch (item.tagName.toLowerCase())
         {
            case "img":
               var img = item;
               var imgSrc = img.src;
               var extension = "";
               if (XMatch(imgSrc, /^(.*)(\.[^\.]+)$/))
               {
                  imgSrc = XMatch.matches[1];
                  extension = XMatch.matches[2];
               }
               img.src = imgSrc.replace(/\.Highlight$/i, "") + ".Highlight" + extension;
               break;
            default:
               var className = item.className;
               item.className = className.replace(/\-Highlight$/i, "") + "-Highlight";
               if (item.style.backgroundColor != "")
               {
                  item.setAttribute("restoreBackgroundColor", item.style.backgroundColor);
                  item.style.backgroundColor = "";
               }
               break;
         }
      }
   }

   if (XUI.onHighlight)
      XUI.onHighlight(event, id);

}

//-----------------------------------------------------------------------------

XUI.doUnhighlight = function(
   event,
   id
)
{
   event = (event == null) ? window.event : event;

   var items = $(id);
   if (items != null)
   {
      items = (items.length == null) ? [items] : items;
      for (var i = 0; i<items.length; i++)
      {
         var item = items[i];
         switch (item.tagName.toLowerCase())
         {
            case "img":
               var img = item;
               var imgSrc = img.src;
               var extension = "";
               if (XMatch(imgSrc, /^(.*)(\.[^\.]+)$/))
               {
                  imgSrc = XMatch.matches[1];
                  extension = XMatch.matches[2];
               }
               img.src = imgSrc.replace(/\.Highlight$/i, "") + extension;
               break;
            default:
               var className = item.className;
               item.className = className.replace(/\-Highlight$/i, "");
               item.style.backgroundColor = item.getAttribute("restoreBackgroundColor")
               break;
         }
      }
   }

   if (XUI.onUnhighlight)
      XUI.onUnhighlight(event, id);

}

//-----------------------------------------------------------------------------

XUI.doBrowse = function(
   event,
   ref,
   gotoId,
   highlightWordsText
)
{
   event = (event == null) ? window.event : event;
   ref = (ref == null) ? null : ref.toString();
   gotoId = (gotoId == null) ? null : gotoId;
   highlightWordsText = (highlightWordsText == null) ? null : highlightWordsText;

   try
   {

      XUI.browse(ref, gotoId, highlightWordsText);

      if (XUI.onBrowse)
         XUI.onBrowse(event, ref, gotoId, highlightWordsText);

   }
   catch (error)
   {
      XApp.logEvent(XApp.EVENT_ERROR, error);
      XMsg.alert(error);
   }

   if (event)
      event.cancelBubble = true;

}

//-----------------------------------------------------------------------------

XUI.contentShowing = new Array();

XUI.doShowContent = function(
   event,
   id
)
{
   event = (event == null) ? window.event : event;

   try
   {
      XUI(id + ".expandIcon").hide();
      XUI(id + ".collapseIcon").show(XUI.INLINE_BLOCK_DISPLAY);
      XUI(id + ".summary").hide();
      XUI(id + ".content").show();

      if (XUI.onShowContent)
         XUI.onShowContent(event, id);
   }
   catch (error)
   {
      XApp.logEvent(XApp.EVENT_ERROR, error);
      XMsg.alert(error);
   }

   if (XUI.recordChanges)
      XUI.recordChanges(id, XUI.SHOW);

   if (event)
      event.cancelBubble = true;

}

//-----------------------------------------------------------------------------

XUI.doHideContent = function(
   event,
   id
)
{
   event = (event == null) ? window.event : event;

   try
   {
      XUI(id + ".expandIcon").show(XUI.INLINE_BLOCK_DISPLAY);
      XUI(id + ".collapseIcon").hide();
      XUI(id + ".summary").show();
      XUI(id + ".content").hide();

      if (XUI.onHideContent)
         XUI.onHideContent(event, id);
   }
   catch (error)
   {
      XApp.logEvent(XApp.EVENT_ERROR, error);
      XMsg.alert(error);
   }

   if (XUI.recordChanges)
      XUI.recordChanges(id, XUI.HIDE);

   if (event)
      event.cancelBubble = true;

}

//-----------------------------------------------------------------------------

XUI.doToggleContent = function(
   event,
   id
)
{
   event = (event == null) ? window.event : event;

   try
   {
      if (XUI(id + ".expandIcon").isVisible())
         XUI.doShowContent(event, id);
      else if (XUI(id + ".collapseIcon").isVisible())
         XUI.doHideContent(event, id);

      if (XUI.onToggleContent)
         XUI.onToggleContent(event, id);
   }
   catch (error)
   {
      XApp.logEvent(XApp.EVENT_ERROR, error);
      XMsg.alert(error);
   }
}

//-----------------------------------------------------------------------------

XUI.doToggleHelp = function(
   event,
   id
)
{
   event = (event == null) ? window.event : event;

   try
   {

      var help = XUI(id);
      var helpShowIcon = XUI(id + ".showDetailsIcon");
      var helpHideIcon = XUI(id + ".hideDetailsIcon");
      if (help.exists())
      {
         if (help.getRuntimeStyle("display") == "block")
         {
            help.setRuntimeStyle("display", "none");
            helpShowIcon.setRuntimeStyle("display", "inline");
            helpHideIcon.setRuntimeStyle("display", "none");
         }
         else
         {
            help.setRuntimeStyle("display", "block");
            helpShowIcon.setRuntimeStyle("display", "none");
            helpHideIcon.setRuntimeStyle("display", "inline");
         }
      }

      if (XUI.onToggleHelp)
         XUI.onToggleHelp(event, id);
   }
   catch (error)
   {
      XApp.logEvent(XApp.EVENT_ERROR, error);
      XMsg.alert(error);
   }

   if (event)
      event.cancelBubble = true;

}

//-----------------------------------------------------------------------------

XUI.doKeyDown = function(
   event,
   idOrAction,
   contextId
)
{
   event = (event == null) ? window.event : event;
   contextId = (contextId == null) ? null : contextId;

   if (typeof(idOrAction) == "string")
   {
      var id = idOrAction;
      var element = $(id);
      if (element)
      {
         var keyCode = event.keyCode;
         if (keyCode == XUI.KEY_ENTER)
         {
            // Note: Chrome and Safari do not fully support click methods and events
            if (XApp.isBrowser("Safari") || XApp.isBrowser("Chrome"))
            {
               var onClick = element.getAttribute("onclick");
               if (XString(onClick).isSomething())
                  eval(onClick);
            }
            else if (element.click && typeof(element.click) == "function")
            {
               if (element.fireEvent)
                  element.fireEvent("onclick");
               else
                  element.click();
            }
            else
            {
               var onClick = element.getAttribute("onclick");
               if (XString(onClick).isSomething())
                  eval(onClick);
            }
         }
      }
   }
   else
   {
      var action = idOrAction;
      try
      {
         var keyCode = event.keyCode;
         if (keyCode == XUI.KEY_ENTER && action)
         {
            if (contextId != null)
               action(event, contextId);
            else
               action(event);
         }
      }
      catch (error)
      {}
   }

   if (XUI.onKeyDown)
      XUI.onKeyDown(event, idOrAction, contextId);

}

//-----------------------------------------------------------------------------

XUI.doLinkTo = function(
   event,
   ref,
   windowName,
   width,
   height,
   scrollbars,
   resizable
)
{
   ref = (ref == null) ? null : ref.toString();
   windowName = (windowName == null) ? "_blank" : windowName;
   width = (width == null) ? null : width;
   height = (height == null) ? null : height;
   scrollbars = (scrollbars == null) ? true : scrollbars;
   resizable = (resizable == null) ? true : resizable;

   try
   {
      if (ref)
      {
         if ((/\.asx/i).test(ref))
            window.location = ref;
         else
         {
            var params = "";
            params += (width != null) ? "width=" + width + "," : "";
            params += (height != null) ? "height=" + height + "," : "";
            params += (windowName != "_blank") ? "toolbar=no," : "toolbar=yes,";
            params += (windowName != "_blank") ? "menubar=no," : "menubar=yes,";
            params += (windowName != "_blank") ? "titlebar=no," : "titlebar=yes,";
            params += (windowName != "_blank") ? "location=no," : "location=yes,";
            params += (windowName != "_blank") ? "status=no," : "status=yes,";
            params += (scrollbars) ? "scrollbars=yes," : "scrollbars=no,";
            params += (resizable) ? "resizable=yes," : "resizable=no,";
            XUI.openWindow(ref, windowName, (XString(params).isSomething()) ? params : null);
         }

      }

      if (XUI.onLinkTo)
         XUI.onLinkTo(event, ref, windowName, width, height, scrollbars, resizable);

   }
   catch (error)
   {
      XApp.logEvent(XApp.EVENT_ERROR, error);
      XMsg.alert(error);
   }

   if (event)
      event.cancelBubble = true;

}

//-----------------------------------------------------------------------------

XUI.doGrabPermalink = function(
   event,
   source,
   linkingTool
)
{
   event = (event == null) ? window.event : event;
   linkingTool = (linkingTool == null) ? "linking tool" : linkingTool;

   try
   {

      var walker = self;
      while (walker && !walker.grabPermalink && walker.parent != walker)
         walker = walker.parent;

      if (walker && walker.grabPermalink)
         walker.grabPermalink(source, linkingTool);
      else
         XUI.grabPermalink(source, linkingTool);

      if (XUI.onGrabPermalink)
         XUI.onGrabPermalink(event, source);

   }
   catch (error)
   {
      XApp.logEvent(XApp.EVENT_ERROR, error);
      XMsg.alert(error);
   }

   if (event)
      event.cancelBubble = true;

}

//-----------------------------------------------------------------------------

XUI.doShowPopup = function(
   event,
   controlId,
   contentId,
   width,
   height
)
{
   contentId = (contentId == null) ? controlId : contentId;
   width = (width == null) ? null : width;
   height = (height == null) ? null : height;

   try
   {

      var popupNoteElememt = $(contentId + ".note");
      if (popupNoteElememt)
      {
         var walker = self;
         while (walker && !walker.showPopup && walker.parent != walker)
            walker = walker.parent;

         if (walker && walker.showPopup)
         {
            var x = ((walker != self) ? XUI.getAbsoluteLeft(self, XUI.TRAVERSE_FRAMES) : 0) + event.clientX;
            var y = ((walker != self) ? XUI.getAbsoluteTop(self, XUI.TRAVERSE_FRAMES) : 0) + event.clientY;
            var popupNote = popupNoteElememt.innerHTML;
            if (XString(popupNote).trim().length == 0)
            {
               popupNote = popupNoteElememt.getAttribute("title");
            }
            if (popupNote && XString(popupNote).trim().length > 0)
               popupNote = "<div class=\"Message Popup Note\">" + popupNote + "</div>";
            walker.showPopup(controlId, null, popupNote, x, y, width, height);
         }

      }

      if (XUI.onShowPopup)
         XUI.onShowPopup(event, controlId, contentId, width, height);

   }
   catch (error)
   {
      XApp.logEvent(XApp.EVENT_ERROR, error);
      XMsg.alert(error);
   }

}

//-----------------------------------------------------------------------------

XUI.doHidePopup = function(
   event,
   controlId
)
{

   try
   {

      var walker = self;
      while (walker && !walker.hidePopup && walker.parent != walker)
         walker = walker.parent;

      if (walker && walker.hidePopup)
         walker.hidePopup(controlId);

      if (XUI.onHidePopup)
         XUI.onHidePopup(event, controlId);

   }
   catch (error)
   {
      XApp.logEvent(XApp.EVENT_ERROR, error);
      XMsg.alert(error);
   }

}

//-----------------------------------------------------------------------------

XUI.doCancelEvent = function(
   event
)
{
   event = (event == null) ? window.event : event;

   if (XUI.onCancelEvent)
      XUI.onCancelEvent(event);

   if (event)
      event.cancelBubble = true;

}

//-----------------------------------------------------------------------------

XUI.init = function()
{

   // Mozilla does not implement the click method on anchors, so we add it here.
   if (XApp.isBrowser("Firefox"))
   {
      HTMLAnchorElement.prototype.click = function()
      {
         var event = this.ownerDocument.createEvent('MouseEvent');
         event.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
         this.dispatchEvent(event);
      }
   }

}

XUI.init();

//=============================================================================
// Public Interface

XUI.prototype.exists = function()
{

   var element = this.valueOf();

   return (element != null) ? true : false;
}

//-----------------------------------------------------------------------------

XUI.prototype.getElement = function()
{

   return this.valueOf()
}

//-----------------------------------------------------------------------------

XUI.prototype.isVisible = function()
{

   if (!this.exists())
      return false;

   return (this.getRuntimeStyle("display") != "none") ? true : false;
}

//-----------------------------------------------------------------------------

XUI.prototype.show = function(
   displayStyle
)
{
   displayStyle = (displayStyle == null) ? "block" : displayStyle;

   this.setRuntimeStyle("display", displayStyle);

}

//-----------------------------------------------------------------------------

XUI.prototype.hide = function()
{

   this.setRuntimeStyle("display", "none");

}

//-----------------------------------------------------------------------------

XUI.prototype.toText = function(
   castAs
)
{
   castAs = (castAs == null) ? null : castAs;

   var element = this.valueOf();
   if (element == null)
      return null;

   var text = null;
   if (element.textContent != null)
      text = element.textContent;
   else if (element.innerText!= null)
      text = element.innerText;

   return (text == null) ? null : (castAs == null) ? text : castAs(text);
}

//-----------------------------------------------------------------------------

XUI.prototype.setText = function(
   text
)
{

   var element = this.valueOf();
   if (element == null)
      throw XMsg("Element could not be found while setting text content.");

   if (element.textContent != null)
      element.textContent = text;
   else if (element.innerText != null)
      element.innerText = text;

}

//-----------------------------------------------------------------------------

XUI.prototype.getHtmlContent = function(
)
{

   var element = this.valueOf();
   if (element == null)
      return null;

   var htmlContent = element.innerHTML;

   return htmlContent;
}

//-----------------------------------------------------------------------------

XUI.prototype.setHtmlContent = function(
   htmlContent
)
{

   var element = this.valueOf();
   if (element == null)
      throw XMsg("Element could not be found while setting HTML content.");

   element.innerHTML = htmlContent;

}

//-----------------------------------------------------------------------------

XUI.prototype.getId = function()
{

   var element = this.valueOf();
   if (element == null)
      return null;

   return element.getAttribute("id");
}

//-----------------------------------------------------------------------------

XUI.prototype.getAttribute = function(
   name,
   defaultValue
)
{
   defaultValue = (defaultValue == null) ? null : defaultValue;

   var element = this.valueOf();
   if (element == null)
      return null;

   var attribute = element.getAttribute(name);

   return (attribute == null) ? defaultValue : attribute;
}

//-----------------------------------------------------------------------------

XUI.prototype.setAttribute = function(
   name,
   value
)
{

   var element = this.valueOf();
   if (element == null)
      return;

   element.setAttribute(name, value);

}

//-----------------------------------------------------------------------------

XUI.prototype.normalize = function(
   castAs,
   style
)
{
   castAs = (castAs == null) ? null : castAs;
   style = (style == null) ? null : style;

   if (!this.displaysTitle())
   {
      value = XString(this.getValue()).trim();
      if (castAs && value.length > 0)
      {
         var newValue = castAs(value).toString(style);
         value = ((/NaN/).test(newValue)) ? value : newValue;
      }

      this.setValue(value);
   }

}

//-----------------------------------------------------------------------------

XUI.prototype.setTitle = function(
   title,
   force
)
{
   title = (title == null) ? this.valueOf().title : title;
   force = (force == null) ? false : force;

   var element = this.valueOf();
   if (element == null)
      return;

   if (force || XString(this.getValue()).trim().length == 0)
   {
      if (this.getTagName() == "iframe")
      {
         var iframeBodies = $$$("body", element.contentWindow.document);
         if (iframeBodies.length > 0)
         {
            var iframeBody = iframeBodies[0];
            iframeBody.innerHTML = title;
            iframeBody.style.color = "#BBBBBB";
         }
      }
      else if (element.value != null)
         element.value = title;
      else
         this.setText(title);
      element.style.color = "#BBBBBB";
   }

}

//-----------------------------------------------------------------------------

XUI.prototype.displaysTitle = function()
{

   var element = this.valueOf();
   if (element == null)
      return false;

   var color = XUI(element).getCurrentStyle("color");
   color = color.toUpperCase().replace(/\s/g,"")

   return (color == "#BBBBBB" || color == "RGB(187,187,187)") ? true : false;
}

//-----------------------------------------------------------------------------

XUI.prototype.clearTitle = function(
   force,
   setFocus
)
{
   force = (force == null) ? false : force;
   setFocus = (setFocus == null) ? false : setFocus;

   var element = this.valueOf();
   if (element == null)
      return;

   if (this.displaysTitle() || force)
   {
      if (this.getTagName() == "iframe")
      {
         var iframeBodies = $$$("body", element.contentWindow.document);
         if (iframeBodies.length > 0)
         {
            var iframeBody = iframeBodies[0];
            iframeBody.innerHTML = "";
            iframeBody.style.color = "#000000";
         }
      }
      else if (element.value != null)
         element.value = "";
      else
         element.innerHTML = "";
      element.style.color = "#000000";
   }

   if (setFocus)
      element.focus();

}

//-----------------------------------------------------------------------------

XUI.prototype.setFlyoverText = function(
   text
)
{
   text = (text == null) ? this.valueOf().text : text;

   var element = this.valueOf();
   if (element == null)
      return;

   element.title = text;

}

//-----------------------------------------------------------------------------

XUI.prototype.getTagName = function()
{

   var element = this.valueOf();
   if (element == null)
      return null;

   return element.tagName.toLowerCase();
}

//-----------------------------------------------------------------------------

XUI.prototype.setValue = function(
   value,
   ifDifferent
)
{
   value = (value == null) ? "" : value;
   ifDifferent = (ifDifferent == null) ? false : ifDifferent;

   //--------------------------------------------------------------------------

   function normalizeTags(
      value
   )
   {

      var valueA = "";
      while (XMatch(value, /<[^>]+>/))
      {
         valueA += XMatch.leftContext;
         valueA += XMatch.lastMatch.toLowerCase();
         value = XMatch.rightContext;
      }
      valueA += value;

      return valueA;
   }

   //--------------------------------------------------------------------------

   function isDifferent(
      value1,
      value2
   )
   {
      value1 = (value1 == null) ? "" : value1.toLowerCase().replace(/[\r\n\s]+/g," ");
      value2 = (value2 == null) ? "" : value2.toLowerCase().replace(/[\r\n\s]+/g, " ");

      // Fudge around entities
      value1 = value1.replace(/\&.*;/gi, "");
      value2 = value2.replace(/\&.*;/gi, "");

      if (normalizeTags(value1) == normalizeTags(value2))
         return false;

      return true;
   }

   //--------------------------------------------------------------------------

   var element = this.valueOf();
   if (element == null)
      return;

   if (this.getTagName() == "iframe")
   {
      if (element.contentWindow)
      {
         var iframeBodies = $$$("body", element.contentWindow.document);
         if (iframeBodies.length > 0)
         {
            var iframeBody = iframeBodies[0];
            if (!ifDifferent || isDifferent(value, iframeBody.innerHTML))
               iframeBody.innerHTML = value;
            element.style.color = "#000000";
         }
      }
   }
   else if (this.getTagName() == "input" && element.type == "checkbox")
   {
      element.checked = XBoolean(value).toBoolean();
   }
   else if (element.value != null)
   {
      if (!ifDifferent || isDifferent(value, element.value))
         element.value = value;
      element.style.color = "#000000";
   }
   else
   {
      if (!ifDifferent || isDifferent(value, this.toText()))
      this.setText(value);
      element.style.color = "#000000";
   }

}

//-----------------------------------------------------------------------------

XUI.prototype.getValue = function(
   castAs
)
{
   castAs = (castAs == null) ? null : castAs;

   var element = this.valueOf();
   if (element == null)
      return null;

   var value = "";
   if (!this.displaysTitle())
   {
      if (this.getTagName() == "iframe")
      {
         var iframeBodies = $$$("body", element.contentWindow.document);
         if (iframeBodies.length > 0)
         {
            var iframeBody = iframeBodies[0];
            value = XUI(iframeBody).toText();
         }
      }
      else if (this.getTagName() == "input" && this.valueOf().type == "checkbox")
         value = (this.valueOf().checked) ? element.value : null;
      else if (element.value != null)
         value = element.value;
      else
         value = this.toText();
   }

   return (value == null) ? null : (castAs == null) ? value : castAs(value);
}

//-----------------------------------------------------------------------------

XUI.prototype.getInnerHTML = function()
{

   var element = this.valueOf();
   if (element == null)
      throw XMsg("Element could not be found while getting inner HTML content.");

   return element.innerHTML;
}

//-----------------------------------------------------------------------------

XUI.prototype.setInnerHTML = function(
   innerHTML
)
{

   var element = this.valueOf();
   if (element == null)
      throw XMsg("Element could not be found while setting inner HTML content.");

   element.innerHTML = innerHTML;

}

//-----------------------------------------------------------------------------

XUI.prototype.appendInnerHTML = function(
   innerHTML
)
{

   var element = this.valueOf();
   if (element == null)
      throw XMsg("Element could not be found while appending to inner HTML content.");

   element.innerHTML += innerHTML;
}

//-----------------------------------------------------------------------------

XUI.prototype.setOuterHTML = function(
   outerHTML
)
{
   outerHTML = (outerHTML == null) ? "" : outerHTML;

   var element = this.valueOf();
   if (element == null)
      throw XMsg("Element could not be found while setting outer HTML content.");

   if (element.outerHTML != null)
   {
      element.outerHTML = outerHTML;
   }
   else if (element.innerHTML != null)
   {
      var insertSpan = document.createElement("span");
      insertSpan.innerHTML = outerHTML;
      while (insertSpan.childNodes.length > 0)
      {
         var child = insertSpan.childNodes.item(0);
         insertSpan.removeChild(child);
         element.parentNode.insertBefore(child, element);
      }
      element.parentNode.removeChild(element);
   }
   else
      throw XMsg("Cannot set the outer HTML with this browser.");

}

//-----------------------------------------------------------------------------

XUI.prototype.getClass = function()
{

   var element = this.valueOf();
   if (element == null)
      return null;

   return element.className;
}

//-----------------------------------------------------------------------------

XUI.prototype.setClass = function(
   className
)
{

   var element = this.valueOf();
   if (element == null)
      return;

   element.className = className;

}

//-----------------------------------------------------------------------------

XUI.prototype.getCurrentStyle = function(
   styleName,
   defaultStyle
)
{
   defaultStyle = (defaultStyle == null) ? null : defaultStyle;

   var currentStyle = defaultStyle;

   var element = this.valueOf();
   if (element == null)
      return currentStyle;

   try
   {
      if (element.currentStyle != null)
         currentStyle = element.currentStyle[styleName];
   }
   catch (error)
   {
      currentStyle = null;
   }

   if (currentStyle == null)
   {
      if (document.defaultView != null && document.defaultView.getComputedStyle != null)
      {
         try
         {
            var cssStyleName = styleName.replace(/([A-Z])/g, "-$1").toLowerCase();
            var computedStyle = document.defaultView.getComputedStyle(element,null);
            if (computedStyle)
               currentStyle = computedStyle.getPropertyValue(cssStyleName);
         }
         catch (error)
         {
         }
      }
      if (currentStyle == null)
         currentStyle = element.style[styleName];
   }

   return currentStyle;
}

//-----------------------------------------------------------------------------

XUI.prototype.getStyle = function(
   styleName,
   defaultStyle
)
{
   defaultStyle = (defaultStyle == null) ? null : defaultStyle;

   var style = defaultStyle;

   var element = this.valueOf();
   if (element == null)
      return style;

   if (element.style != null)
      style = element.style[styleName];

   return style;
}

//-----------------------------------------------------------------------------

XUI.prototype.setStyle = function(
   styleName,
   value
)
{
   value = (value == null) ? null : value;

   var element = this.valueOf();
   if (element == null)
      return;

   if (element.style != null)
   {
      if (value != null)
         element.style[styleName] = value;
      else if (element.style.removeAttribute)
         element.style.removeAttribute(styleName);
      else
         element.style.removeProperty(styleName);
   }

}

//-----------------------------------------------------------------------------

XUI.prototype.getRuntimeStyle = function(
   styleName,
   defaultStyle
)
{
   defaultStyle = (defaultStyle == null) ? null : defaultStyle;

   var element = this.valueOf();
   if (element == null)
      return null;

   var runtimeStyle = null;

   if (element.runtimeStyle != null && XApp.isBrowser("MSIE",6.0,7.0))
      runtimeStyle = element.runtimeStyle[styleName];

   if (runtimeStyle == null || runtimeStyle == "")
      runtimeStyle = element.style[styleName];

   return (runtimeStyle == null || runtimeStyle == "") ? defaultStyle : runtimeStyle;
}

//-----------------------------------------------------------------------------

XUI.prototype.setRuntimeStyle = function(
   styleName,
   value
)
{
   value = (value == null) ? null : value;

   var element = this.valueOf();
   if (element == null)
      return;

   // Note: IE8 crashes when using runtimeStyle, so the use has been
   //       disabled for now.

   if (element.runtimeStyle != null && XApp.isBrowser("MSIE",6.0,7.0))
   {
      if (value != null)
         element.runtimeStyle[styleName] = value;
      else if (element.runtimeStyle[styleName] != '')
         element.runtimeStyle.removeAttribute(styleName);
   }
   else
   {
      if (value != null)
         element.style[styleName] = value;
      else if (element.style.removeAttribute)
         element.style.removeAttribute(styleName);
      else
         element.style.removeProperty(styleName);
   }

}

//-----------------------------------------------------------------------------

XUI.prototype.setRuntimeExpression = function(
   styleName,
   value
)
{
   value = (value == null) ? null : value;

   var element = this.valueOf()
   if (element == null)
      return;

   if (element.runtimeStyle != null && XApp.isBrowser("MSIE",6.0,7.0))
   {
      try
      {
         if (value != null)
         {
            try
            {
               element.style[styleName] = null; // Without this, there is an sometimes an 'unspecified error'
               element.runtimeStyle[styleName] = null; // Without this, there is sometimes an 'unspecified error'
               element.runtimeStyle.setExpression(styleName, value);
            }
            catch (error)
            {
               element.runtimeStyle[styleName] = null; // Without this, there is an 'unspecified error'
               element.runtimeStyle.setExpression(styleName, value);
            }
         }
         else if (element.runtimeStyle.getExpression(styleName) != '')
            element.runtimeStyle.removeExpression(styleName);
      }
      catch (error)
      {
         throw XMsg("Cannot set or unset CSS runtime expressions. Please disable compatibility view for this website if it is set in your browser. (Also, if this site is running in an intranet, check that compatibility view is not the default for intranets. This is an IE8+ option)", error);
      }
   }
   else
      throw XMsg("Style expressions cannot be set with this browser.");

}

//-----------------------------------------------------------------------------

XUI.prototype.getEnabled = function()
{

   var element = this.valueOf();
   if (element == null)
      return false;

   return (element.disabled) ? false : true;
}

//-----------------------------------------------------------------------------

XUI.prototype.setEnabled = function(
   enabled
)
{
   enabled = (enabled == null) ? true : enabled;

   var element = this.valueOf();
   if (element == null)
      return false;

   element.disabled = (enabled) ? false : true;

   return enabled;
}

//-----------------------------------------------------------------------------

XUI.prototype.setOptions = function(
   optionSettings
)
{
   optionSetting = (optionSettings == null) ? [] : optionSettings;

   var element = this.valueOf();
   if (element == null)
      return;

   if (this.getTagName() != "select")
      return;

   // Check to see if there are any changes - if not, don't reset
   if (element.options.length == optionSettings.length)
   {
      var identical = true;
      for (var i=0; i<element.options.length; i++)
      {
         var option = element.options.item(i);
         var optionSetting = optionSettings[i];
         if (option.text != optionSetting.text ||
             option.value != optionSetting.value ||
             ((XString(option.className).isSomething() || XString(optionSetting.className).isSomething()) &&
               option.className != optionSetting.className
             )
         )
         {
            identical = false;
            break;
         }
      }
      if (identical)
         return;
   }

   var currentValue = element.value;
   while (element.options.length > 0)
      element.remove(0);
   for (var i=0; i<optionSettings.length; i++)
   {
      var optionSetting = optionSettings[i];
      var option = document.createElement("option");
      element.options.add(option);
      option.text = optionSetting.text;
      option.value = optionSetting.value;
      option.className = (optionSetting.className != null) ? optionSetting.className : option.className;
      option.selected = (currentValue.toLowerCase() == option.value.toLowerCase()) ? true : false;
   }

}

//-----------------------------------------------------------------------------

XUI.prototype.fireEvent = function(
   eventName
)
{

   var element = this.valueOf()
   if (element == null)
      return;

   if (document.createEvent)
   {
      var event = document.createEvent('Event');
      event.initEvent(eventName, true, false);
      element.dispatchEvent(event);
   }
   else if (document.createEventObject)
   {
      element.fireEvent(eventName);
   }
   else
      throw XMsg("Custom events cannot be fired with this browser.");

}

//-----------------------------------------------------------------------------

XUI.prototype.getPixelHeight = function()
{

   var element = this.valueOf();
   if (element == null)
      return null;

   if (element.style.pixelHeight)
      return element.style.pixelHeight;
   else
      return element.offsetHeight;

}

//-----------------------------------------------------------------------------

XUI.prototype.getPixelWidth = function()
{

   var element = this.valueOf();
   if (element == null)
      return null;

   if (element.style.pixelWidth)
      return element.style.pixelWidth;
   else
      return element.offsetWidth;

}

//-----------------------------------------------------------------------------

XUI.prototype.getAbsoluteTop = function()
{

   var element = this.valueOf();
   if (element == null)
      return null;

   return XUI.getAbsoluteTop(element);
}

//-----------------------------------------------------------------------------

XUI.prototype.getAbsoluteLeft = function()
{

   var element = this.valueOf();
   if (element == null)
      return null;

   return XUI.getAbsoluteLeft(element);
}

//-----------------------------------------------------------------------------

XUI.prototype.getHeight = function()
{

   var element = this.valueOf();
   if (element == null)
      return null;

   return XUI.getHeight(element);
}

//-----------------------------------------------------------------------------

XUI.prototype.getWidth = function()
{

   var element = this.valueOf();
   if (element == null)
      return null;

   return XUI.getWidth(element);
}

//-----------------------------------------------------------------------------

XUI.prototype.prepareForSubmit = function(
   clearTitle
)
{
   clearTitle = (clearTitle == null) ? false : clearTitle;

   var element = this.valueOf();
   if (element == null)
      return;

   if (clearTitle || this.displaysTitle())
      this.setValue("");

}

//-----------------------------------------------------------------------------

XUI.prototype.isEditable = function()
{

   var element = this.valueOf();
   if (element == null)
      return;

   switch (this.getTagName())
   {
      case "iframe":
         var editDocument = element.contentWindow.document;
         if (editDocument.designMode != null)
            return (editDocument.designMode.toLowerCase() == "inherit") ? false : XBoolean(editDocument.designMode).toBoolean();
         else if (element.contentWindow.designMode != null)
            return XBoolean(element.contentWindow.designMode).toBoolean();
         else if (editDocument.body.contentEditable != null)
            return (editDocument.body.contentEditable.toLowerCase() == "inherit") ? false : XBoolean(editDocument.body.contentEditable).toBoolean();
         else
            return false;
         break;
      case "input":
         return false;
         break;
   }

   return false;
}

//-----------------------------------------------------------------------------

XUI.prototype.enableEditMode = function()
{

   var element = this.valueOf();
   if (element == null)
      return;

   if (this.getTagName() == "iframe" && element.contentWindow)
   {
      var editDocument = element.contentWindow.document;
      if (XApp.isBrowser("MSIE"))
         editDocument.body.contentEditable = true;
      else
      {
         if (editDocument.designMode != null)
            editDocument.designMode = "on";  // Using designMode in IE seems to clear the content
         else if (element.contentDocument.designMode != null)
            element.contentDocument.designMode = "on"; // Safari 1.3 - 2.0 only support setting contentDocument.designMode
      }
   }

}

//-----------------------------------------------------------------------------

XUI.prototype.disableEditMode = function()
{

   var element = this.valueOf();
   if (element == null)
      return;

   if (this.getTagName() == "iframe" && element.contentWindow)
   {
      var editDocument = element.contentWindow.document;
      if (XApp.isBrowser("MSIE"))
         editDocument.body.contentEditable = false;
      else
      {
         if (editDocument.designMode != null)
            editDocument.designMode = "off";  // Using designMode in IE seems to clear the content
         else if (element.contentDocument.designMode != null)
            element.contentDocument.designMode = "off"; // Safari 1.3 - 2.0 only support setting contentDocument.designMode
      }
   }

}

//-----------------------------------------------------------------------------

XUI.getPremiumNoticeHTML = function(
   style,
   backgroundColor,
   edgeColor
)
{
   style = (style == null) ? "block" : style;
   backgroundColor = (backgroundColor == null) ? "white" : XString(backgroundColor).toTitleCase();
   edgeColor = (edgeColor == null) ? "Blue" : XString(edgeColor).toTitleCase();

   var noticeHTML = "";
   switch (style)
   {
      case "block":
         noticeHTML += "<div class=\"PremiumNotice\" style=\"background-color: " + backgroundColor + ";\" id=\"premiumNotice\">\n";
         noticeHTML += "   <div class=\"TopLeftCorner-" + edgeColor + "\"></div>\n";
         noticeHTML += "   <div class=\"TopRightCorner-" + edgeColor + "\"></div>\n";
         noticeHTML += "   <div class=\"BottomLeftCorner-" + edgeColor + "\"></div>\n";
         noticeHTML += "   <div class=\"BottomRightCorner-" + edgeColor + "\"></div>\n";
         noticeHTML += "      PREMIUM FEATURE\n";
         noticeHTML += "</div>\n";
         break;
      case "inline":
         noticeHTML += "<span class=\"PremiumNoticeInline\" style=\"background-color: " + backgroundColor + ";\" id=\"premiumNotice\">\n";
         noticeHTML += "   PREMIUM FEATURE\n";
         noticeHTML += "</span>\n";
         break;
   }

   return noticeHTML;
}

//=============================================================================


